text
stringlengths
8
4.13M
use super::player::Player; use super::wizard::Wizard; use super::minion::Minion; use super::projectile::Projectile; use super::bonus::Bonus; use super::building::Building; use super::tree::Tree; #[derive(Clone, Debug, PartialEq)] pub struct World { pub tick_index: i32, pub tick_count: i32, pub width: f64, pub height: f64, pub players: Vec<Player>, pub wizards: Vec<Wizard>, pub minions: Vec<Minion>, pub projectiles: Vec<Projectile>, pub bonuses: Vec<Bonus>, pub buildings: Vec<Building>, pub trees: Vec<Tree>, }
use std::{cell::RefCell, collections::HashMap, net::SocketAddr, rc::Rc}; use naia_shared::StateMask; use crate::actors::actor_key::actor_key::ActorKey; use indexmap::IndexMap; #[derive(Debug)] pub struct MutHandler { actor_state_mask_list_map: HashMap<ActorKey, IndexMap<SocketAddr, Rc<RefCell<StateMask>>>>, } impl MutHandler { pub fn new() -> Rc<RefCell<MutHandler>> { Rc::new(RefCell::new(MutHandler { actor_state_mask_list_map: HashMap::new(), })) } pub fn mutate(&mut self, actor_key: &ActorKey, property_index: u8) { if let Some(state_mask_list) = self.actor_state_mask_list_map.get_mut(actor_key) { for (_, mask_ref) in state_mask_list.iter_mut() { mask_ref.borrow_mut().set_bit(property_index, true); } } } pub fn clear_state(&mut self, address: &SocketAddr, actor_key: &ActorKey) { if let Some(state_mask_list) = self.actor_state_mask_list_map.get_mut(actor_key) { if let Some(mask_ref) = state_mask_list.get(address) { mask_ref.borrow_mut().clear(); } } } pub fn set_state( &mut self, address: &SocketAddr, actor_key: &ActorKey, other_state: &StateMask, ) { if let Some(state_mask_list) = self.actor_state_mask_list_map.get_mut(actor_key) { if let Some(mask_ref) = state_mask_list.get(address) { mask_ref.borrow_mut().copy_contents(other_state); } } } pub fn register_actor(&mut self, actor_key: &ActorKey) { if self.actor_state_mask_list_map.contains_key(actor_key) { panic!("Actor cannot register with server more than once!"); } self.actor_state_mask_list_map .insert(*actor_key, IndexMap::new()); } pub fn deregister_actor(&mut self, actor_key: &ActorKey) { self.actor_state_mask_list_map.remove(actor_key); } pub fn register_mask( &mut self, address: &SocketAddr, actor_key: &ActorKey, mask: &Rc<RefCell<StateMask>>, ) { if let Some(state_mask_list) = self.actor_state_mask_list_map.get_mut(actor_key) { state_mask_list.insert(*address, mask.clone()); } } pub fn deregister_mask(&mut self, address: &SocketAddr, actor_key: &ActorKey) { if let Some(state_mask_list) = self.actor_state_mask_list_map.get_mut(actor_key) { state_mask_list.remove(address); } } }
#[doc = "Reader of register IOPENR"] pub type R = crate::R<u32, super::IOPENR>; #[doc = "Writer for register IOPENR"] pub type W = crate::W<u32, super::IOPENR>; #[doc = "Register IOPENR `reset()`'s with value 0"] impl crate::ResetValue for super::IOPENR { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "I/O port H clock enable bit\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum IOPHEN_A { #[doc = "0: Port clock disabled"] DISABLED = 0, #[doc = "1: Port clock enabled"] ENABLED = 1, } impl From<IOPHEN_A> for bool { #[inline(always)] fn from(variant: IOPHEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `IOPHEN`"] pub type IOPHEN_R = crate::R<bool, IOPHEN_A>; impl IOPHEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> IOPHEN_A { match self.bits { false => IOPHEN_A::DISABLED, true => IOPHEN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == IOPHEN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == IOPHEN_A::ENABLED } } #[doc = "Write proxy for field `IOPHEN`"] pub struct IOPHEN_W<'a> { w: &'a mut W, } impl<'a> IOPHEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPHEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Port clock disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(IOPHEN_A::DISABLED) } #[doc = "Port clock enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(IOPHEN_A::ENABLED) } #[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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "I/O port D clock enable bit"] pub type IOPDEN_A = IOPHEN_A; #[doc = "Reader of field `IOPDEN`"] pub type IOPDEN_R = crate::R<bool, IOPHEN_A>; #[doc = "Write proxy for field `IOPDEN`"] pub struct IOPDEN_W<'a> { w: &'a mut W, } impl<'a> IOPDEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPDEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Port clock disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(IOPHEN_A::DISABLED) } #[doc = "Port clock enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(IOPHEN_A::ENABLED) } #[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 = "IO port A clock enable bit"] pub type IOPCEN_A = IOPHEN_A; #[doc = "Reader of field `IOPCEN`"] pub type IOPCEN_R = crate::R<bool, IOPHEN_A>; #[doc = "Write proxy for field `IOPCEN`"] pub struct IOPCEN_W<'a> { w: &'a mut W, } impl<'a> IOPCEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPCEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Port clock disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(IOPHEN_A::DISABLED) } #[doc = "Port clock enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(IOPHEN_A::ENABLED) } #[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 = "IO port B clock enable bit"] pub type IOPBEN_A = IOPHEN_A; #[doc = "Reader of field `IOPBEN`"] pub type IOPBEN_R = crate::R<bool, IOPHEN_A>; #[doc = "Write proxy for field `IOPBEN`"] pub struct IOPBEN_W<'a> { w: &'a mut W, } impl<'a> IOPBEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPBEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Port clock disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(IOPHEN_A::DISABLED) } #[doc = "Port clock enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(IOPHEN_A::ENABLED) } #[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 = "IO port A clock enable bit"] pub type IOPAEN_A = IOPHEN_A; #[doc = "Reader of field `IOPAEN`"] pub type IOPAEN_R = crate::R<bool, IOPHEN_A>; #[doc = "Write proxy for field `IOPAEN`"] pub struct IOPAEN_W<'a> { w: &'a mut W, } impl<'a> IOPAEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPAEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Port clock disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(IOPHEN_A::DISABLED) } #[doc = "Port clock enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(IOPHEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "IO port E clock enable bit"] pub type IOPEEN_A = IOPHEN_A; #[doc = "Reader of field `IOPEEN`"] pub type IOPEEN_R = crate::R<bool, IOPHEN_A>; #[doc = "Write proxy for field `IOPEEN`"] pub struct IOPEEN_W<'a> { w: &'a mut W, } impl<'a> IOPEEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: IOPEEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Port clock disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(IOPHEN_A::DISABLED) } #[doc = "Port clock enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(IOPHEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } impl R { #[doc = "Bit 7 - I/O port H clock enable bit"] #[inline(always)] pub fn iophen(&self) -> IOPHEN_R { IOPHEN_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 3 - I/O port D clock enable bit"] #[inline(always)] pub fn iopden(&self) -> IOPDEN_R { IOPDEN_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 2 - IO port A clock enable bit"] #[inline(always)] pub fn iopcen(&self) -> IOPCEN_R { IOPCEN_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 1 - IO port B clock enable bit"] #[inline(always)] pub fn iopben(&self) -> IOPBEN_R { IOPBEN_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 0 - IO port A clock enable bit"] #[inline(always)] pub fn iopaen(&self) -> IOPAEN_R { IOPAEN_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 4 - IO port E clock enable bit"] #[inline(always)] pub fn iopeen(&self) -> IOPEEN_R { IOPEEN_R::new(((self.bits >> 4) & 0x01) != 0) } } impl W { #[doc = "Bit 7 - I/O port H clock enable bit"] #[inline(always)] pub fn iophen(&mut self) -> IOPHEN_W { IOPHEN_W { w: self } } #[doc = "Bit 3 - I/O port D clock enable bit"] #[inline(always)] pub fn iopden(&mut self) -> IOPDEN_W { IOPDEN_W { w: self } } #[doc = "Bit 2 - IO port A clock enable bit"] #[inline(always)] pub fn iopcen(&mut self) -> IOPCEN_W { IOPCEN_W { w: self } } #[doc = "Bit 1 - IO port B clock enable bit"] #[inline(always)] pub fn iopben(&mut self) -> IOPBEN_W { IOPBEN_W { w: self } } #[doc = "Bit 0 - IO port A clock enable bit"] #[inline(always)] pub fn iopaen(&mut self) -> IOPAEN_W { IOPAEN_W { w: self } } #[doc = "Bit 4 - IO port E clock enable bit"] #[inline(always)] pub fn iopeen(&mut self) -> IOPEEN_W { IOPEEN_W { w: self } } }
extern crate byteorder; extern crate libc; #[macro_use] extern crate plugkit; use std::io::{BufReader, Error, ErrorKind, Read, Result}; use std::fs::File; use std::path::Path; use byteorder::{BigEndian, LittleEndian, ReadBytesExt}; use plugkit::file::{Importer, RawFrame}; use plugkit::context::Context; pub struct PcapImporter {} impl Importer for PcapImporter { fn is_supported(_ctx: &mut Context, path: &Path) -> bool { if let Some(ext) = path.extension() { ext == "pcap" } else { false } } fn start( ctx: &mut Context, path: &Path, dst: &mut [RawFrame], cb: &Fn(&mut Context, usize, f64), ) -> Result<()> { let file = File::open(path)?; let mut rdr = BufReader::new(file); let magic_number = rdr.read_u32::<BigEndian>()?; let (le, nsec) = match magic_number { 0xd4c3b2a1 => (true, false), 0xa1b2c3d4 => (false, false), 0x4d3cb2a1 => (true, true), 0xa1b23c4d => (false, true), _ => return Err(Error::new(ErrorKind::InvalidData, "wrong magic number")), }; let (_ver_major, _var_minor, _thiszone, _sigfigs, _snaplen, network) = if le { ( rdr.read_u16::<LittleEndian>()?, rdr.read_u16::<LittleEndian>()?, rdr.read_i32::<LittleEndian>()?, rdr.read_u32::<LittleEndian>()?, rdr.read_u32::<LittleEndian>()?, rdr.read_u32::<LittleEndian>()?, ) } else { ( rdr.read_u16::<BigEndian>()?, rdr.read_u16::<BigEndian>()?, rdr.read_i32::<BigEndian>()?, rdr.read_u32::<BigEndian>()?, rdr.read_u32::<BigEndian>()?, rdr.read_u32::<BigEndian>()?, ) }; loop { let mut cnt = 0; let result = (|| -> Result<()> { for idx in 0..dst.len() { let (ts_sec, mut ts_usec, inc_len, orig_len) = if le { ( rdr.read_u32::<LittleEndian>()?, rdr.read_u32::<LittleEndian>()?, rdr.read_u32::<LittleEndian>()?, rdr.read_u32::<LittleEndian>()?, ) } else { ( rdr.read_u32::<BigEndian>()?, rdr.read_u32::<BigEndian>()?, rdr.read_u32::<BigEndian>()?, rdr.read_u32::<BigEndian>()?, ) }; if !nsec { ts_usec *= 1000; } let mut vec = Vec::<u8>::with_capacity(inc_len as usize); unsafe { vec.set_len(inc_len as usize); } rdr.read_exact(&mut vec)?; let frame = &mut dst[idx]; frame.set_link(network); frame.set_actlen(orig_len as usize); frame.set_payload_and_forget(vec.into_boxed_slice()); frame.set_ts((ts_sec as i64, ts_usec as i64)); cnt += 1; } Ok(()) })(); cb(ctx, cnt, 0.5); if result.is_err() { break; } } Ok(()) } } plugkit_module!({}); plugkit_api_file_import!(PcapImporter);
fn main() { enum SpreadsheetCell { Int(i32), Float(f64), Text(String), } let row = vec![ SpreadsheetCell::Int(3), SpreadsheetCell::Text(String::from("blue")), SpreadsheetCell::Float(10.12), ]; } // rust needs to know what types will be in the vector // at compile time so it knows exactly how much // memory on the heap will be needed to store each element
/// Creates an [`NSString`](foundation/struct.NSString.html) from a static /// string. /// /// # Feature Flag /// /// This macro is defined in [`foundation`](foundation/index.html), /// which requires the **`foundation`** /// [feature flag](index.html#feature-flags). /// /// # Examples /// /// This macro takes a either a `"string"` literal or `const` string slice as /// the argument: /// /// ``` /// let hello = fruity::nsstring!("hello"); /// assert_eq!(hello.to_string(), "hello"); /// /// const WORLD: &str = "world"; /// let world = fruity::nsstring!(WORLD); /// assert_eq!(world.to_string(), WORLD); /// ``` /// /// The result of this macro can even be used to create `static` values: /// /// ``` /// # use fruity::foundation::NSString; /// static WORLD: NSString = fruity::nsstring!("world"); /// /// assert_eq!(WORLD.to_string(), "world"); /// ``` /// /// Note that the result cannot be used in a `const` because it refers to /// static data outside of this library. /// /// # Unicode Strings /// /// In Objective-C, non-ASCII strings are represented as UTF-16. However, `&str` /// is encoded as UTF-8. /// /// Because of this, using a non-ASCII string is a compile error: /// /// ```compile_fail /// let non_ascii = fruity::nsstring!("straße"); /// ``` /// /// This is tracked in [issue #3](https://github.com/nvzqz/fruity/issues/3). /// /// # Null-Terminated Strings /// /// If the input string already ends with a 0 byte, then this macro does not /// append one. /// /// ``` /// let cstr = fruity::nsstring!("example\0"); /// let normal = fruity::nsstring!("example"); /// /// assert_eq!(cstr, normal); /// ``` /// /// # Runtime Cost /// /// None. /// /// The result is equivalent to `@"string"` syntax in Objective-C. /// /// Because of that, this should be preferred over /// [`NSString::from_str`](foundation/struct.NSString.html#method.from_str) /// where possible. /// /// # Compile-time Cost /// /// Minimal. /// /// This is implemented entirely with `const` evaluation. It is not a procedural /// macro that requires dependencies for parsing. #[macro_export] macro_rules! nsstring { ($s:expr) => {{ // Note that this always uses full paths to items from `$crate`. This // does not import any items because doing so could cause ambiguity if // the same names are exposed at the call site of this macro. // // The only names directly used are expressions, whose names shadow any // other names outside of this macro. // TODO(#3): Convert `INPUT` to UTF-16 if it contains non-ASCII bytes. const INPUT: &str = $s; // Assert that `INPUT` is ASCII. Unicode strings are not currently // supported. const _: [(); 1] = [(); $crate::_priv::str::is_cf_ascii(INPUT) as usize]; // This is defined in CoreFoundation, but we don't emit a link attribute // here because it is already linked via Foundation. // // Although this is a "private" (underscored) symbol, it is directly // referenced in Objective-C binaries. So it's safe for us to reference. extern "C" { static __CFConstantStringClassReference: $crate::_priv::std::ffi::c_void; } // This is composed of: // - 07: The `CFTypeID` for `CFString` // - C8: Flags for a constant ASCII string with a trailing null byte. const FLAGS: usize = 0x07c8; // If input already ends with a 0 byte, then we don't need to add it. let data = if $crate::_priv::str::is_nul_terminated(INPUT) { #[link_section = "__DATA,__cfstring,regular"] static DATA: $crate::_priv::__CFString = $crate::_priv::__CFString { isa: unsafe { &__CFConstantStringClassReference }, flags: FLAGS, data: INPUT.as_ptr(), // The length does not include the null byte. len: INPUT.len() - 1, }; &DATA } else { // Create a new constant with 0 appended to INPUT. #[repr(C)] struct Bytes { input: [u8; INPUT.len()], nul: u8, } const BYTES: Bytes = Bytes { input: unsafe { *$crate::_priv::std::mem::transmute::<_, &_>(INPUT.as_ptr()) }, nul: 0, }; const INPUT_WITH_NUL: &[u8; INPUT.len() + 1] = unsafe { $crate::_priv::std::mem::transmute(&BYTES) }; #[link_section = "__DATA,__cfstring,regular"] static DATA: $crate::_priv::__CFString = $crate::_priv::__CFString { isa: unsafe { &__CFConstantStringClassReference }, flags: FLAGS, data: INPUT_WITH_NUL.as_ptr(), // The length does not include the null byte. len: INPUT.len(), }; &DATA }; #[allow(unused_unsafe)] let nsstring = unsafe { $crate::foundation::NSString::from_ptr(data as *const _ as *mut _) }; nsstring }}; }
use prelude::*; #[derive(Copy, Clone, Serialize, Deserialize)] pub struct Tile { pub terrain: Terrain, pub mob_id: Option<MobId>, } #[derive(PartialEq, Eq, Debug, Copy, Clone, Serialize, Deserialize)] pub enum Terrain { Wall, Floor, ShortGrass, TallGrass, Brownberry, Exit, Entrance, Water, } #[derive(Serialize, Deserialize, PartialEq, Eq)] pub enum TileView { Visible, Remembered(Terrain), None, } // pub enum FullTileView<'a> { // Seen { // terrain: Terrain, // mob: Option<&'a Mob>, // }, // Remembered(Terrain), // None, // } impl Terrain { pub fn passable(&self) -> bool { use self::Terrain::*; match *self { Wall | Entrance | Exit | Water => false, _ => true, } } pub fn transparent(&self) -> bool { use self::Terrain::*; match *self { Wall | TallGrass => false, _ => true, } } // pub fn solid(&self) -> bool { // !self.passable() && !self.transparent() // } } impl TileView { pub fn is_visible(&self) -> bool { match self { TileView::Visible => true, _ => false, } } }
use std::env; use std::fs::File; use std::io::{self, BufRead}; use std::path::Path; fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } fn valid_password_part1(line: &String) -> bool { let mut parts = line.split_whitespace().collect::<Vec<&str>>(); if parts.len() != 3 { return false; } let minmax = parts[0].split("-").collect::<Vec<&str>>(); if minmax.len() != 2 { return false; } let min = minmax[0].parse::<i32>().unwrap(); let max = minmax[1].parse::<i32>().unwrap(); let search = parts[1].chars().next().unwrap(); let password = String::from(parts[2]); let mut n_search = 0; for c in password.chars() { if c == search { n_search += 1; } } if n_search < min { return false; } if n_search > max { return false; } true } fn valid_password_part2(line: &String) -> bool { let mut parts = line.split_whitespace().collect::<Vec<&str>>(); if parts.len() != 3 { return false; } let minmax = parts[0].split("-").collect::<Vec<&str>>(); if minmax.len() != 2 { return false; } let idx = minmax[0].parse::<usize>().unwrap() - 1; let idy = minmax[1].parse::<usize>().unwrap() - 1; let search = parts[1].chars().next().unwrap(); let password = String::from(parts[2]).chars().collect::<Vec<char>>(); if (password[idx] == search && password[idy] == search) { return false; } if (password[idx] == search || password[idy] == search) { return true; } false } fn main() { let args: Vec<String> = env::args().collect(); let mut valid = 0; if let Ok(lines) = read_lines("./input.txt") { for line in lines { if let Ok(v) = line { if args[1] == "1" { if valid_password_part1(&v) { valid += 1; } } else if args[1] == "2" { if valid_password_part2(&v) { valid += 1; } } } } } println!("{}", valid) }
//! Matrixrices with dimensions known at compile-time. #![allow(missing_docs)] // we allow missing to avoid having to document the mij components. use std::fmt; use std::ops::{Add, Sub, Mul, Div, AddAssign, SubAssign, MulAssign, DivAssign, Index, IndexMut}; use std::mem; use std::slice::{Iter, IterMut}; use rand::{Rand, Rng}; use num::{Zero, One}; use traits::operations::ApproxEq; use structs::vector::{Vector1, Vector2, Vector3, Vector4, Vector5, Vector6}; use structs::point::{Point1, Point4, Point5, Point6}; use structs::dvector::{DVector1, DVector2, DVector3, DVector4, DVector5, DVector6}; use traits::structure::{Cast, Row, Column, Iterable, IterableMut, Dimension, Indexable, Eye, ColumnSlice, RowSlice, Diagonal, DiagMut, Shape, BaseFloat, BaseNum, Repeat}; use traits::operations::{Absolute, Transpose, Inverse, Outer, EigenQR, Mean}; use traits::geometry::{ToHomogeneous, FromHomogeneous, Origin}; use linalg; #[cfg(feature="arbitrary")] use quickcheck::{Arbitrary, Gen}; /// Special identity matrix. All its operation are no-ops. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Debug, Copy)] pub struct Identity; impl Identity { /// Creates a new identity matrix. #[inline] pub fn new() -> Identity { Identity } } /// Square matrix of dimension 1. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Hash, Debug, Copy)] pub struct Matrix1<N> { pub m11: N } eye_impl!(Matrix1, 1, m11); mat_impl!(Matrix1, m11); repeat_impl!(Matrix1, m11); conversion_impl!(Matrix1, 1); mat_cast_impl!(Matrix1, m11); add_impl!(Matrix1, m11); sub_impl!(Matrix1, m11); scalar_add_impl!(Matrix1, m11); scalar_sub_impl!(Matrix1, m11); scalar_mul_impl!(Matrix1, m11); scalar_div_impl!(Matrix1, m11); absolute_impl!(Matrix1, m11); zero_impl!(Matrix1, m11); one_impl!(Matrix1, ::one); iterable_impl!(Matrix1, 1); iterable_mut_impl!(Matrix1, 1); at_fast_impl!(Matrix1, 1); dim_impl!(Matrix1, 1); indexable_impl!(Matrix1, 1); index_impl!(Matrix1, 1); mat_mul_mat_impl!(Matrix1, 1); mat_mul_vec_impl!(Matrix1, Vector1, 1, ::zero); vec_mul_mat_impl!(Matrix1, Vector1, 1, ::zero); mat_mul_point_impl!(Matrix1, Point1, 1, Origin::origin); point_mul_mat_impl!(Matrix1, Point1, 1, Origin::origin); // (specialized); inverse_impl!(Matrix1, 1); transpose_impl!(Matrix1, 1); approx_eq_impl!(Matrix1); row_impl!(Matrix1, Vector1, 1); column_impl!(Matrix1, Vector1, 1); column_slice_impl!(Matrix1, Vector1, DVector1, 1); row_slice_impl!(Matrix1, Vector1, DVector1, 1); diag_impl!(Matrix1, Vector1, 1); to_homogeneous_impl!(Matrix1, Matrix2, 1, 2); from_homogeneous_impl!(Matrix1, Matrix2, 1, 2); outer_impl!(Vector1, Matrix1); eigen_qr_impl!(Matrix1, Vector1); arbitrary_impl!(Matrix1, m11); rand_impl!(Matrix1, m11); mean_impl!(Matrix1, Vector1, 1); mat_display_impl!(Matrix1, 1); /// Square matrix of dimension 2. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Hash, Debug, Copy)] pub struct Matrix2<N> { pub m11: N, pub m21: N, pub m12: N, pub m22: N } eye_impl!(Matrix2, 2, m11, m22); mat_impl!(Matrix2, m11, m12, m21, m22); repeat_impl!(Matrix2, m11, m12, m21, m22); conversion_impl!(Matrix2, 2); mat_cast_impl!(Matrix2, m11, m12, m21, m22); add_impl!(Matrix2, m11, m12, m21, m22); sub_impl!(Matrix2, m11, m12, m21, m22); scalar_add_impl!(Matrix2, m11, m12, m21, m22); scalar_sub_impl!(Matrix2, m11, m12, m21, m22); scalar_mul_impl!(Matrix2, m11, m12, m21, m22); scalar_div_impl!(Matrix2, m11, m12, m21, m22); absolute_impl!(Matrix2, m11, m12, m21, m22); zero_impl!(Matrix2, m11, m12, m21, m22); one_impl!(Matrix2, ::one, ::zero, ::zero, ::one); iterable_impl!(Matrix2, 2); iterable_mut_impl!(Matrix2, 2); dim_impl!(Matrix2, 2); indexable_impl!(Matrix2, 2); index_impl!(Matrix2, 2); at_fast_impl!(Matrix2, 2); // (specialized); mul_impl!(Matrix2, 2); // (specialized); rmul_impl!(Matrix2, Vector2, 2); // (specialized); lmul_impl!(Matrix2, Vector2, 2); // (specialized); inverse_impl!(Matrix2, 2); transpose_impl!(Matrix2, 2); approx_eq_impl!(Matrix2); row_impl!(Matrix2, Vector2, 2); column_impl!(Matrix2, Vector2, 2); column_slice_impl!(Matrix2, Vector2, DVector2, 2); row_slice_impl!(Matrix2, Vector2, DVector2, 2); diag_impl!(Matrix2, Vector2, 2); to_homogeneous_impl!(Matrix2, Matrix3, 2, 3); from_homogeneous_impl!(Matrix2, Matrix3, 2, 3); outer_impl!(Vector2, Matrix2); eigen_qr_impl!(Matrix2, Vector2); arbitrary_impl!(Matrix2, m11, m12, m21, m22); rand_impl!(Matrix2, m11, m12, m21, m22); mean_impl!(Matrix2, Vector2, 2); mat_display_impl!(Matrix2, 2); /// Square matrix of dimension 3. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Hash, Debug, Copy)] pub struct Matrix3<N> { pub m11: N, pub m21: N, pub m31: N, pub m12: N, pub m22: N, pub m32: N, pub m13: N, pub m23: N, pub m33: N } eye_impl!(Matrix3, 3, m11, m22, m33); mat_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33); repeat_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33); conversion_impl!(Matrix3, 3); mat_cast_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33); add_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); sub_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); scalar_add_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); scalar_sub_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); scalar_mul_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); scalar_div_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); absolute_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); zero_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); one_impl!(Matrix3, ::one , ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::one); iterable_impl!(Matrix3, 3); iterable_mut_impl!(Matrix3, 3); dim_impl!(Matrix3, 3); indexable_impl!(Matrix3, 3); index_impl!(Matrix3, 3); at_fast_impl!(Matrix3, 3); // (specialized); mul_impl!(Matrix3, 3); // (specialized); rmul_impl!(Matrix3, Vector3, 3); // (specialized); lmul_impl!(Matrix3, Vector3, 3); // (specialized); inverse_impl!(Matrix3, 3); transpose_impl!(Matrix3, 3); approx_eq_impl!(Matrix3); // (specialized); row_impl!(Matrix3, Vector3, 3); // (specialized); column_impl!(Matrix3, Vector3, 3); column_slice_impl!(Matrix3, Vector3, DVector3, 3); row_slice_impl!(Matrix3, Vector3, DVector3, 3); diag_impl!(Matrix3, Vector3, 3); to_homogeneous_impl!(Matrix3, Matrix4, 3, 4); from_homogeneous_impl!(Matrix3, Matrix4, 3, 4); outer_impl!(Vector3, Matrix3); eigen_qr_impl!(Matrix3, Vector3); arbitrary_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); rand_impl!(Matrix3, m11, m12, m13, m21, m22, m23, m31, m32, m33 ); mean_impl!(Matrix3, Vector3, 3); mat_display_impl!(Matrix3, 3); /// Square matrix of dimension 4. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Hash, Debug, Copy)] pub struct Matrix4<N> { pub m11: N, pub m21: N, pub m31: N, pub m41: N, pub m12: N, pub m22: N, pub m32: N, pub m42: N, pub m13: N, pub m23: N, pub m33: N, pub m43: N, pub m14: N, pub m24: N, pub m34: N, pub m44: N } eye_impl!(Matrix4, 4, m11, m22, m33, m44); mat_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); repeat_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); conversion_impl!(Matrix4, 4); mat_cast_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); add_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); sub_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); scalar_add_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); scalar_sub_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); scalar_mul_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); scalar_div_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); absolute_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); zero_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); one_impl!(Matrix4, ::one , ::zero, ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::zero, ::one); iterable_impl!(Matrix4, 4); iterable_mut_impl!(Matrix4, 4); dim_impl!(Matrix4, 4); indexable_impl!(Matrix4, 4); index_impl!(Matrix4, 4); at_fast_impl!(Matrix4, 4); mat_mul_mat_impl!(Matrix4, 4); mat_mul_vec_impl!(Matrix4, Vector4, 4, ::zero); vec_mul_mat_impl!(Matrix4, Vector4, 4, ::zero); mat_mul_point_impl!(Matrix4, Point4, 4, Origin::origin); point_mul_mat_impl!(Matrix4, Point4, 4, Origin::origin); inverse_impl!(Matrix4, 4); transpose_impl!(Matrix4, 4); approx_eq_impl!(Matrix4); row_impl!(Matrix4, Vector4, 4); column_impl!(Matrix4, Vector4, 4); column_slice_impl!(Matrix4, Vector4, DVector4, 4); row_slice_impl!(Matrix4, Vector4, DVector4, 4); diag_impl!(Matrix4, Vector4, 4); to_homogeneous_impl!(Matrix4, Matrix5, 4, 5); from_homogeneous_impl!(Matrix4, Matrix5, 4, 5); outer_impl!(Vector4, Matrix4); eigen_qr_impl!(Matrix4, Vector4); arbitrary_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); rand_impl!(Matrix4, m11, m12, m13, m14, m21, m22, m23, m24, m31, m32, m33, m34, m41, m42, m43, m44 ); mean_impl!(Matrix4, Vector4, 4); mat_display_impl!(Matrix4, 4); /// Square matrix of dimension 5. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Hash, Debug, Copy)] pub struct Matrix5<N> { pub m11: N, pub m21: N, pub m31: N, pub m41: N, pub m51: N, pub m12: N, pub m22: N, pub m32: N, pub m42: N, pub m52: N, pub m13: N, pub m23: N, pub m33: N, pub m43: N, pub m53: N, pub m14: N, pub m24: N, pub m34: N, pub m44: N, pub m54: N, pub m15: N, pub m25: N, pub m35: N, pub m45: N, pub m55: N } eye_impl!(Matrix5, 5, m11, m22, m33, m44, m55); mat_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); repeat_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); conversion_impl!(Matrix5, 5); mat_cast_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); absolute_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); zero_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); one_impl!(Matrix5, ::one , ::zero, ::zero, ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::zero, ::zero, ::one ); add_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); sub_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); scalar_add_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); scalar_sub_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); scalar_mul_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); scalar_div_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); iterable_impl!(Matrix5, 5); iterable_mut_impl!(Matrix5, 5); dim_impl!(Matrix5, 5); indexable_impl!(Matrix5, 5); index_impl!(Matrix5, 5); at_fast_impl!(Matrix5, 5); mat_mul_mat_impl!(Matrix5, 5); mat_mul_vec_impl!(Matrix5, Vector5, 5, ::zero); vec_mul_mat_impl!(Matrix5, Vector5, 5, ::zero); mat_mul_point_impl!(Matrix5, Point5, 5, Origin::origin); point_mul_mat_impl!(Matrix5, Point5, 5, Origin::origin); inverse_impl!(Matrix5, 5); transpose_impl!(Matrix5, 5); approx_eq_impl!(Matrix5); row_impl!(Matrix5, Vector5, 5); column_impl!(Matrix5, Vector5, 5); column_slice_impl!(Matrix5, Vector5, DVector5, 5); row_slice_impl!(Matrix5, Vector5, DVector5, 5); diag_impl!(Matrix5, Vector5, 5); to_homogeneous_impl!(Matrix5, Matrix6, 5, 6); from_homogeneous_impl!(Matrix5, Matrix6, 5, 6); outer_impl!(Vector5, Matrix5); eigen_qr_impl!(Matrix5, Vector5); arbitrary_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); rand_impl!(Matrix5, m11, m12, m13, m14, m15, m21, m22, m23, m24, m25, m31, m32, m33, m34, m35, m41, m42, m43, m44, m45, m51, m52, m53, m54, m55 ); mean_impl!(Matrix5, Vector5, 5); mat_display_impl!(Matrix5, 5); /// Square matrix of dimension 6. #[repr(C)] #[derive(Eq, PartialEq, RustcEncodable, RustcDecodable, Clone, Hash, Debug, Copy)] pub struct Matrix6<N> { pub m11: N, pub m21: N, pub m31: N, pub m41: N, pub m51: N, pub m61: N, pub m12: N, pub m22: N, pub m32: N, pub m42: N, pub m52: N, pub m62: N, pub m13: N, pub m23: N, pub m33: N, pub m43: N, pub m53: N, pub m63: N, pub m14: N, pub m24: N, pub m34: N, pub m44: N, pub m54: N, pub m64: N, pub m15: N, pub m25: N, pub m35: N, pub m45: N, pub m55: N, pub m65: N, pub m16: N, pub m26: N, pub m36: N, pub m46: N, pub m56: N, pub m66: N } eye_impl!(Matrix6, 6, m11, m22, m33, m44, m55, m66); mat_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); repeat_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); conversion_impl!(Matrix6, 6); mat_cast_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); add_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); sub_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); scalar_add_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); scalar_sub_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); scalar_mul_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); scalar_div_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); absolute_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66); zero_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66); one_impl!(Matrix6, ::one , ::zero, ::zero, ::zero, ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::zero, ::zero, ::zero, ::one , ::zero, ::zero, ::zero, ::zero, ::zero, ::zero, ::one ); iterable_impl!(Matrix6, 6); iterable_mut_impl!(Matrix6, 6); dim_impl!(Matrix6, 6); indexable_impl!(Matrix6, 6); index_impl!(Matrix6, 6); at_fast_impl!(Matrix6, 6); mat_mul_mat_impl!(Matrix6, 6); mat_mul_vec_impl!(Matrix6, Vector6, 6, ::zero); vec_mul_mat_impl!(Matrix6, Vector6, 6, ::zero); mat_mul_point_impl!(Matrix6, Point6, 6, Origin::origin); point_mul_mat_impl!(Matrix6, Point6, 6, Origin::origin); inverse_impl!(Matrix6, 6); transpose_impl!(Matrix6, 6); approx_eq_impl!(Matrix6); row_impl!(Matrix6, Vector6, 6); column_impl!(Matrix6, Vector6, 6); column_slice_impl!(Matrix6, Vector6, DVector6, 6); row_slice_impl!(Matrix6, Vector6, DVector6, 6); diag_impl!(Matrix6, Vector6, 6); outer_impl!(Vector6, Matrix6); eigen_qr_impl!(Matrix6, Vector6); arbitrary_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); rand_impl!(Matrix6, m11, m12, m13, m14, m15, m16, m21, m22, m23, m24, m25, m26, m31, m32, m33, m34, m35, m36, m41, m42, m43, m44, m45, m46, m51, m52, m53, m54, m55, m56, m61, m62, m63, m64, m65, m66 ); mean_impl!(Matrix6, Vector6, 6); mat_display_impl!(Matrix6, 6);
use map_macros::{map, btree_map, set, btree_set}; fn main() { let mut mm = map!{}; println!("{:?}", mm); mm.insert("hello", "world"); let mm = btree_map!{"hello"=>"world", "yes"=>"ok"}; println!("{:?}", mm); let mm = set!{"hello", "yes"}; println!("{:?}", mm); let mm = btree_set!{"hello", "yes"}; println!("{:?}", mm); }
//! Trace exporters use crate::{api, sdk}; use std::sync::Arc; use std::time::SystemTime; /// Describes the result of an export. #[derive(Debug)] pub enum ExportResult { /// Batch is successfully exported. Success, /// Batch export failed. Caller must not retry. FailedNotRetryable, /// Batch export failed transiently. Caller should record error and may retry. FailedRetryable, } /// `SpanExporter` defines the interface that protocol-specific exporters must /// implement so that they can be plugged into OpenTelemetry SDK and support /// sending of telemetry data. /// /// The goals of the interface are: /// /// - Minimize burden of implementation for protocol-dependent telemetry /// exporters. The protocol exporter is expected to be primarily a simple /// telemetry data encoder and transmitter. /// - Allow implementing helpers as composable components that use the same /// chainable Exporter interface. SDK authors are encouraged to implement common /// functionality such as queuing, batching, tagging, etc. as helpers. This /// functionality will be applicable regardless of what protocol exporter is used. pub trait SpanExporter: Send + Sync + std::fmt::Debug { /// Exports a batch of telemetry data. Protocol exporters that will implement /// this function are typically expected to serialize and transmit the data /// to the destination. /// /// This function will never be called concurrently for the same exporter /// instance. It can be called again only after the current call returns. /// /// This function must not block indefinitely, there must be a reasonable /// upper limit after which the call must time out with an error result. fn export(&self, batch: Vec<Arc<SpanData>>) -> ExportResult; /// Shuts down the exporter. Called when SDK is shut down. This is an /// opportunity for exporter to do any cleanup required. /// /// `shutdown` should be called only once for each Exporter instance. After /// the call to `shutdown`, subsequent calls to `SpanExport` are not allowed /// and should return an error. /// /// Shutdown should not block indefinitely (e.g. if it attempts to flush the /// data and the destination is unavailable). SDK authors can /// decide if they want to make the shutdown timeout to be configurable. fn shutdown(&self); /// Allows exporter to be downcast fn as_any(&self) -> &dyn std::any::Any; } /// `SpanData` contains all the information collected by a `Span` and can be used /// by exporters as a standard input. #[derive(Clone, Debug)] pub struct SpanData { /// Exportable `SpanContext` pub context: api::SpanContext, /// Span parent id pub parent_span_id: u64, /// Span kind pub span_kind: api::SpanKind, /// Span operation name pub name: String, /// Span start time pub start_time: SystemTime, /// Span end time pub end_time: SystemTime, /// Span attributes pub attributes: sdk::EvictedQueue<api::KeyValue>, /// Span Message events pub message_events: sdk::EvictedQueue<api::Event>, /// Span Links pub links: sdk::EvictedQueue<api::Link>, /// Span status pub status: api::SpanStatus, }
use crate::cache::ResponseCache; use crate::error::Result; use crate::proto::{Proto, Request}; use serde::{Deserialize, Serialize}; use serde_json::{json, Map, Value}; use std::rc::Rc; pub trait Emeter { fn get_emeter_realtime(&mut self) -> Result<RealtimeStats>; fn get_emeter_month_stats(&mut self, year: u32) -> Result<MonthStats>; fn get_emeter_day_stats(&mut self, month: u32, year: u32) -> Result<DayStats>; fn erase_emeter_stats(&mut self) -> Result<()>; } pub(crate) struct EmeterStats { ns: String, proto: Rc<Proto>, cache: Rc<ResponseCache>, } impl EmeterStats { pub(crate) fn new(ns: &str, proto: Rc<Proto>, cache: Rc<ResponseCache>) -> EmeterStats { EmeterStats { ns: String::from(ns), proto, cache, } } pub(crate) fn get_realtime(&self) -> Result<RealtimeStats> { let request = Request::new(&self.ns, "get_realtime", None); let response = if let Some(cache) = self.cache.as_ref() { cache .borrow_mut() .try_get_or_insert_with(request, |r| self.proto.send_request(r))? } else { self.proto.send_request(&request)? }; log::trace!("({}) {:?}", self.ns, response); Ok(serde_json::from_value(response).unwrap_or_else(|err| { panic!( "invalid response from host with address {}: {}", self.proto.host(), err ) })) } pub(crate) fn get_day_stats(&self, month: u32, year: u32) -> Result<DayStats> { let request = Request::new( &self.ns, "get_daystat", Some(json!({ "month": month , "year": year})), ); let response = if let Some(cache) = self.cache.as_ref() { cache .borrow_mut() .try_get_or_insert_with(request, |r| self.proto.send_request(r))? } else { self.proto.send_request(&request)? }; log::trace!("({}) {:?}", self.ns, response); Ok(serde_json::from_value(response).unwrap_or_else(|err| { panic!( "invalid response from host with address {}: {}", self.proto.host(), err ) })) } pub(crate) fn get_month_stats(&self, year: u32) -> Result<MonthStats> { let request = Request::new(&self.ns, "get_monthstat", Some(json!({ "year": year }))); let response = if let Some(cache) = self.cache.as_ref() { cache .borrow_mut() .try_get_or_insert_with(request, |r| self.proto.send_request(r))? } else { self.proto.send_request(&request)? }; log::trace!("({}) {:?}", self.ns, response); Ok(serde_json::from_value(response).unwrap_or_else(|err| { panic!( "invalid response from host with address {}: {}", self.proto.host(), err ) })) } pub(crate) fn erase_stats(&self) -> Result<()> { if let Some(cache) = self.cache.as_ref() { cache.borrow_mut().retain(|k, _| k.target != self.ns) } let response = self.proto .send_request(&Request::new(&self.ns, "erase_emeter_stat", None))?; log::debug!("{:?}", response); Ok(()) } } #[derive(Debug, Serialize, Deserialize)] pub struct RealtimeStats { #[serde(flatten)] stats: Map<String, Value>, } #[derive(Debug, Serialize, Deserialize)] pub struct DayStats { day_list: Vec<DayStat>, } #[derive(Debug, Serialize, Deserialize)] struct DayStat { energy_wh: u32, day: u32, month: u32, year: u32, } #[derive(Debug, Serialize, Deserialize)] pub struct MonthStats { month_list: Vec<MonthStat>, } #[derive(Debug, Serialize, Deserialize)] struct MonthStat { energy_wh: u32, month: u32, year: u32, }
use crow_ecs::{Entities, Entity, Joinable, Storage}; use crate::{ data::{Collider, ColliderType, Collision, Collisions, Grounded, Position, Velocity}, physics, time::Time, }; #[derive(Debug, Default)] pub struct PhysicsSystem { collisions: Collisions, } impl PhysicsSystem { pub fn new() -> Self { PhysicsSystem::default() } pub fn run( &mut self, velocities: &Storage<Velocity>, colliders: &Storage<Collider>, previous_positions: &mut Storage<Position>, mut positions: &mut Storage<Position>, grounded: &mut Storage<Grounded>, time: &Time, ) -> &mut Collisions { #[cfg(feature = "profiler")] profile_scope!("run"); self.collisions.clear(); previous_positions.clear(); grounded.clear(); for (velocity, position, entity) in (&velocities, &mut positions, Entities).join() { if velocity.x != 0.0 || velocity.y != 0.0 { previous_positions.insert(entity, *position); position.x += velocity.x * time.fixed_seconds(); position.y += velocity.y * time.fixed_seconds(); } } // check for collisions between moving entities let mut iter = (&positions, &colliders, Entities, &previous_positions).join(); while let Some((&a_pos, &a_collider, a_entity, _moved)) = iter.next() { for (&b_pos, &b_collider, b_entity, _moved) in iter.clone() { if physics::is_collision(a_pos, a_collider, b_pos, b_collider) { self.resolve_collisions((a_entity, a_collider.ty), (b_entity, b_collider.ty)) } } } // collisions with other entities for (&a_pos, &a_collider, a_entity, _moved) in (&positions, &colliders, Entities, &previous_positions).join() { for (&b_pos, &b_collider, b_entity, _not_moved) in (&positions, &colliders, Entities, !&previous_positions).join() { if physics::is_collision(a_pos, a_collider, b_pos, b_collider) { self.resolve_collisions((a_entity, a_collider.ty), (b_entity, b_collider.ty)) } } } &mut self.collisions } fn resolve_collisions(&mut self, a: (Entity, ColliderType), b: (Entity, ColliderType)) { match (a, b) { ((e, ColliderType::Environment), (p, ColliderType::Player)) | ((p, ColliderType::Player), (e, ColliderType::Environment)) | ((e, ColliderType::CameraRestriction), (p, ColliderType::Camera)) | ((p, ColliderType::Camera), (e, ColliderType::CameraRestriction)) => { self.collisions.fixed.push(Collision(e, p)) } ((b, ColliderType::Bridge), (p, ColliderType::Player)) | ((p, ColliderType::Player), (b, ColliderType::Bridge)) => { self.collisions.bridge.push(Collision(b, p)) } ((p, ColliderType::Player), (d, ColliderType::PlayerDamage)) | ((d, ColliderType::PlayerDamage), (p, ColliderType::Player)) => { self.collisions.player_damage.push(Collision(p, d)) } ((_, ColliderType::Environment), (_, ColliderType::Environment)) | ((_, ColliderType::Environment), (_, ColliderType::Bridge)) | ((_, ColliderType::Bridge), (_, ColliderType::Environment)) | ((_, ColliderType::Environment), (_, ColliderType::PlayerDamage)) | ((_, ColliderType::PlayerDamage), (_, ColliderType::Environment)) | ((_, ColliderType::Player), (_, ColliderType::Player)) | ((_, ColliderType::Bridge), (_, ColliderType::Bridge)) | ((_, ColliderType::Bridge), (_, ColliderType::PlayerDamage)) | ((_, ColliderType::PlayerDamage), (_, ColliderType::Bridge)) | ((_, ColliderType::PlayerDamage), (_, ColliderType::PlayerDamage)) | ((_, ColliderType::Camera), _) | (_, (_, ColliderType::Camera)) | ((_, ColliderType::CameraRestriction), _) | (_, (_, ColliderType::CameraRestriction)) => {} } } }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. /// Represents a `Locator` for ILNPv6 along with its preference. /// /// Used in a `L32` record; similar in purpose to an `A` record. #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Locator64 { /// Indicates the owner name's relative preference for record among other records associated with this owner name. /// /// Lower preference values are preferred over higher preference values. pub preference: u16, /// `Locator64`. /// /// Has the same syntax and semantics as a 64-bit Internet Protocol version 6 routing prefix. pub locator: [u8; 8], }
pub mod evaluator; pub mod fan; pub mod fan_console; pub mod fan_hwmon_pwm; pub use fan::fan::Fan; pub use fan::fan_console::ConsoleFan; pub use fan::fan_hwmon_pwm::HwmonPwmFan;
mod get_blocks_proof; mod get_transactions_proof;
fn main() { yew::start_app::<npm_and_rest_web_sys::Model>(); }
use crate::{DocBase, VarType}; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Variable, name: "accdist", signatures: vec![], description: "Accumulation/distribution index.", example: "", returns: "", arguments: "", remarks: "", links: "", }; vec![fn_doc] }
// Copyright 2018 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. pub struct Size { pub width: u32, pub height: u32, } pub fn get_window_size() -> Result<Size, failure::Error> { Err(failure::err_msg( "fuchsia-device is deprecated; please use fuchsia.hardware.pty.Device instead", )) }
use std::sync::Arc; use crate::{graphics::{SampleCount, Format, Backend}, Matrix4}; pub trait Surface { } #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum SwapchainError { ZeroExtents, SurfaceLost, Other } pub trait WSIFence : Sized {} pub struct PreparedBackBuffer<'a, B: Backend> { pub prepare_fence: &'a B::WSIFence, pub present_fence: &'a B::WSIFence, pub texture_view: &'a Arc<B::TextureView> } pub trait Swapchain<B: Backend> : Sized { fn recreate(old: &Self, width: u32, height: u32) -> Result<Arc<Self>, SwapchainError>; fn recreate_on_surface(old: &Self, surface: &Arc<B::Surface>, width: u32, height: u32) -> Result<Arc<Self>, SwapchainError>; fn sample_count(&self) -> SampleCount; fn format(&self) -> Format; fn surface(&self) -> &Arc<B::Surface>; fn prepare_back_buffer(&self) -> Option<PreparedBackBuffer<'_, B>>; fn transform(&self) -> Matrix4; fn width(&self) -> u32; fn height(&self) -> u32; }
use std::{fmt::Debug, sync::Arc}; use parking_lot::{Mutex, MutexGuard}; use crate::buffer_tree::partition::PartitionData; pub(crate) trait PostWriteObserver: Send + Sync + Debug { fn observe(&self, partition: Arc<Mutex<PartitionData>>, guard: MutexGuard<'_, PartitionData>); }
use std::{ cell::UnsafeCell, clone::Clone, mem::MaybeUninit, ops::Deref, ptr, sync::{Arc, Once}, }; /// Helps you create C-compatible string literals, like `c_string!("Hello!")` -> `b"Hello!\0"`. macro_rules! c_string { ($s:expr) => { concat!($s, "\0").as_bytes() }; } /// Macro to get around the limitation of not being able to write `#[doc = concat!("a", "b", ...)]`. macro_rules! document { ($comment:expr, $($tt:tt)*) => { #[doc = $comment] $($tt)* }; } /// Generates simple dynamic linkings. macro_rules! dyn_link { ( $(#[$outer:meta])* $s_vis:vis struct $s_ident:ident($dlopen:expr => $dlopen_ty:ty | $dlsym:expr) { $($($module_name:literal)|+ { $( $(#[$fn_outer:meta])* fn $sym_fn:ident($($name:ident : $ty:ty),*$(,)?) -> $ret:ty; )* }),* $(,)? } ) => { $(#[$outer])* pub struct $s_ident { $($( $(#[$fn_outer])* $sym_fn : ::std::option::Option< unsafe extern "system" fn($($name : $ty ,)*) -> $ret > , )*)* } impl $s_ident { #[allow(unused_doc_comments)] unsafe fn _link() -> Self { let mut inst = ::std::mem::MaybeUninit::<Self>::uninit(); let mut inst_ref = &mut *(inst.as_mut_ptr()); $( let mut handle = 0 as $dlopen_ty; for name in &[$(c_string!($module_name) ,)*] { handle = $dlopen(name.as_ptr().cast()); if handle != (0 as $dlopen_ty) { break } } if handle != (0 as $dlopen_ty) { $( $(#[$fn_outer])* { inst_ref.$sym_fn = ::std::mem::transmute::<_, Option<unsafe extern "system" fn($($name : $ty ,)*) -> $ret>> ($dlsym(handle, c_string!(stringify!($sym_fn)).as_ptr().cast())); } )* } else { $( $(#[$fn_outer])* { inst_ref.$sym_fn = None; } )* } )* inst.assume_init() } $($( $(#[$fn_outer])* $s_vis unsafe fn $sym_fn(&self, $($name : $ty ,)*) -> ::std::option::Option<$ret> { self.$sym_fn.map(|f| f($($name ,)*)) } )*)* } }; } pub fn str_has_nulls(s: &str) -> bool { s.bytes().any(|b| b == 0x00) } pub fn str_sweep_nulls(s: &mut String) { // SAFETY: 0x00 is a one-byte null and is safe to swap with 0x20 for byte in unsafe { s.as_mut_vec().iter_mut() } { if *byte == 0x00 { *byte = b' '; } } } pub struct FixedVec<T, const N: usize> { array: MaybeUninit<[T; N]>, len: usize, } impl<T: Copy, const N: usize> FixedVec<T, N> { pub fn clear(&mut self) { for el in self.slice_mut() { unsafe { ptr::drop_in_place(el); } } self.len = 0; } pub fn new() -> Self { Self { array: MaybeUninit::uninit(), len: 0, } } pub fn push(&mut self, item: &T) -> bool { self.push_many(unsafe { std::slice::from_raw_parts(item, 1) }) } pub fn push_many(&mut self, items: &[T]) -> bool { if self.len + items.len() <= N { unsafe { ptr::copy_nonoverlapping( items.as_ptr(), (&mut *self.array.as_mut_ptr()) .get_unchecked_mut(self.len), items.len(), ); } self.len += items.len(); true } else { false } } pub fn slice(&self) -> &[T] { unsafe { (&*self.array.as_ptr()).get_unchecked(..self.len) } } pub fn slice_mut(&mut self) -> &mut [T] { unsafe { (&mut *self.array.as_mut_ptr()).get_unchecked_mut(..self.len) } } } /// Minimal lazily initialized type, similar to the one in `once_cell`. /// /// Thread safe initialization, immutable-only access. pub struct LazyCell<T, F = fn() -> T> { // Invariant: Written to at most once on first access. init: UnsafeCell<Option<F>>, ptr: UnsafeCell<*const T>, // Synchronization primitive for initializing `init` and `ptr`. once: Once, } unsafe impl<T, F> Send for LazyCell<T, F> where T: Send {} unsafe impl<T, F> Sync for LazyCell<T, F> where T: Sync {} impl<T, F> LazyCell<T, F> { pub const fn new(init: F) -> Self { Self { init: UnsafeCell::new(Some(init)), ptr: UnsafeCell::new(ptr::null()), once: Once::new(), } } } impl<T, F: FnOnce() -> T> LazyCell<T, F> { pub fn get(&self) -> &T { self.once.call_once(|| unsafe { if let Some(f) = (&mut *self.init.get()).take() { let pointer = Box::into_raw(Box::new(f())); ptr::write(self.ptr.get(), pointer); } }); // SAFETY: A call to `call_once` initialized the pointer unsafe { &**self.ptr.get() } } } impl<T, F: FnOnce() -> T> Deref for LazyCell<T, F> { type Target = T; #[inline] fn deref(&self) -> &Self::Target { self.get() } } /// Static or dynamic data shared across threads. pub enum MaybeArc<T: 'static + ?Sized> { Static(&'static T), Dynamic(Arc<T>), } impl<T: 'static + ?Sized> AsRef<T> for MaybeArc<T> { fn as_ref(&self) -> &T { match self { Self::Static(s) => s, Self::Dynamic(d) => d.as_ref(), } } } impl<T: 'static + ?Sized> Clone for MaybeArc<T> { fn clone(&self) -> Self { match self { Self::Static(x) => Self::Static(x), Self::Dynamic(x) => Self::Dynamic(Arc::clone(x)), } } } /// Wrapper for working with both `std` and `parking_lot`. /// None of these functions should panic when used correctly as they're used in FFI. #[cfg(not(feature = "parking-lot"))] pub(crate) mod sync { pub use std::sync::{Condvar, Mutex, MutexGuard}; use std::ptr; #[inline] pub fn condvar_notify1(cvar: &Condvar) { cvar.notify_one(); } pub fn condvar_wait<T>(cvar: &Condvar, guard: &mut MutexGuard<T>) { // The signature in `std` is quite terrible and CONSUMES the guard // HACK: We "move it out" for the duration of the wait unsafe { let guard_copy = ptr::read(guard); let result = cvar.wait(guard_copy).expect("cvar mutex poisoned (this is a bug)"); ptr::write(guard, result); } } pub fn mutex_lock<T>(mtx: &Mutex<T>) -> MutexGuard<T> { mtx.lock().expect("mutex poisoned (this is a bug)") } } #[cfg(feature = "parking-lot")] pub(crate) mod sync { pub use parking_lot::{Condvar, Mutex, MutexGuard}; #[inline] pub fn condvar_notify1(cvar: &Condvar) { let _ = cvar.notify_one(); } #[inline] pub fn condvar_wait<T>(cvar: &Condvar, guard: &mut MutexGuard<T>) { cvar.wait(guard); } #[inline] pub fn mutex_lock<T>(mtx: &Mutex<T>) -> MutexGuard<T> { mtx.lock() } }
use std::sync::{Arc, atomic::{AtomicU64, Ordering}, Mutex, Condvar}; use sourcerenderer_core::graphics::{Format, SampleCount, Surface, Swapchain, Texture, TextureInfo, TextureViewInfo, TextureUsage, TextureDimension}; use wasm_bindgen::JsCast; use web_sys::{Document, HtmlCanvasElement, WebGl2RenderingContext}; use crate::{GLThreadSender, WebGLBackend, WebGLTexture, device::WebGLHandleAllocator, sync::WebGLSemaphore, texture::WebGLTextureView, thread::WebGLTextureHandleView}; pub struct WebGLSurface { //canvas_element: HtmlCanvasElement selector: String, width: u32, height: u32 } impl Surface for WebGLSurface {} impl PartialEq for WebGLSurface { fn eq(&self, other: &Self) -> bool { //self.canvas_element == other.canvas_element self.selector == other.selector } } impl Eq for WebGLSurface {} impl WebGLSurface { /*pub fn new(canvas_element: &HtmlCanvasElement) -> Self { Self { canvas_element: canvas_element.clone() } }*/ pub fn new(selector: &str, document: &Document) -> Self { let canvas = Self::canvas_internal(selector, document); let width = canvas.width(); let height = canvas.height(); Self { selector: selector.to_string(), width, height } } fn canvas_internal(selector: &str, document: &Document) -> HtmlCanvasElement { let element = document.query_selector(selector).unwrap().unwrap(); element.dyn_into::<HtmlCanvasElement>().unwrap() } pub fn canvas(&self, document: &Document) -> HtmlCanvasElement { Self::canvas_internal(&self.selector, document) } pub fn selector(&self) -> &str { &self.selector } } pub struct GLThreadSync { empty_mutex: Mutex<()>, // Use empty mutex + atomics so we never accidently call wait on the main thread if there's contention prepared_frame: AtomicU64, processed_frame: AtomicU64, condvar: Condvar, } pub struct WebGLSwapchain { sync: Arc<GLThreadSync>, surface: Arc<WebGLSurface>, width: u32, height: u32, backbuffer_view: Arc<WebGLTextureView>, sender: GLThreadSender, allocator: Arc<WebGLHandleAllocator>, } impl WebGLSwapchain { pub fn new(surface: &Arc<WebGLSurface>, sender: &GLThreadSender, allocator: &Arc<WebGLHandleAllocator>) -> Self { let handle = allocator.new_texture_handle(); let backbuffer = Arc::new(WebGLTexture::new(handle, &TextureInfo { dimension: TextureDimension::Dim2D, format: Format::RGBA8UNorm, width: surface.width, height: surface.height, depth: 1, mip_levels: 1, array_length: 1, samples: SampleCount::Samples1, usage: TextureUsage::RENDER_TARGET, supports_srgb: false, }, sender)); let view = Arc::new(WebGLTextureView::new(&backbuffer, &TextureViewInfo::default())); Self { sync: Arc::new(GLThreadSync { empty_mutex: Mutex::new(()), condvar: Condvar::new(), prepared_frame: AtomicU64::new(0), processed_frame: AtomicU64::new(0), }), surface: surface.clone(), width: surface.width, height: surface.height, backbuffer_view: view, sender: sender.clone(), allocator: allocator.clone(), } } pub(crate) fn present(&self) { self.sync.prepared_frame.fetch_add(1, Ordering::SeqCst); let c_sync = self.sync.clone(); let backbuffer_handle = self.backbuffer_view.texture().handle(); let info = self.backbuffer_view.texture().info(); let width = info.width as i32; let height = info.height as i32; self.sender.send(Box::new(move |device| { let mut rts: [Option<WebGLTextureHandleView>; 8] = Default::default(); rts[0] = Some(WebGLTextureHandleView { texture: backbuffer_handle, array_layer: 0, mip: 0, }); let read_fb = device.get_framebuffer(&rts, None, Format::Unknown); device.bind_framebuffer(WebGl2RenderingContext::DRAW_FRAMEBUFFER, None); device.bind_framebuffer(WebGl2RenderingContext::READ_FRAMEBUFFER, Some(&read_fb)); device.blit_framebuffer(0, 0, width, height, 0, 0, width, height, WebGl2RenderingContext::COLOR_BUFFER_BIT, WebGl2RenderingContext::LINEAR); c_sync.processed_frame.fetch_add(1, Ordering::SeqCst); c_sync.condvar.notify_all(); })); } } impl Swapchain<WebGLBackend> for WebGLSwapchain { fn recreate(old: &Self, _width: u32, _height: u32) -> Result<std::sync::Arc<Self>, sourcerenderer_core::graphics::SwapchainError> { Ok( Arc::new(WebGLSwapchain::new(&old.surface, &old.sender, &old.allocator)) ) } fn recreate_on_surface(old: &Self, surface: &std::sync::Arc<WebGLSurface>, _width: u32, _height: u32) -> Result<std::sync::Arc<Self>, sourcerenderer_core::graphics::SwapchainError> { Ok( Arc::new(WebGLSwapchain::new(&surface, &old.sender, &old.allocator)) ) } fn sample_count(&self) -> sourcerenderer_core::graphics::SampleCount { SampleCount::Samples1 } fn format(&self) -> sourcerenderer_core::graphics::Format { Format::Unknown } fn surface(&self) -> &std::sync::Arc<WebGLSurface> { &self.surface } fn prepare_back_buffer(&self, _semaphore: &Arc<WebGLSemaphore>) -> Option<Arc<WebGLTextureView>> { let guard = self.sync.empty_mutex.lock().unwrap(); let _new_guard = self.sync.condvar.wait_while(guard, |_| self.sync.processed_frame.load(Ordering::SeqCst) + 1 < self.sync.prepared_frame.load(Ordering::SeqCst)).unwrap(); Some(self.backbuffer_view.clone()) } fn transform(&self) -> sourcerenderer_core::Matrix4 { sourcerenderer_core::Matrix4::identity() } fn width(&self) -> u32 { self.width } fn height(&self) -> u32 { self.height } }
#[macro_use] extern crate conrod; mod gui; mod config; mod gui_result; mod reasonable_main; pub use gui::{run, run_config}; pub use config::Config; pub use gui_result::GuiResult; pub use reasonable_main::{reasonable_main, Command}; pub use conrod::color;
use crate::codegen::segment::*; use crate::parser::Segment; use crate::parser::Source; use anyhow::Result; pub fn gen_push(vm_name: &str, seg: Segment, index: i64, _source: Source) -> Result<String> { let asm = vec![format!("// push {:?} {}", seg, index), gen_segment_read(vm_name, seg, index), gen_stack_push()?].join("\n"); Ok(asm) } // push D-register value to stack top pub fn gen_stack_push() -> Result<String> { let asm = r#"@SP // push stack A=M M=D @SP M=M+1 "#; Ok(asm.to_string()) } // pop stack top value to D-register pub fn gen_stack_pop() -> Result<String> { let asm = r#"@SP // pop stack to D-register AM=M-1 D=M "#; Ok(asm.to_string()) } pub fn gen_pop(vm_name: &str, seg: Segment, index: i64, _source: Source) -> Result<String> { let asm = vec![format!("// pop {:?} {}", seg, index), gen_stack_pop()?, gen_segment_write(vm_name, seg, index)].join("\n"); Ok(asm) }
#[macro_use] extern crate error_chain; extern crate url; mod errors; mod url_example; pub fn run() { //let run = url_example::run_parse; //let run = url_example::run_base_url; //let run = url_example::run_join; //let run = url_example::run_exposes; //let run = url_example::run_origin; let run = url_example::run_positon; if let Err(ref e) = run() { println!("error: {}", e); for e in e.iter().skip(1) { println!(" caused by: {}", e); } if let Some(backtrace) = e.backtrace() { println!("backtrace: {:?}", backtrace); } std::process::exit(1) } }
use std::env; use std::error::Error; use std::fs; use bioinformatics_algorithms::revc; fn main() -> Result<(), Box<dyn Error>> { let input: String = env::args() .nth(1) .unwrap_or("data/rosalind_ba1c.txt".into()); let data = fs::read_to_string(input)?; let mut lines = data.lines(); let text = lines.next().unwrap(); println!("{}", revc(text)); Ok(()) }
/* * Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2. * * Note: * The length of both num1 and num2 is < 5100. * Both num1 and num2 contains only digits 0-9. * Both num1 and num2 does not contain any leading zero. * You must not use any built-in BigInteger library or convert the inputs to integer directly. */ pub fn add_string(num1: String, num2: String) -> String { let (p1, p2) = pad_inputs(num1, num2); let mut index = p1.len(); let mut carry = 0; let mut res: Vec<u32> = vec![]; while index > 0 { let a = p1[index-1].to_digit(10).unwrap_or(0); let b = p2[index-1].to_digit(10).unwrap_or(0); let tmp_sum = a + b + carry; if tmp_sum >= 10 { let val = tmp_sum % 10; carry = 1; res.push(val); } else { let val = tmp_sum; carry = 0; res.push(val); } index -= 1; if index == 0 && carry == 1 { res.push(carry) } } res.reverse(); let ans = res.into_iter().map(|i| i.to_string()).collect::<String>(); return ans } fn pad_inputs(num1: String, num2: String) -> (Vec<char>, Vec<char>) { let mut chars1: Vec<char> = num1.chars().collect(); let mut chars2: Vec<char> = num2.chars().collect(); let mut p1; let mut p2; let len1 = chars1.len(); let len2 = chars2.len(); if len1 > len2 { let pad = len1 - len2; p2 = vec!['0'; pad]; p2.append(&mut chars2); p1 = chars1; } else if len1 < len2 { let pad = len2 - len1; p1 = vec!['0'; pad]; p1.append(&mut chars1); p2 = chars2; } else { p1 = chars1; p2 = chars2; } return (p1, p2) } #[cfg(test)] mod test { use super::add_string; #[test] fn example1() { let num1 = String::from("1234"); let num2 = String::from("567"); assert_eq!(add_string(num1, num2), String::from("1801")); } #[test] fn example2() { let num1 = String::from("123"); let num2 = String::from("5678"); assert_eq!(add_string(num1, num2), String::from("5801")); } #[test] fn example3() { let num1 = String::from("1234"); let num2 = String::from("5678"); assert_eq!(add_string(num1, num2), String::from("6912")); } #[test] fn example4() { let num1 = String::from("6913259244"); let num2 = String::from("71103343"); assert_eq!(add_string(num1, num2), String::from("6984362587")); } #[test] fn example5() { let num1 = String::from("401716832807512840963"); let num2 = String::from("167141802233061013023557397451289113296441069"); assert_eq!(add_string(num1, num2), String::from("167141802233061013023557799168121920809282032")); } #[test] fn example6() { let num1 = String::from("1"); let num2 = String::from("9"); assert_eq!(add_string(num1, num2), String::from("10")); } }
use core::{ptr, slice}; /// An iterator that removes the items from a `SmallVec` and yields them by value. /// /// Returned from [`SmallVec::drain`][1]. /// /// [1]: struct.SmallVec.html#method.drain pub struct Drain<'a, T: 'a> { pub(crate) iter: slice::IterMut<'a, T>, } impl<'a, T: 'a> Iterator for Drain<'a, T> { type Item = T; #[inline] fn next(&mut self) -> Option<T> { self.iter .next() .map(|reference| unsafe { ptr::read(reference) }) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { self.iter.size_hint() } } impl<'a, T: 'a> DoubleEndedIterator for Drain<'a, T> { #[inline] fn next_back(&mut self) -> Option<T> { self.iter .next_back() .map(|reference| unsafe { ptr::read(reference) }) } } impl<'a, T> ExactSizeIterator for Drain<'a, T> {} impl<'a, T: 'a> Drop for Drain<'a, T> { fn drop(&mut self) { // Destroy the remaining elements. for _ in self.by_ref() {} } }
#[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::CFG { #[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 = "Possible values of the field `ENABLE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENABLER { #[doc = "Disabled. The USART is disabled and the internal state machine and counters are reset. While Enable = 0, all USART interrupts are disabled. When Enable is set again, CFG and most other control bits remain unchanged. For instance, when re-enabled, the USART will immediately generate a TxRdy interrupt if enabled because the transmitter has been reset and is therefore available."] DISABLED_THE_USART_, #[doc = "Enabled. The USART is enabled for operation."] ENABLED_THE_USART_I, } impl ENABLER { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { ENABLER::DISABLED_THE_USART_ => false, ENABLER::ENABLED_THE_USART_I => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENABLER { match value { false => ENABLER::DISABLED_THE_USART_, true => ENABLER::ENABLED_THE_USART_I, } } #[doc = "Checks if the value of the field is `DISABLED_THE_USART_`"] #[inline] pub fn is_disabled_the_usart_(&self) -> bool { *self == ENABLER::DISABLED_THE_USART_ } #[doc = "Checks if the value of the field is `ENABLED_THE_USART_I`"] #[inline] pub fn is_enabled_the_usart_i(&self) -> bool { *self == ENABLER::ENABLED_THE_USART_I } } #[doc = "Possible values of the field `DATALEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DATALENR { #[doc = "7 bit Data length."] _7_BIT_DATA_LENGTH_, #[doc = "8 bit Data length."] _8_BIT_DATA_LENGTH_, #[doc = "9 bit data length. The 9th bit is commonly used for addressing in multidrop mode. See the ADDRDET bit in the CTRL register."] _9_BIT_DATA_LENGTH_T, #[doc = "Reserved."] RESERVED_, } impl DATALENR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { DATALENR::_7_BIT_DATA_LENGTH_ => 0, DATALENR::_8_BIT_DATA_LENGTH_ => 1, DATALENR::_9_BIT_DATA_LENGTH_T => 2, DATALENR::RESERVED_ => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> DATALENR { match value { 0 => DATALENR::_7_BIT_DATA_LENGTH_, 1 => DATALENR::_8_BIT_DATA_LENGTH_, 2 => DATALENR::_9_BIT_DATA_LENGTH_T, 3 => DATALENR::RESERVED_, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `_7_BIT_DATA_LENGTH_`"] #[inline] pub fn is_7_bit_data_length_(&self) -> bool { *self == DATALENR::_7_BIT_DATA_LENGTH_ } #[doc = "Checks if the value of the field is `_8_BIT_DATA_LENGTH_`"] #[inline] pub fn is_8_bit_data_length_(&self) -> bool { *self == DATALENR::_8_BIT_DATA_LENGTH_ } #[doc = "Checks if the value of the field is `_9_BIT_DATA_LENGTH_T`"] #[inline] pub fn is_9_bit_data_length_t(&self) -> bool { *self == DATALENR::_9_BIT_DATA_LENGTH_T } #[doc = "Checks if the value of the field is `RESERVED_`"] #[inline] pub fn is_reserved_(&self) -> bool { *self == DATALENR::RESERVED_ } } #[doc = "Possible values of the field `PARITYSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PARITYSELR { #[doc = "No parity."] NO_PARITY_, #[doc = "Reserved."] RESERVED_, #[doc = "Even parity. Adds a bit to each character such that the number of 1s in a transmitted character is even, and the number of 1s in a received character is expected to be even."] EVEN_PARITY_ADDS_A_, #[doc = "Odd parity. Adds a bit to each character such that the number of 1s in a transmitted character is odd, and the number of 1s in a received character is expected to be odd."] ODD_PARITY_ADDS_A_B, } impl PARITYSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bits(&self) -> u8 { match *self { PARITYSELR::NO_PARITY_ => 0, PARITYSELR::RESERVED_ => 1, PARITYSELR::EVEN_PARITY_ADDS_A_ => 2, PARITYSELR::ODD_PARITY_ADDS_A_B => 3, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: u8) -> PARITYSELR { match value { 0 => PARITYSELR::NO_PARITY_, 1 => PARITYSELR::RESERVED_, 2 => PARITYSELR::EVEN_PARITY_ADDS_A_, 3 => PARITYSELR::ODD_PARITY_ADDS_A_B, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `NO_PARITY_`"] #[inline] pub fn is_no_parity_(&self) -> bool { *self == PARITYSELR::NO_PARITY_ } #[doc = "Checks if the value of the field is `RESERVED_`"] #[inline] pub fn is_reserved_(&self) -> bool { *self == PARITYSELR::RESERVED_ } #[doc = "Checks if the value of the field is `EVEN_PARITY_ADDS_A_`"] #[inline] pub fn is_even_parity_adds_a_(&self) -> bool { *self == PARITYSELR::EVEN_PARITY_ADDS_A_ } #[doc = "Checks if the value of the field is `ODD_PARITY_ADDS_A_B`"] #[inline] pub fn is_odd_parity_adds_a_b(&self) -> bool { *self == PARITYSELR::ODD_PARITY_ADDS_A_B } } #[doc = "Possible values of the field `STOPLEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum STOPLENR { #[doc = "1 stop bit."] _1_STOP_BIT_, #[doc = "2 stop bits. This setting should only be used for asynchronous communication."] _2_STOP_BITS_THIS_SE, } impl STOPLENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { STOPLENR::_1_STOP_BIT_ => false, STOPLENR::_2_STOP_BITS_THIS_SE => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> STOPLENR { match value { false => STOPLENR::_1_STOP_BIT_, true => STOPLENR::_2_STOP_BITS_THIS_SE, } } #[doc = "Checks if the value of the field is `_1_STOP_BIT_`"] #[inline] pub fn is_1_stop_bit_(&self) -> bool { *self == STOPLENR::_1_STOP_BIT_ } #[doc = "Checks if the value of the field is `_2_STOP_BITS_THIS_SE`"] #[inline] pub fn is_2_stop_bits_this_se(&self) -> bool { *self == STOPLENR::_2_STOP_BITS_THIS_SE } } #[doc = "Possible values of the field `CTSEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CTSENR { #[doc = "No flow control. The transmitter does not receive any automatic flow control signal."] NO_FLOW_CONTROL_THE, #[doc = "Flow control enabled. The transmitter uses external or internal CTS for flow control purposes."] FLOW_CONTROL_ENABLED, } impl CTSENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { CTSENR::NO_FLOW_CONTROL_THE => false, CTSENR::FLOW_CONTROL_ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> CTSENR { match value { false => CTSENR::NO_FLOW_CONTROL_THE, true => CTSENR::FLOW_CONTROL_ENABLED, } } #[doc = "Checks if the value of the field is `NO_FLOW_CONTROL_THE`"] #[inline] pub fn is_no_flow_control_the(&self) -> bool { *self == CTSENR::NO_FLOW_CONTROL_THE } #[doc = "Checks if the value of the field is `FLOW_CONTROL_ENABLED`"] #[inline] pub fn is_flow_control_enabled(&self) -> bool { *self == CTSENR::FLOW_CONTROL_ENABLED } } #[doc = "Possible values of the field `SYNCEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SYNCENR { #[doc = "Asynchronous mode is selected."] ASYNCHRONOUS_MODE_IS, #[doc = "Synchronous mode is selected."] SYNCHRONOUS_MODE_IS_, } impl SYNCENR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SYNCENR::ASYNCHRONOUS_MODE_IS => false, SYNCENR::SYNCHRONOUS_MODE_IS_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SYNCENR { match value { false => SYNCENR::ASYNCHRONOUS_MODE_IS, true => SYNCENR::SYNCHRONOUS_MODE_IS_, } } #[doc = "Checks if the value of the field is `ASYNCHRONOUS_MODE_IS`"] #[inline] pub fn is_asynchronous_mode_is(&self) -> bool { *self == SYNCENR::ASYNCHRONOUS_MODE_IS } #[doc = "Checks if the value of the field is `SYNCHRONOUS_MODE_IS_`"] #[inline] pub fn is_synchronous_mode_is_(&self) -> bool { *self == SYNCENR::SYNCHRONOUS_MODE_IS_ } } #[doc = "Possible values of the field `CLKPOL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CLKPOLR { #[doc = "Falling edge. Un_RXD is sampled on the falling edge of SCLK."] FALLING_EDGE_UN_RXD, #[doc = "Rising edge. Un_RXD is sampled on the rising edge of SCLK."] RISING_EDGE_UN_RXD_, } impl CLKPOLR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { CLKPOLR::FALLING_EDGE_UN_RXD => false, CLKPOLR::RISING_EDGE_UN_RXD_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> CLKPOLR { match value { false => CLKPOLR::FALLING_EDGE_UN_RXD, true => CLKPOLR::RISING_EDGE_UN_RXD_, } } #[doc = "Checks if the value of the field is `FALLING_EDGE_UN_RXD`"] #[inline] pub fn is_falling_edge_un_rxd(&self) -> bool { *self == CLKPOLR::FALLING_EDGE_UN_RXD } #[doc = "Checks if the value of the field is `RISING_EDGE_UN_RXD_`"] #[inline] pub fn is_rising_edge_un_rxd_(&self) -> bool { *self == CLKPOLR::RISING_EDGE_UN_RXD_ } } #[doc = "Possible values of the field `SYNCMST`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SYNCMSTR { #[doc = "Slave. When synchronous mode is enabled, the USART is a slave."] SLAVE_WHEN_SYNCHRON, #[doc = "Master. When synchronous mode is enabled, the USART is a master. In asynchronous mode, the baud rate clock will be output on SCLK if it is connected to a pin."] MASTER_WHEN_SYNCHRO, } impl SYNCMSTR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { SYNCMSTR::SLAVE_WHEN_SYNCHRON => false, SYNCMSTR::MASTER_WHEN_SYNCHRO => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SYNCMSTR { match value { false => SYNCMSTR::SLAVE_WHEN_SYNCHRON, true => SYNCMSTR::MASTER_WHEN_SYNCHRO, } } #[doc = "Checks if the value of the field is `SLAVE_WHEN_SYNCHRON`"] #[inline] pub fn is_slave_when_synchron(&self) -> bool { *self == SYNCMSTR::SLAVE_WHEN_SYNCHRON } #[doc = "Checks if the value of the field is `MASTER_WHEN_SYNCHRO`"] #[inline] pub fn is_master_when_synchro(&self) -> bool { *self == SYNCMSTR::MASTER_WHEN_SYNCHRO } } #[doc = "Possible values of the field `LOOP`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LOOPR { #[doc = "Normal operation."] NORMAL_OPERATION_, #[doc = "Loopback mode. This provides a mechanism to perform diagnostic loopback testing for USART data. Serial data from the transmitter (Un_TXD) is connected internally to serial input of the receive (Un_RXD). Un_TXD and Un_RTS activity will also appear on external pins if these functions are configured to appear on device pins. The receiver RTS signal is also looped back to CTS and performs flow control if enabled by CTSEN."] LOOPBACK_MODE_THIS_, } impl LOOPR { #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { match *self { LOOPR::NORMAL_OPERATION_ => false, LOOPR::LOOPBACK_MODE_THIS_ => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> LOOPR { match value { false => LOOPR::NORMAL_OPERATION_, true => LOOPR::LOOPBACK_MODE_THIS_, } } #[doc = "Checks if the value of the field is `NORMAL_OPERATION_`"] #[inline] pub fn is_normal_operation_(&self) -> bool { *self == LOOPR::NORMAL_OPERATION_ } #[doc = "Checks if the value of the field is `LOOPBACK_MODE_THIS_`"] #[inline] pub fn is_loopback_mode_this_(&self) -> bool { *self == LOOPR::LOOPBACK_MODE_THIS_ } } #[doc = "Values that can be written to the field `ENABLE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENABLEW { #[doc = "Disabled. The USART is disabled and the internal state machine and counters are reset. While Enable = 0, all USART interrupts are disabled. When Enable is set again, CFG and most other control bits remain unchanged. For instance, when re-enabled, the USART will immediately generate a TxRdy interrupt if enabled because the transmitter has been reset and is therefore available."] DISABLED_THE_USART_, #[doc = "Enabled. The USART is enabled for operation."] ENABLED_THE_USART_I, } impl ENABLEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENABLEW::DISABLED_THE_USART_ => false, ENABLEW::ENABLED_THE_USART_I => true, } } } #[doc = r" Proxy"] pub struct _ENABLEW<'a> { w: &'a mut W, } impl<'a> _ENABLEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENABLEW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disabled. The USART is disabled and the internal state machine and counters are reset. While Enable = 0, all USART interrupts are disabled. When Enable is set again, CFG and most other control bits remain unchanged. For instance, when re-enabled, the USART will immediately generate a TxRdy interrupt if enabled because the transmitter has been reset and is therefore available."] #[inline] pub fn disabled_the_usart_(self) -> &'a mut W { self.variant(ENABLEW::DISABLED_THE_USART_) } #[doc = "Enabled. The USART is enabled for operation."] #[inline] pub fn enabled_the_usart_i(self) -> &'a mut W { self.variant(ENABLEW::ENABLED_THE_USART_I) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `DATALEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DATALENW { #[doc = "7 bit Data length."] _7_BIT_DATA_LENGTH_, #[doc = "8 bit Data length."] _8_BIT_DATA_LENGTH_, #[doc = "9 bit data length. The 9th bit is commonly used for addressing in multidrop mode. See the ADDRDET bit in the CTRL register."] _9_BIT_DATA_LENGTH_T, #[doc = "Reserved."] RESERVED_, } impl DATALENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { DATALENW::_7_BIT_DATA_LENGTH_ => 0, DATALENW::_8_BIT_DATA_LENGTH_ => 1, DATALENW::_9_BIT_DATA_LENGTH_T => 2, DATALENW::RESERVED_ => 3, } } } #[doc = r" Proxy"] pub struct _DATALENW<'a> { w: &'a mut W, } impl<'a> _DATALENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: DATALENW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "7 bit Data length."] #[inline] pub fn _7_bit_data_length_(self) -> &'a mut W { self.variant(DATALENW::_7_BIT_DATA_LENGTH_) } #[doc = "8 bit Data length."] #[inline] pub fn _8_bit_data_length_(self) -> &'a mut W { self.variant(DATALENW::_8_BIT_DATA_LENGTH_) } #[doc = "9 bit data length. The 9th bit is commonly used for addressing in multidrop mode. See the ADDRDET bit in the CTRL register."] #[inline] pub fn _9_bit_data_length_t(self) -> &'a mut W { self.variant(DATALENW::_9_BIT_DATA_LENGTH_T) } #[doc = "Reserved."] #[inline] pub fn reserved_(self) -> &'a mut W { self.variant(DATALENW::RESERVED_) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `PARITYSEL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum PARITYSELW { #[doc = "No parity."] NO_PARITY_, #[doc = "Reserved."] RESERVED_, #[doc = "Even parity. Adds a bit to each character such that the number of 1s in a transmitted character is even, and the number of 1s in a received character is expected to be even."] EVEN_PARITY_ADDS_A_, #[doc = "Odd parity. Adds a bit to each character such that the number of 1s in a transmitted character is odd, and the number of 1s in a received character is expected to be odd."] ODD_PARITY_ADDS_A_B, } impl PARITYSELW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> u8 { match *self { PARITYSELW::NO_PARITY_ => 0, PARITYSELW::RESERVED_ => 1, PARITYSELW::EVEN_PARITY_ADDS_A_ => 2, PARITYSELW::ODD_PARITY_ADDS_A_B => 3, } } } #[doc = r" Proxy"] pub struct _PARITYSELW<'a> { w: &'a mut W, } impl<'a> _PARITYSELW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: PARITYSELW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "No parity."] #[inline] pub fn no_parity_(self) -> &'a mut W { self.variant(PARITYSELW::NO_PARITY_) } #[doc = "Reserved."] #[inline] pub fn reserved_(self) -> &'a mut W { self.variant(PARITYSELW::RESERVED_) } #[doc = "Even parity. Adds a bit to each character such that the number of 1s in a transmitted character is even, and the number of 1s in a received character is expected to be even."] #[inline] pub fn even_parity_adds_a_(self) -> &'a mut W { self.variant(PARITYSELW::EVEN_PARITY_ADDS_A_) } #[doc = "Odd parity. Adds a bit to each character such that the number of 1s in a transmitted character is odd, and the number of 1s in a received character is expected to be odd."] #[inline] pub fn odd_parity_adds_a_b(self) -> &'a mut W { self.variant(PARITYSELW::ODD_PARITY_ADDS_A_B) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bits(self, value: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `STOPLEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum STOPLENW { #[doc = "1 stop bit."] _1_STOP_BIT_, #[doc = "2 stop bits. This setting should only be used for asynchronous communication."] _2_STOP_BITS_THIS_SE, } impl STOPLENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { STOPLENW::_1_STOP_BIT_ => false, STOPLENW::_2_STOP_BITS_THIS_SE => true, } } } #[doc = r" Proxy"] pub struct _STOPLENW<'a> { w: &'a mut W, } impl<'a> _STOPLENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: STOPLENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "1 stop bit."] #[inline] pub fn _1_stop_bit_(self) -> &'a mut W { self.variant(STOPLENW::_1_STOP_BIT_) } #[doc = "2 stop bits. This setting should only be used for asynchronous communication."] #[inline] pub fn _2_stop_bits_this_se(self) -> &'a mut W { self.variant(STOPLENW::_2_STOP_BITS_THIS_SE) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 6; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `CTSEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CTSENW { #[doc = "No flow control. The transmitter does not receive any automatic flow control signal."] NO_FLOW_CONTROL_THE, #[doc = "Flow control enabled. The transmitter uses external or internal CTS for flow control purposes."] FLOW_CONTROL_ENABLED, } impl CTSENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { CTSENW::NO_FLOW_CONTROL_THE => false, CTSENW::FLOW_CONTROL_ENABLED => true, } } } #[doc = r" Proxy"] pub struct _CTSENW<'a> { w: &'a mut W, } impl<'a> _CTSENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: CTSENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "No flow control. The transmitter does not receive any automatic flow control signal."] #[inline] pub fn no_flow_control_the(self) -> &'a mut W { self.variant(CTSENW::NO_FLOW_CONTROL_THE) } #[doc = "Flow control enabled. The transmitter uses external or internal CTS for flow control purposes."] #[inline] pub fn flow_control_enabled(self) -> &'a mut W { self.variant(CTSENW::FLOW_CONTROL_ENABLED) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 9; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SYNCEN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SYNCENW { #[doc = "Asynchronous mode is selected."] ASYNCHRONOUS_MODE_IS, #[doc = "Synchronous mode is selected."] SYNCHRONOUS_MODE_IS_, } impl SYNCENW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SYNCENW::ASYNCHRONOUS_MODE_IS => false, SYNCENW::SYNCHRONOUS_MODE_IS_ => true, } } } #[doc = r" Proxy"] pub struct _SYNCENW<'a> { w: &'a mut W, } impl<'a> _SYNCENW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SYNCENW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Asynchronous mode is selected."] #[inline] pub fn asynchronous_mode_is(self) -> &'a mut W { self.variant(SYNCENW::ASYNCHRONOUS_MODE_IS) } #[doc = "Synchronous mode is selected."] #[inline] pub fn synchronous_mode_is_(self) -> &'a mut W { self.variant(SYNCENW::SYNCHRONOUS_MODE_IS_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 11; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `CLKPOL`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CLKPOLW { #[doc = "Falling edge. Un_RXD is sampled on the falling edge of SCLK."] FALLING_EDGE_UN_RXD, #[doc = "Rising edge. Un_RXD is sampled on the rising edge of SCLK."] RISING_EDGE_UN_RXD_, } impl CLKPOLW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { CLKPOLW::FALLING_EDGE_UN_RXD => false, CLKPOLW::RISING_EDGE_UN_RXD_ => true, } } } #[doc = r" Proxy"] pub struct _CLKPOLW<'a> { w: &'a mut W, } impl<'a> _CLKPOLW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: CLKPOLW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Falling edge. Un_RXD is sampled on the falling edge of SCLK."] #[inline] pub fn falling_edge_un_rxd(self) -> &'a mut W { self.variant(CLKPOLW::FALLING_EDGE_UN_RXD) } #[doc = "Rising edge. Un_RXD is sampled on the rising edge of SCLK."] #[inline] pub fn rising_edge_un_rxd_(self) -> &'a mut W { self.variant(CLKPOLW::RISING_EDGE_UN_RXD_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 12; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `SYNCMST`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SYNCMSTW { #[doc = "Slave. When synchronous mode is enabled, the USART is a slave."] SLAVE_WHEN_SYNCHRON, #[doc = "Master. When synchronous mode is enabled, the USART is a master. In asynchronous mode, the baud rate clock will be output on SCLK if it is connected to a pin."] MASTER_WHEN_SYNCHRO, } impl SYNCMSTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SYNCMSTW::SLAVE_WHEN_SYNCHRON => false, SYNCMSTW::MASTER_WHEN_SYNCHRO => true, } } } #[doc = r" Proxy"] pub struct _SYNCMSTW<'a> { w: &'a mut W, } impl<'a> _SYNCMSTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SYNCMSTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Slave. When synchronous mode is enabled, the USART is a slave."] #[inline] pub fn slave_when_synchron(self) -> &'a mut W { self.variant(SYNCMSTW::SLAVE_WHEN_SYNCHRON) } #[doc = "Master. When synchronous mode is enabled, the USART is a master. In asynchronous mode, the baud rate clock will be output on SCLK if it is connected to a pin."] #[inline] pub fn master_when_synchro(self) -> &'a mut W { self.variant(SYNCMSTW::MASTER_WHEN_SYNCHRO) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 14; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = "Values that can be written to the field `LOOP`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum LOOPW { #[doc = "Normal operation."] NORMAL_OPERATION_, #[doc = "Loopback mode. This provides a mechanism to perform diagnostic loopback testing for USART data. Serial data from the transmitter (Un_TXD) is connected internally to serial input of the receive (Un_RXD). Un_TXD and Un_RTS activity will also appear on external pins if these functions are configured to appear on device pins. The receiver RTS signal is also looped back to CTS and performs flow control if enabled by CTSEN."] LOOPBACK_MODE_THIS_, } impl LOOPW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { LOOPW::NORMAL_OPERATION_ => false, LOOPW::LOOPBACK_MODE_THIS_ => true, } } } #[doc = r" Proxy"] pub struct _LOOPW<'a> { w: &'a mut W, } impl<'a> _LOOPW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: LOOPW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Normal operation."] #[inline] pub fn normal_operation_(self) -> &'a mut W { self.variant(LOOPW::NORMAL_OPERATION_) } #[doc = "Loopback mode. This provides a mechanism to perform diagnostic loopback testing for USART data. Serial data from the transmitter (Un_TXD) is connected internally to serial input of the receive (Un_RXD). Un_TXD and Un_RTS activity will also appear on external pins if these functions are configured to appear on device pins. The receiver RTS signal is also looped back to CTS and performs flow control if enabled by CTSEN."] #[inline] pub fn loopback_mode_this_(self) -> &'a mut W { self.variant(LOOPW::LOOPBACK_MODE_THIS_) } #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 15; 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 = "Bit 0 - USART Enable."] #[inline] pub fn enable(&self) -> ENABLER { ENABLER::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bits 2:3 - Selects the data size for the USART."] #[inline] pub fn datalen(&self) -> DATALENR { DATALENR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bits 4:5 - Selects what type of parity is used by the USART."] #[inline] pub fn paritysel(&self) -> PARITYSELR { PARITYSELR::_from({ const MASK: u8 = 3; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 }) } #[doc = "Bit 6 - Number of stop bits appended to transmitted data. Only a single stop bit is required for received data."] #[inline] pub fn stoplen(&self) -> STOPLENR { STOPLENR::_from({ const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 9 - CTS Enable. Determines whether CTS is used for flow control. CTS can be from the input pin, or from the USART's own RTS if loopback mode is enabled. See Section 16.7.3 for more information."] #[inline] pub fn ctsen(&self) -> CTSENR { CTSENR::_from({ const MASK: bool = true; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 11 - Selects synchronous or asynchronous operation."] #[inline] pub fn syncen(&self) -> SYNCENR { SYNCENR::_from({ const MASK: bool = true; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 12 - Selects the clock polarity and sampling edge of received data in synchronous mode."] #[inline] pub fn clkpol(&self) -> CLKPOLR { CLKPOLR::_from({ const MASK: bool = true; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 14 - Synchronous mode Master select."] #[inline] pub fn syncmst(&self) -> SYNCMSTR { SYNCMSTR::_from({ const MASK: bool = true; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 15 - Selects data loopback mode."] #[inline] pub fn loop_(&self) -> LOOPR { LOOPR::_from({ const MASK: bool = true; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - USART Enable."] #[inline] pub fn enable(&mut self) -> _ENABLEW { _ENABLEW { w: self } } #[doc = "Bits 2:3 - Selects the data size for the USART."] #[inline] pub fn datalen(&mut self) -> _DATALENW { _DATALENW { w: self } } #[doc = "Bits 4:5 - Selects what type of parity is used by the USART."] #[inline] pub fn paritysel(&mut self) -> _PARITYSELW { _PARITYSELW { w: self } } #[doc = "Bit 6 - Number of stop bits appended to transmitted data. Only a single stop bit is required for received data."] #[inline] pub fn stoplen(&mut self) -> _STOPLENW { _STOPLENW { w: self } } #[doc = "Bit 9 - CTS Enable. Determines whether CTS is used for flow control. CTS can be from the input pin, or from the USART's own RTS if loopback mode is enabled. See Section 16.7.3 for more information."] #[inline] pub fn ctsen(&mut self) -> _CTSENW { _CTSENW { w: self } } #[doc = "Bit 11 - Selects synchronous or asynchronous operation."] #[inline] pub fn syncen(&mut self) -> _SYNCENW { _SYNCENW { w: self } } #[doc = "Bit 12 - Selects the clock polarity and sampling edge of received data in synchronous mode."] #[inline] pub fn clkpol(&mut self) -> _CLKPOLW { _CLKPOLW { w: self } } #[doc = "Bit 14 - Synchronous mode Master select."] #[inline] pub fn syncmst(&mut self) -> _SYNCMSTW { _SYNCMSTW { w: self } } #[doc = "Bit 15 - Selects data loopback mode."] #[inline] pub fn loop_(&mut self) -> _LOOPW { _LOOPW { w: self } } }
mod schema; use diesel::prelude::*; use model::*; use std::collections::HashMap; use std::str::FromStr; use thiserror::Error; #[macro_use] extern crate diesel; pub struct SqliteClient { scorelog_db_url: String, song_db_url: String, score_db_url: String, } impl SqliteClient { fn new(scorelog_db_url: String, song_db_url: String, score_db_url: String) -> SqliteClient { SqliteClient { scorelog_db_url, score_db_url, song_db_url, } } pub fn for_score(score_db_url: &str, scorelog_db_url: &str) -> SqliteClient { SqliteClient::new(scorelog_db_url.into(), "".into(), score_db_url.into()) } pub fn for_song(song_db_url: &str) -> SqliteClient { SqliteClient::new("".into(), song_db_url.into(), "".into()) } fn establish_connection(url: &str) -> SqliteResult<SqliteConnection> { let connection = SqliteConnection::establish(url)?; Ok(connection) } fn score_log(&self) -> Result<HashMap<ScoreId, SnapShots>, SqliteError> { use schema::score_log::scorelog::dsl::*; let mut connection = Self::establish_connection(&self.scorelog_db_url)?; let record: Vec<schema::score_log::ScoreLog> = scorelog.load(&mut connection)?; Ok(record.into_iter().fold(HashMap::new(), |mut map, row| { map.entry(ScoreId::new( row.sha256.parse().unwrap(), PlayMode::from(row.mode), )) .or_default() .add(SnapShot::from_data( row.clear, row.score, row.combo, row.minbp, row.date as i64, )); map })) } pub fn player(&self) -> SqliteResult<PlayerStats> { use schema::player::player::dsl::*; let mut connection = Self::establish_connection(&self.score_db_url)?; let records: Vec<schema::player::Player> = player.load(&mut connection)?; let mut log = Vec::new(); for row in records { let pl = PlayerStat::new( PlayCount::new(row.playcount), PlayCount::new(row.clear), PlayTime::new(row.playtime), UpdatedAt::from_timestamp(row.date as i64), TotalJudge::new(Judge { early_pgreat: row.epg, late_pgreat: row.lpg, early_great: row.egr, late_great: row.lgr, early_good: row.egd, late_good: row.lgd, early_bad: row.ebd, late_bad: row.lbd, early_poor: row.epr, late_poor: row.lpr, early_miss: row.ems, late_miss: row.lms, }), ); log.push(pl); } Ok(PlayerStats::new(log)) } pub fn song_data(&self) -> Result<Songs, SqliteError> { let mut connection = Self::establish_connection(&self.song_db_url)?; let record: Vec<schema::song::Song> = schema::song::song::table.load(&mut connection)?; Ok(record .iter() .fold(SongsBuilder::default(), |mut builder, row| { builder.push( HashMd5::from_str(&row.md5).unwrap(), HashSha256::from_str(&row.sha256).unwrap(), Title::new(format!("{}{}", row.title, row.subtitle)), Artist::new(row.artist.clone()), row.notes, IncludeFeatures::from(row.feature), ); builder }) .build()) } pub fn score(&self) -> SqliteResult<Scores> { let mut connection = Self::establish_connection(&self.score_db_url)?; let record: Vec<schema::score::Score> = schema::score::score::table.load(&mut connection)?; let score_log = self.score_log()?; Ok(Scores::create_by_map( record .iter() .map(|row| { let song_id = ScoreId::new(row.sha256.parse().unwrap(), PlayMode::from(row.mode)); (song_id.clone(), { let judge = Judge { early_pgreat: row.epg, late_pgreat: row.lpg, early_great: row.egr, late_great: row.lgr, early_good: row.egd, late_good: row.lgd, early_bad: row.ebd, late_bad: row.lbd, early_poor: row.epr, late_poor: row.lpr, early_miss: row.ems, late_miss: row.lms, }; Score { clear: ClearType::from_integer(row.clear), updated_at: UpdatedAt::from_timestamp(row.date as i64), score: judge.ex_score(), judge, max_combo: MaxCombo::from_combo(row.combo), play_count: PlayCount::new(row.playcount), clear_count: ClearCount::new(row.clearcount), min_bp: MinBP::from_bp(row.minbp), log: score_log.get(&song_id).cloned().unwrap_or_default(), } }) }) .collect::<HashMap<ScoreId, Score>>(), )) } } pub type SqliteResult<T> = Result<T, SqliteError>; #[derive(Debug, Error)] pub enum SqliteError { #[error("ConnectionError {0:?}")] ConnectionError(diesel::ConnectionError), #[error("DieselResultError {0:?}")] DieselResultError(diesel::result::Error), } impl From<diesel::ConnectionError> for SqliteError { fn from(e: ConnectionError) -> Self { SqliteError::ConnectionError(e) } } impl From<diesel::result::Error> for SqliteError { fn from(e: diesel::result::Error) -> Self { SqliteError::DieselResultError(e) } }
extern crate peg; fn main() { peg::cargo_build("src/grammar/smtp.rustpeg"); }
use crate::error::HandleError::*; use serde::Serialize; use std::convert::Infallible; use std::num::ParseIntError; use thiserror::Error; use warp::{http::StatusCode, Rejection, Reply}; #[derive(Debug, Error)] pub enum HandleError { #[error("AuthorizationCodeIsNotFound")] AuthorizationCodeIsNotFound, #[error("AccountIsNotFound: {0:?}")] AccountIsNotFound(anyhow::Error), #[error("AccountIsNotSelected")] AccountIsNotSelected, #[error("AccountSelectionIsInvalid")] AccountSelectionIsInvalid(ParseIntError), #[error("IOError: {0:?}")] IOError(std::io::Error), #[error("MySqlError: {0:?}")] MySqlError(mysql::Error), #[error("SqliteError: {0:?}")] SqliteError(sqlite::SqliteError), #[error("WarpError: {0:?}")] WarpError(warp::Error), #[error("SessionIsNotFound:{0:?}")] SessionError(redis::RedisError), #[error("DirectoryCouldNotCreated")] DirectoryCouldNotCreated, #[error("FileIsNotFound")] FileIsNotFound, #[error("FileIsNotDeleted")] FileIsNotDeleted, #[error("SaveIsNotComplete")] SaveIsNotComplete, #[error("FormIsIncomplete")] FormIsIncomplete, #[error("ChangedNameNotFound")] ChangedNameNotFound, #[error("ChangedVisibilityNotFound")] ChangedVisibilityNotFound, #[error("OAuthGoogleError: {0:?}")] OAuthGoogleError(oauth_google::Error), #[error("OtherError: {0}")] OtherError(anyhow::Error), #[error("RedisError: {0:?}")] RedisError(redis::RedisError), #[error("SerdeJsonError: {0:?}")] SerdeJsonError(serde_json::Error), } #[derive(Serialize)] struct ErrorResponse { error: String, } pub async fn handle_rejection(err: Rejection) -> std::result::Result<impl Reply, Infallible> { let (code, message): (StatusCode, String) = if err.is_not_found() { (StatusCode::NOT_FOUND, "Not Found".into()) } else if let Some(e) = err.find::<HandleError>() { use HandleError::*; ( match e { AuthorizationCodeIsNotFound => StatusCode::BAD_REQUEST, AccountIsNotFound(_) => StatusCode::BAD_REQUEST, AccountIsNotSelected => StatusCode::BAD_REQUEST, AccountSelectionIsInvalid(_) => StatusCode::BAD_REQUEST, WarpError(_) => StatusCode::BAD_REQUEST, FileIsNotFound => StatusCode::OK, SaveIsNotComplete => StatusCode::OK, FileIsNotDeleted => StatusCode::OK, SessionError(_) => StatusCode::UNAUTHORIZED, _ => StatusCode::INTERNAL_SERVER_ERROR, }, e.to_string(), ) } else if err .find::<warp::filters::body::BodyDeserializeError>() .is_some() { (StatusCode::BAD_REQUEST, "Invalid Body".into()) } else if err.find::<warp::reject::MethodNotAllowed>().is_some() { (StatusCode::UNAUTHORIZED, "Method Not Allowed".into()) } else { log::error!("unhandled error: {:?}", err); ( StatusCode::INTERNAL_SERVER_ERROR, "Internal Server Error".into(), ) }; log::error!("{} {}", code, message); let json = warp::reply::json(&ErrorResponse { error: message }); Ok(warp::reply::with_status(json, code)) } impl HandleError { pub fn rejection(self) -> Rejection { warp::reject::custom(self) } } impl warp::reject::Reject for HandleError {} impl From<anyhow::Error> for HandleError { fn from(e: anyhow::Error) -> Self { OtherError(e) } } impl From<std::io::Error> for HandleError { fn from(e: std::io::Error) -> Self { IOError(e) } } impl From<warp::Error> for HandleError { fn from(e: warp::Error) -> Self { WarpError(e) } } impl From<redis::RedisError> for HandleError { fn from(e: redis::RedisError) -> Self { RedisError(e) } } impl From<mysql::Error> for HandleError { fn from(e: mysql::Error) -> Self { MySqlError(e) } } impl From<sqlite::SqliteError> for HandleError { fn from(e: sqlite::SqliteError) -> Self { SqliteError(e) } } impl From<serde_json::Error> for HandleError { fn from(e: serde_json::Error) -> Self { SerdeJsonError(e) } }
mod builder; use self::builder::*; use firefly_diagnostics::CodeMap; use firefly_mlir::{self as mlir, Context, OwnedContext}; use firefly_pass::Pass; use firefly_session::Options; use firefly_syntax_ssa as syntax_ssa; use log::debug; pub struct SsaToMlir<'a> { context: Context, codemap: &'a CodeMap, options: &'a Options, } impl<'a> SsaToMlir<'a> { pub fn new(context: &OwnedContext, codemap: &'a CodeMap, options: &'a Options) -> Self { Self { context: **context, codemap, options, } } } impl<'m> Pass for SsaToMlir<'m> { type Input<'a> = syntax_ssa::Module; type Output<'a> = Result<mlir::OwnedModule, mlir::OwnedModule>; fn run<'a>(&mut self, module: Self::Input<'a>) -> anyhow::Result<Self::Output<'a>> { debug!("building mlir module for {}", module.name()); let builder = ModuleBuilder::new(&module, self.codemap, self.context, self.options); builder.build() } }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use crate::registry::base::{Command, Registry, State}; use crate::switchboard::base::{ SettingAction, SettingActionData, SettingEvent, SettingRequest, SettingResponseResult, SettingType, }; use failure::{format_err, Error, ResultExt}; use fuchsia_async as fasync; use futures::channel::mpsc::UnboundedReceiver; use futures::channel::mpsc::UnboundedSender; use futures::stream::StreamExt; use futures::TryFutureExt; use parking_lot::RwLock; use std::collections::HashMap; use std::sync::Arc; pub struct RegistryImpl { /// A mapping of setting types to senders, used to relay new commands. command_sender_map: HashMap<SettingType, UnboundedSender<Command>>, /// Used to send messages back to the source producing messages on the /// receiver provided at construction. event_sender: UnboundedSender<SettingEvent>, /// A sender handed as part of State::Listen to allow entities to provide /// back updates. /// TODO(SU-334): Investigate restricting the setting type a sender may /// specify to the one registered. notification_sender: UnboundedSender<SettingType>, /// The current types being listened in on. active_listeners: Vec<SettingType>, } impl RegistryImpl { /// Returns a handle to a RegistryImpl which is listening to SettingAction from the /// provided receiver and will send responses/updates on the given sender. pub fn create( sender: UnboundedSender<SettingEvent>, mut receiver: UnboundedReceiver<SettingAction>, ) -> Arc<RwLock<RegistryImpl>> { let (notification_tx, mut notification_rx) = futures::channel::mpsc::unbounded::<SettingType>(); // We must create handle here rather than return back the value as we // reference the registry in the async tasks below. let registry = Arc::new(RwLock::new(Self { command_sender_map: HashMap::new(), event_sender: sender, notification_sender: notification_tx, active_listeners: vec![], })); // An async task is spawned here to listen to the SettingAction for new // directives. Note that the receiver is the one provided in the arguments. { let registry_clone = registry.clone(); fasync::spawn( async move { while let Some(action) = receiver.next().await { registry_clone.write().process_action(action); } Ok(()) } .unwrap_or_else(|_e: failure::Error| {}), ); } // An async task is spawned here to listen for notifications. The receiver // handles notifications from all sources. { let registry_clone = registry.clone(); fasync::spawn( async move { while let Some(setting_type) = notification_rx.next().await { registry_clone.write().notify(setting_type); } Ok(()) } .unwrap_or_else(|_e: failure::Error| {}), ); } return registry; } /// Interpret action from switchboard into registry actions. fn process_action(&mut self, action: SettingAction) { match action.data { SettingActionData::Request(request) => { self.process_request(action.id, action.setting_type, request); } SettingActionData::Listen(size) => { self.process_listen(action.setting_type, size); } } } /// Notifies proper sink in the case the notification listener count is /// non-zero and we aren't already listening for changes to the type or there /// are no more listeners and we are actively listening. fn process_listen(&mut self, setting_type: SettingType, size: u64) { let candidate = self.command_sender_map.get(&setting_type); if candidate.is_none() { return; } let sender = candidate.unwrap(); let listening = self.active_listeners.contains(&setting_type); if size == 0 && listening { // FIXME: use `Vec::remove_item` upon stabilization let listener_to_remove = self.active_listeners.iter().enumerate().find(|(_i, elem)| **elem == setting_type); if let Some((i, _elem)) = listener_to_remove { self.active_listeners.remove(i); } sender.unbounded_send(Command::ChangeState(State::EndListen)).ok(); } else if size > 0 && !listening { self.active_listeners.push(setting_type); sender .unbounded_send(Command::ChangeState(State::Listen( self.notification_sender.clone(), ))) .ok(); } } /// Called by the receiver task when a sink has reported a change to its /// setting type. fn notify(&self, setting_type: SettingType) { // Only return updates for types actively listened on. if self.active_listeners.contains(&setting_type) { self.event_sender.unbounded_send(SettingEvent::Changed(setting_type)).ok(); } } /// Forwards request to proper sink. A new task is spawned in order to receive /// the response. If no sink is available, an error is immediately reported /// back. fn process_request(&self, id: u64, setting_type: SettingType, request: SettingRequest) { let candidate = self.command_sender_map.get(&setting_type); match candidate { None => { self.event_sender .unbounded_send(SettingEvent::Response( id, Err(format_err!("no handler for requested type")), )) .ok(); } Some(command_sender) => { let (responder, receiver) = futures::channel::oneshot::channel::<SettingResponseResult>(); let sender_clone = self.event_sender.clone(); let error_sender_clone = self.event_sender.clone(); fasync::spawn( async move { let response = receiver.await.context("getting response from controller")?; sender_clone.unbounded_send(SettingEvent::Response(id, response)).ok(); Ok(()) } .unwrap_or_else(move |e: failure::Error| { error_sender_clone .unbounded_send(SettingEvent::Response(id, Err(e))) .ok(); }), ); command_sender.unbounded_send(Command::HandleRequest(request, responder)).ok(); } } } } impl Registry for RegistryImpl { /// Associates the provided command sender with the given type to receive /// future commands and updates. If a sender has already been associated with /// the type, returns an error. fn register( &mut self, setting_type: SettingType, command_sender: UnboundedSender<Command>, ) -> Result<(), Error> { if self.command_sender_map.contains_key(&setting_type) { return Err(format_err!("SettingType is already registered for type")); } self.command_sender_map.insert(setting_type, command_sender); return Ok(()); } } #[cfg(test)] mod tests { use super::*; #[fuchsia_async::run_until_stalled(test)] async fn test_notify() { let (action_tx, action_rx) = futures::channel::mpsc::unbounded::<SettingAction>(); let (event_tx, mut event_rx) = futures::channel::mpsc::unbounded::<SettingEvent>(); let registry = RegistryImpl::create(event_tx, action_rx); let setting_type = SettingType::Unknown; let (handler_tx, mut handler_rx) = futures::channel::mpsc::unbounded::<Command>(); assert!(registry.write().register(setting_type, handler_tx).is_ok()); // Send a listen state and make sure sink is notified. { assert!(action_tx .unbounded_send(SettingAction { id: 1, setting_type: setting_type, data: SettingActionData::Listen(1) }) .is_ok()); let command = handler_rx.next().await.unwrap(); match command { Command::ChangeState(State::Listen(notifier)) => { // Send back notification and make sure it is received. assert!(notifier.unbounded_send(setting_type).is_ok()); match event_rx.next().await.unwrap() { SettingEvent::Changed(changed_type) => { assert_eq!(changed_type, setting_type); } _ => { panic!("wrong response received"); } } } _ => { panic!("incorrect command received"); } } } // Send an end listen state and make sure sink is notified. { assert!(action_tx .unbounded_send(SettingAction { id: 1, setting_type: setting_type, data: SettingActionData::Listen(0) }) .is_ok()); match handler_rx.next().await.unwrap() { Command::ChangeState(State::EndListen) => { // Success case - ignore. } _ => { panic!("unexpected command"); } } } } #[fuchsia_async::run_until_stalled(test)] async fn test_request() { let (action_tx, action_rx) = futures::channel::mpsc::unbounded::<SettingAction>(); let (event_tx, mut event_rx) = futures::channel::mpsc::unbounded::<SettingEvent>(); let registry = RegistryImpl::create(event_tx, action_rx); let setting_type = SettingType::Unknown; let request_id = 42; let (handler_tx, mut handler_rx) = futures::channel::mpsc::unbounded::<Command>(); assert!(registry.write().register(setting_type, handler_tx).is_ok()); // Send initial request. assert!(action_tx .unbounded_send(SettingAction { id: request_id, setting_type: setting_type, data: SettingActionData::Request(SettingRequest::Get) }) .is_ok()); let command = handler_rx.next().await.unwrap(); match command { Command::HandleRequest(request, responder) => { assert_eq!(request, SettingRequest::Get); // Send back response assert!(responder.send(Ok(None)).is_ok()); // verify response matches match event_rx.next().await.unwrap() { SettingEvent::Response(response_id, response) => { assert_eq!(request_id, response_id); assert!(response.is_ok()); assert_eq!(None, response.unwrap()); } _ => { panic!("unexpected response"); } } } _ => { panic!("incorrect command received"); } } } }
use std::ffi::OsString; use std::fs::read_dir; use std::path::Path; use std::sync::Arc; use std::time::Duration; use arrow_util::assert_batches_sorted_eq; use assert_matches::assert_matches; use data_types::{PartitionKey, TableId, Timestamp}; use ingester_query_grpc::influxdata::iox::ingester::v1::IngesterQueryRequest; use ingester_test_ctx::{TestContextBuilder, DEFAULT_MAX_PERSIST_QUEUE_DEPTH}; use iox_catalog::interface::Catalog; use itertools::Itertools; use metric::{ assert_counter, assert_histogram, DurationHistogram, U64Counter, U64Gauge, U64Histogram, }; use parquet_file::ParquetFilePath; use test_helpers::timeout::FutureTimeout; use trace::{ctx::SpanContext, RingBufferTraceCollector}; // Write data to an ingester through the RPC interface and persist the data. #[tokio::test] async fn write_persist() { let namespace_name = "write_query_test_namespace"; let mut ctx = TestContextBuilder::default().build().await; let ns = ctx.ensure_namespace(namespace_name, None, None).await; let partition_key = PartitionKey::from("1970-01-01"); ctx.write_lp( namespace_name, r#"bananas count=42,greatness="inf" 200"#, partition_key.clone(), 42, None, ) .await; // Perform a query to validate the actual data buffered. let table_id = ctx.table_id(namespace_name, "bananas").await.get(); let data: Vec<_> = ctx .query(IngesterQueryRequest { namespace_id: ns.id.get(), table_id, columns: vec![], predicate: None, }) .await .expect("query request failed"); let expected = vec![ "+-------+-----------+--------------------------------+", "| count | greatness | time |", "+-------+-----------+--------------------------------+", "| 42.0 | inf | 1970-01-01T00:00:00.000000200Z |", "+-------+-----------+--------------------------------+", ]; assert_batches_sorted_eq!(&expected, &data); // Persist the data. ctx.persist(namespace_name).await; // Ensure the data is no longer buffered. let data: Vec<_> = ctx .query(IngesterQueryRequest { namespace_id: ns.id.get(), table_id, columns: vec![], predicate: None, }) .await .expect("query request failed"); assert!(data.is_empty()); // Validate the parquet file was added to the catalog let parquet_files = ctx.catalog_parquet_file_records(namespace_name).await; let (path, want_file_size) = assert_matches!(parquet_files.as_slice(), [f] => { assert_eq!(f.namespace_id, ns.id); assert_eq!(f.table_id, TableId::new(table_id)); assert_eq!(f.min_time, Timestamp::new(200)); assert_eq!(f.max_time, Timestamp::new(200)); assert_eq!(f.to_delete, None); assert_eq!(f.row_count, 1); assert_eq!(f.column_set.len(), 3); assert_eq!(f.max_l0_created_at, f.created_at); (ParquetFilePath::from(f), f.file_size_bytes) }); // Validate the file exists at the expected object store path. let file_size = ctx .object_store() .get(&path.object_store_path()) .await .expect("parquet file must exist in object store") .bytes() .await .expect("failed to read parquet file bytes") .len(); assert_eq!(file_size, want_file_size as usize); // And that the persist metrics were recorded. let metrics = ctx.metrics(); //////////////////////////////////////////////////////////////////////////// // Config reflection metrics assert_counter!( metrics, U64Gauge, "ingester_persist_max_parallelism", value = 5, ); assert_counter!( metrics, U64Gauge, "ingester_persist_max_queue_depth", value = DEFAULT_MAX_PERSIST_QUEUE_DEPTH as u64, ); //////////////////////////////////////////////////////////////////////////// // Persist worker metrics assert_histogram!( metrics, DurationHistogram, "ingester_persist_active_duration", samples = 1, ); assert_histogram!( metrics, DurationHistogram, "ingester_persist_enqueue_duration", samples = 1, ); assert_counter!( metrics, U64Counter, "ingester_persist_enqueued_jobs", value = 1, ); //////////////////////////////////////////////////////////////////////////// // Parquet file metrics assert_histogram!( metrics, DurationHistogram, "ingester_persist_parquet_file_time_range", samples = 1, sum = Duration::from_secs(0), ); assert_histogram!( metrics, U64Histogram, "ingester_persist_parquet_file_size_bytes", samples = 1, ); assert_histogram!( metrics, U64Histogram, "ingester_persist_parquet_file_row_count", samples = 1, sum = 1, ); assert_histogram!( metrics, U64Histogram, "ingester_persist_parquet_file_column_count", samples = 1, sum = 3, ); } // Write data to the ingester, which writes it to the WAL, then drop and recreate the WAL and // validate the data is replayed from the WAL into memory. #[tokio::test] async fn wal_replay() { let wal_dir = Arc::new(test_helpers::tmp_dir().unwrap()); let metrics: Arc<metric::Registry> = Default::default(); let catalog: Arc<dyn Catalog> = Arc::new(iox_catalog::mem::MemCatalog::new(Arc::clone(&metrics))); let namespace_name = "wal_replay_test_namespace"; { let mut ctx = TestContextBuilder::default() .with_wal_dir(Arc::clone(&wal_dir)) .with_catalog(Arc::clone(&catalog)) .build() .await; let ns = ctx.ensure_namespace(namespace_name, None, None).await; // Initial write let partition_key = PartitionKey::from("1970-01-01"); ctx.write_lp( namespace_name, "bananas greatness=\"unbounded\" 10", partition_key.clone(), 0, None, ) .await; // A subsequent write with a non-contiguous sequence number to a different table. ctx.write_lp( namespace_name, "cpu bar=2 20\ncpu bar=3 30", partition_key.clone(), 7, None, ) .await; // And a third write that appends more data to the table in the initial // write. ctx.write_lp( namespace_name, "bananas count=42 200", partition_key.clone(), 42, None, ) .await; // Perform a query to validate the actual data buffered. let data: Vec<_> = ctx .query(IngesterQueryRequest { namespace_id: ns.id.get(), table_id: ctx.table_id(namespace_name, "bananas").await.get(), columns: vec![], predicate: None, }) .await .expect("query request failed"); let expected = vec![ "+-------+-----------+--------------------------------+", "| count | greatness | time |", "+-------+-----------+--------------------------------+", "| | unbounded | 1970-01-01T00:00:00.000000010Z |", "| 42.0 | | 1970-01-01T00:00:00.000000200Z |", "+-------+-----------+--------------------------------+", ]; assert_batches_sorted_eq!(&expected, &data); } // Drop the first ingester instance // Restart the ingester and perform replay by creating another ingester using the same WAL // directory and catalog let ctx = TestContextBuilder::default() .with_wal_dir(wal_dir) .with_catalog(catalog) .build() .await; // Validate the data has been replayed and is now in object storage (it won't be in the // ingester's memory because replaying the WAL also persists). let parquet_files = ctx.catalog_parquet_file_records(namespace_name).await; assert_eq!(parquet_files.len(), 2); let mut expected_table_ids = vec![ ctx.table_id(namespace_name, "bananas").await, ctx.table_id(namespace_name, "cpu").await, ]; expected_table_ids.sort(); let mut actual_table_ids: Vec<_> = parquet_files.iter().map(|pf| pf.table_id).collect(); actual_table_ids.sort(); assert_eq!(actual_table_ids, expected_table_ids); } // Ensure that data applied to an ingester is persisted at shutdown, and the WAL // files are cleared. #[tokio::test] async fn graceful_shutdown() { let wal_dir = Arc::new(test_helpers::tmp_dir().unwrap()); let metrics: Arc<metric::Registry> = Default::default(); let catalog: Arc<dyn Catalog> = Arc::new(iox_catalog::mem::MemCatalog::new(Arc::clone(&metrics))); let namespace_name = "wal_replay_test_namespace"; let mut ctx = TestContextBuilder::default() .with_wal_dir(Arc::clone(&wal_dir)) .with_catalog(Arc::clone(&catalog)) .build() .await; let ns = ctx.ensure_namespace(namespace_name, None, None).await; let namespace_id = ns.id; // Initial write let partition_key = PartitionKey::from("1970-01-01"); ctx.write_lp( namespace_name, "bananas greatness=\"unbounded\" 10", partition_key.clone(), 0, None, ) .await; // Persist the data ctx.persist(namespace_name).await; // A subsequent write with a non-contiguous sequence number to a different table. ctx.write_lp( namespace_name, "cpu bar=2 20\ncpu bar=3 30", partition_key.clone(), 7, None, ) .await; // And a third write that appends more data to the table in the initial // write. ctx.write_lp( namespace_name, "bananas count=42 200", partition_key.clone(), 42, None, ) .await; // Perform a query to validate the actual data buffered. let data: Vec<_> = ctx .query(IngesterQueryRequest { namespace_id: ns.id.get(), table_id: ctx.table_id(namespace_name, "bananas").await.get(), columns: vec![], predicate: None, }) .await .expect("query request failed"); let expected = vec![ "+-------+--------------------------------+", "| count | time |", "+-------+--------------------------------+", "| 42.0 | 1970-01-01T00:00:00.000000200Z |", "+-------+--------------------------------+", ]; assert_batches_sorted_eq!(&expected, &data); // Gracefully stop the ingester. ctx.shutdown().await; // Inspect the WAL files. // // There should be one WAL file, containing no operations. let wal = wal::Wal::new(wal_dir.path()) .await .expect("failed to reinitialise WAL"); let wal_files = wal.closed_segments(); assert_eq!(wal_files.len(), 1); let mut reader = wal .reader_for_segment(wal_files[0].id()) .expect("failed to open wal segment"); // Assert the file contains no operations assert_matches!(reader.next(), None); // Validate the parquet files were added to the catalog during shutdown. let parquet_files = catalog .repositories() .await .parquet_files() .list_by_namespace_not_to_delete(namespace_id) .await .unwrap(); assert_eq!(parquet_files.len(), 3); } #[tokio::test] async fn wal_reference_dropping() { let wal_dir = Arc::new(test_helpers::tmp_dir().unwrap()); let metrics = Arc::new(metric::Registry::default()); let catalog: Arc<dyn Catalog> = Arc::new(iox_catalog::mem::MemCatalog::new(Arc::clone(&metrics))); // Test-local namespace name const TEST_NAMESPACE_NAME: &str = "wal_reference_dropping_test_namespace"; // Create an ingester using a fairly low write-ahead log rotation interval const WAL_ROTATION_PERIOD: Duration = Duration::from_secs(15); // Create an ingester with a low let mut ctx = TestContextBuilder::default() .with_wal_dir(Arc::clone(&wal_dir)) .with_catalog(Arc::clone(&catalog)) .with_wal_rotation_period(WAL_ROTATION_PERIOD) .build() .await; let ns = ctx.ensure_namespace(TEST_NAMESPACE_NAME, None, None).await; // Initial write let partition_key = PartitionKey::from("1970-01-01"); ctx.write_lp( TEST_NAMESPACE_NAME, "bananas greatness=\"unbounded\" 10", partition_key.clone(), 0, None, ) .await; // A subsequent write with a non-contiguous sequence number to a different table. ctx.write_lp( TEST_NAMESPACE_NAME, "cpu bar=2 20\ncpu bar=3 30", partition_key.clone(), 7, None, ) .await; // And a third write that appends more data to the table in the initial // write. ctx.write_lp( TEST_NAMESPACE_NAME, "bananas count=42 200", partition_key.clone(), 42, None, ) .await; // Perform a query to validate the actual data buffered. let data: Vec<_> = ctx .query(IngesterQueryRequest { namespace_id: ns.id.get(), table_id: ctx.table_id(TEST_NAMESPACE_NAME, "bananas").await.get(), columns: vec![], predicate: None, }) .await .expect("query request failed"); let expected = vec![ "+-------+-----------+--------------------------------+", "| count | greatness | time |", "+-------+-----------+--------------------------------+", "| | unbounded | 1970-01-01T00:00:00.000000010Z |", "| 42.0 | | 1970-01-01T00:00:00.000000200Z |", "+-------+-----------+--------------------------------+", ]; assert_batches_sorted_eq!(&expected, &data); let initial_segment_names = get_file_names_in_dir(wal_dir.path()).expect("should be able to get file names"); assert_eq!(initial_segment_names.len(), 1); // Ensure a single (open) segment is present tokio::time::pause(); tokio::time::advance(WAL_ROTATION_PERIOD).await; tokio::time::resume(); // Wait for the rotation to result in the initial segment no longer being present in // the write-ahead log directory async { loop { let segments = get_file_names_in_dir(wal_dir.path()).expect("should be able to get file names"); if !segments .iter() .any(|name| initial_segment_names.contains(name)) { break; } tokio::task::yield_now().await; } } .with_timeout_panic(Duration::from_secs(5)) .await; let final_segment_names = get_file_names_in_dir(wal_dir.path()).expect("should be able to get file names"); assert_eq!(final_segment_names.len(), 1); // Ensure a single (open) segment is present after the old one has been dropped } fn get_file_names_in_dir(dir: &Path) -> Result<Vec<OsString>, std::io::Error> { read_dir(dir)? .filter_map_ok(|f| { if let Ok(file_type) = f.file_type() { if file_type.is_file() { return Some(f.file_name()); } } None }) .collect::<Result<Vec<_>, std::io::Error>>() } #[tokio::test] async fn write_tracing() { let namespace_name = "write_tracing_test_namespace"; let mut ctx = TestContextBuilder::default().build().await; let ns = ctx.ensure_namespace(namespace_name, None, None).await; let trace_collector = Arc::new(RingBufferTraceCollector::new(5)); let span_ctx = SpanContext::new(Arc::new(Arc::clone(&trace_collector))); let request_span = span_ctx.child("write request span"); let partition_key = PartitionKey::from("1970-01-01"); ctx.write_lp( namespace_name, r#"bananas count=42,greatness="inf" 200"#, partition_key.clone(), 42, Some(request_span.ctx.clone()), ) .await; // Perform a query to validate the actual data buffered. let table_id = ctx.table_id(namespace_name, "bananas").await.get(); let data: Vec<_> = ctx .query(IngesterQueryRequest { namespace_id: ns.id.get(), table_id, columns: vec![], predicate: None, }) .await .expect("query request failed"); let expected = vec![ "+-------+-----------+--------------------------------+", "| count | greatness | time |", "+-------+-----------+--------------------------------+", "| 42.0 | inf | 1970-01-01T00:00:00.000000200Z |", "+-------+-----------+--------------------------------+", ]; assert_batches_sorted_eq!(&expected, &data); // Check the spans emitted for the write request align capture what is expected let spans = trace_collector.spans(); assert_matches!(spans.as_slice(), [span3, span2, span1, handler_span] => { // Check that the DML handlers are hit, and that they inherit from the // handler span, which in turn inherits from the request assert_eq!(handler_span.name, "ingester write"); assert_eq!(span1.name, "write_apply"); assert_eq!(span2.name, "wal"); assert_eq!(span3.name, "buffer"); assert_eq!(handler_span.ctx.parent_span_id, Some(request_span.ctx.span_id)); assert_eq!(span1.ctx.parent_span_id, Some(handler_span.ctx.span_id)); assert_eq!(span2.ctx.parent_span_id, Some(handler_span.ctx.span_id)); assert_eq!(span3.ctx.parent_span_id, Some(handler_span.ctx.span_id)); }) }
#[macro_use] extern crate rocket; extern crate hex; use core::str; use hex::FromHex; use url::form_urlencoded::{parse}; use regex::Regex; fn ascii_to_hex<'a>(text: String) -> String { let hex_text: String = hex::encode(text); format!("{}", hex_text) } fn hex_to_ascii<'a>(hex: String) -> String { let hex_to_bytes: String = parse(hex.as_bytes()) .map(|(key, val)| [key, val].concat()) .collect(); let re = Regex::new(r"^[0-9a-fA-F]+$").unwrap(); let hex_slice: &str = &hex_to_bytes.to_owned()[..]; if !re.is_match(hex_slice) { return "Introduce un texto hexadecimal correcto".to_string() } let buffer = <Vec<u8>>::from_hex(&hex_to_bytes).unwrap(); let string = str::from_utf8(&buffer).expect("invalid string"); format!("{}",string) } #[get("/to-hex/<text>")] fn text_encoder(text: String) -> String { ascii_to_hex(text) } #[get("/to-text/<hex>")] fn text_decoder(hex: String) -> String { hex_to_ascii(hex) } #[launch] fn rocket() -> _ { rocket::build().mount("/", routes![text_encoder, text_decoder]) }
use std::cmp::Ordering; use std::collections::HashSet; use std::collections::VecDeque; use std::io; type Deck = VecDeque<u32>; /// Read cards. Terminates on blank line or EOF. fn read_player() -> Deck { let mut line = String::new(); io::stdin().read_line(&mut line).expect("error!"); let mut cards = VecDeque::new(); loop { let mut line = String::new(); match io::stdin().read_line(&mut line) { Err(error) => panic!("error: {}", error), Ok(n) => { if n == 0 || line.trim().len() == 0 { break; } cards.push_back(line.trim().parse::<u32>().unwrap()); } } } cards } fn compute_score(deck: &Deck) -> u32 { let mut score = 0; for (i, card) in deck.iter().rev().enumerate() { score += (i as u32 + 1) * card; } score } fn print_deck(deck: &Deck) { for card in deck { print!("{}, ", card); } println!(); } fn play_game(p1_cards: &mut Deck, p2_cards: &mut Deck) { loop { if p1_cards.len() == 0 || p2_cards.len() == 0 { // game ends if p1_cards.len() == 0 { println!("Score: {}", compute_score(&p2_cards)); } else { println!("Score: {}", compute_score(&p1_cards)); } return; } let c1 = p1_cards.pop_front().unwrap(); let c2 = p2_cards.pop_front().unwrap(); match c1.cmp(&c2) { Ordering::Greater => { // player 1 wins round p1_cards.push_back(c1); p1_cards.push_back(c2); } Ordering::Less => { // player 2 wins round p2_cards.push_back(c2); p2_cards.push_back(c1); } Ordering::Equal => panic!("got same card in both decks"), } } } enum Player { Player1, Player2, } fn hash_game(p1_cards: &Deck, p2_cards: &Deck) -> String { let mut hash = String::new(); for card in p1_cards { hash.push_str(format!("{},", card).as_str()); } hash.push_str("|"); for card in p2_cards { hash.push_str(format!("{},", card).as_str()); } hash } fn play_recursive_game(p1_cards: &mut Deck, p2_cards: &mut Deck) -> Player { // keep a set of all rounds (as strings) to prevent infinite games let mut rounds = HashSet::new(); loop { let hash = hash_game(p1_cards, p2_cards); if rounds.contains(&hash) { return Player::Player1; } rounds.insert(hash); match (p1_cards.len() == 0, p2_cards.len() == 0) { (true, false) => return Player::Player2, (false, true) => return Player::Player1, (true, true) => panic!("both players have no cards in their decks"), (false, false) => (), } let c1 = p1_cards.pop_front().unwrap(); let c2 = p2_cards.pop_front().unwrap(); // check if we go into a subgame if (c1 as usize) <= p1_cards.len() && (c2 as usize) <= p2_cards.len() { let mut p1_subdeck = VecDeque::new(); for i in 0..c1 { p1_subdeck.push_back(p1_cards.get(i as usize).unwrap().clone()); } let mut p2_subdeck = VecDeque::new(); for i in 0..c2 { p2_subdeck.push_back(p2_cards.get(i as usize).unwrap().clone()); } match play_recursive_game(&mut p1_subdeck, &mut p2_subdeck) { Player::Player1 => { p1_cards.push_back(c1); p1_cards.push_back(c2); } Player::Player2 => { p2_cards.push_back(c2); p2_cards.push_back(c1); } } } else { // play normally match c1.cmp(&c2) { Ordering::Greater => { // player 1 wins round p1_cards.push_back(c1); p1_cards.push_back(c2); } Ordering::Less => { // player 2 wins round p2_cards.push_back(c2); p2_cards.push_back(c1); } Ordering::Equal => panic!("got same card in both decks"), } } } } pub fn day22(part_a: bool) { let mut p1_cards = read_player(); let mut p2_cards = read_player(); print_deck(&p1_cards); print_deck(&p2_cards); if part_a { play_game(&mut p1_cards, &mut p2_cards); } else { let score = match play_recursive_game(&mut p1_cards, &mut p2_cards) { Player::Player1 => compute_score(&p1_cards), Player::Player2 => compute_score(&p2_cards), }; println!("Score: {}", score); } }
#[derive(Debug, Clone)] pub struct AppState { pub templates: minijinja::Environment<'static>, pub database: sea_orm::DatabaseConnection, }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const CLSID_IITCmdInt: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4662daa2_d393_11d0_9a56_00c04fb68bf7); pub const CLSID_IITDatabase: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x66673452_8c23_11d0_a84e_00aa006c7d01); pub const CLSID_IITDatabaseLocal: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4662daa9_d393_11d0_9a56_00c04fb68bf7); pub const CLSID_IITGroupUpdate: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4662daa4_d393_11d0_9a56_00c04fb68bf7); pub const CLSID_IITIndexBuild: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8fa0d5aa_dedf_11d0_9a61_00c04fb68bf7); pub const CLSID_IITPropList: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4662daae_d393_11d0_9a56_00c04fb68bf7); pub const CLSID_IITResultSet: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4662daa7_d393_11d0_9a56_00c04fb68bf7); pub const CLSID_IITSvMgr: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4662daa3_d393_11d0_9a56_00c04fb68bf7); pub const CLSID_IITWWFilterBuild: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8fa0d5ab_dedf_11d0_9a61_00c04fb68bf7); pub const CLSID_IITWordWheel: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd73725c2_8c12_11d0_a84e_00aa006c7d01); pub const CLSID_IITWordWheelLocal: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4662daa8_d393_11d0_9a56_00c04fb68bf7); pub const CLSID_IITWordWheelUpdate: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4662daa5_d393_11d0_9a56_00c04fb68bf7); pub const CLSID_ITEngStemmer: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8fa0d5a8_dedf_11d0_9a61_00c04fb68bf7); pub const CLSID_ITStdBreaker: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4662daaf_d393_11d0_9a56_00c04fb68bf7); #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct COLUMNSTATUS { pub cPropCount: i32, pub cPropsLoaded: i32, } impl COLUMNSTATUS {} impl ::core::default::Default for COLUMNSTATUS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for COLUMNSTATUS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("COLUMNSTATUS").field("cPropCount", &self.cPropCount).field("cPropsLoaded", &self.cPropsLoaded).finish() } } impl ::core::cmp::PartialEq for COLUMNSTATUS { fn eq(&self, other: &Self) -> bool { self.cPropCount == other.cPropCount && self.cPropsLoaded == other.cPropsLoaded } } impl ::core::cmp::Eq for COLUMNSTATUS {} unsafe impl ::windows::core::Abi for COLUMNSTATUS { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct CProperty { pub dwPropID: u32, pub cbData: u32, pub dwType: u32, pub Anonymous: CProperty_0, pub fPersist: super::super::Foundation::BOOL, } #[cfg(feature = "Win32_Foundation")] impl CProperty {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for CProperty { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for CProperty { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for CProperty {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for CProperty { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub union CProperty_0 { pub lpszwData: super::super::Foundation::PWSTR, pub lpvData: *mut ::core::ffi::c_void, pub dwValue: u32, } #[cfg(feature = "Win32_Foundation")] impl CProperty_0 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for CProperty_0 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for CProperty_0 { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for CProperty_0 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for CProperty_0 { type Abi = Self; } pub const E_ALL_WILD: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479467i32 as _); pub const E_ALREADYINIT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479421i32 as _); pub const E_ALREADYOPEN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479533i32 as _); pub const E_ASSERT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479546i32 as _); pub const E_BADBREAKER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479469i32 as _); pub const E_BADFILE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479549i32 as _); pub const E_BADFILTERSIZE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479528i32 as _); pub const E_BADFORMAT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479548i32 as _); pub const E_BADINDEXFLAGS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479456i32 as _); pub const E_BADPARAM: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479535i32 as _); pub const E_BADRANGEOP: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479459i32 as _); pub const E_BADVALUE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479468i32 as _); pub const E_BADVERSION: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479550i32 as _); pub const E_CANTFINDDLL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479538i32 as _); pub const E_DISKFULL: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479496i32 as _); pub const E_DUPLICATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479551i32 as _); pub const E_EXPECTEDTERM: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479465i32 as _); pub const E_FILECLOSE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479503i32 as _); pub const E_FILECREATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479504i32 as _); pub const E_FILEDELETE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479499i32 as _); pub const E_FILEINVALID: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479498i32 as _); pub const E_FILENOTFOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479497i32 as _); pub const E_FILEREAD: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479502i32 as _); pub const E_FILESEEK: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479501i32 as _); pub const E_FILEWRITE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479500i32 as _); pub const E_GETLASTERROR: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479536i32 as _); pub const E_GROUPIDTOOBIG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479542i32 as _); pub const E_INTERRUPT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479545i32 as _); pub const E_INVALIDSTATE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479534i32 as _); pub const E_MISSINGPROP: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479424i32 as _); pub const E_MISSLPAREN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479464i32 as _); pub const E_MISSQUOTE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479462i32 as _); pub const E_MISSRPAREN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479463i32 as _); pub const E_NAMETOOLONG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479520i32 as _); pub const E_NOHANDLE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479537i32 as _); pub const E_NOKEYPROP: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479417i32 as _); pub const E_NOMERGEDDATA: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479540i32 as _); pub const E_NOPERMISSION: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479547i32 as _); pub const E_NOSTEMMER: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479454i32 as _); pub const E_NOTEXIST: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479552i32 as _); pub const E_NOTFOUND: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479539i32 as _); pub const E_NOTINIT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479420i32 as _); pub const E_NOTOPEN: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479533i32 as _); pub const E_NOTSUPPORTED: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479544i32 as _); pub const E_NULLQUERY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479461i32 as _); pub const E_OUTOFRANGE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479543i32 as _); pub const E_PROPLISTEMPTY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479422i32 as _); pub const E_PROPLISTNOTEMPTY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479423i32 as _); pub const E_RESULTSETEMPTY: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479419i32 as _); pub const E_STOPWORD: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479460i32 as _); pub const E_TOODEEP: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479466i32 as _); pub const E_TOOMANYCOLUMNS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479418i32 as _); pub const E_TOOMANYDUPS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479471i32 as _); pub const E_TOOMANYOBJECTS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479527i32 as _); pub const E_TOOMANYTITLES: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479541i32 as _); pub const E_TOOMANYTOPICS: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479472i32 as _); pub const E_TREETOOBIG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479470i32 as _); pub const E_UNKNOWN_TRANSPORT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479530i32 as _); pub const E_UNMATCHEDTYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479458i32 as _); pub const E_UNSUPPORTED_TRANSPORT: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479529i32 as _); pub const E_WILD_IN_DTYPE: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479455i32 as _); pub const E_WORDTOOLONG: ::windows::core::HRESULT = ::windows::core::HRESULT(-2147479457i32 as _); pub const HHACT_BACK: i32 = 7i32; pub const HHACT_CONTRACT: i32 = 6i32; pub const HHACT_CUSTOMIZE: i32 = 16i32; pub const HHACT_EXPAND: i32 = 5i32; pub const HHACT_FORWARD: i32 = 8i32; pub const HHACT_HIGHLIGHT: i32 = 15i32; pub const HHACT_HOME: i32 = 11i32; pub const HHACT_JUMP1: i32 = 17i32; pub const HHACT_JUMP2: i32 = 18i32; pub const HHACT_LAST_ENUM: i32 = 23i32; pub const HHACT_NOTES: i32 = 22i32; pub const HHACT_OPTIONS: i32 = 13i32; pub const HHACT_PRINT: i32 = 14i32; pub const HHACT_REFRESH: i32 = 10i32; pub const HHACT_STOP: i32 = 9i32; pub const HHACT_SYNC: i32 = 12i32; pub const HHACT_TAB_CONTENTS: i32 = 0i32; pub const HHACT_TAB_FAVORITES: i32 = 4i32; pub const HHACT_TAB_HISTORY: i32 = 3i32; pub const HHACT_TAB_INDEX: i32 = 1i32; pub const HHACT_TAB_SEARCH: i32 = 2i32; pub const HHACT_TOC_NEXT: i32 = 20i32; pub const HHACT_TOC_PREV: i32 = 21i32; pub const HHACT_ZOOM: i32 = 19i32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] pub struct HHNTRACK { pub hdr: super::super::UI::Controls::NMHDR, pub pszCurUrl: super::super::Foundation::PSTR, pub idAction: i32, pub phhWinType: *mut HH_WINTYPE, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl HHNTRACK {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl ::core::default::Default for HHNTRACK { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl ::core::fmt::Debug for HHNTRACK { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HHNTRACK").field("hdr", &self.hdr).field("pszCurUrl", &self.pszCurUrl).field("idAction", &self.idAction).field("phhWinType", &self.phhWinType).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl ::core::cmp::PartialEq for HHNTRACK { fn eq(&self, other: &Self) -> bool { self.hdr == other.hdr && self.pszCurUrl == other.pszCurUrl && self.idAction == other.idAction && self.phhWinType == other.phhWinType } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl ::core::cmp::Eq for HHNTRACK {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] unsafe impl ::windows::core::Abi for HHNTRACK { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] pub struct HHN_NOTIFY { pub hdr: super::super::UI::Controls::NMHDR, pub pszUrl: super::super::Foundation::PSTR, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl HHN_NOTIFY {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl ::core::default::Default for HHN_NOTIFY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl ::core::fmt::Debug for HHN_NOTIFY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HHN_NOTIFY").field("hdr", &self.hdr).field("pszUrl", &self.pszUrl).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl ::core::cmp::PartialEq for HHN_NOTIFY { fn eq(&self, other: &Self) -> bool { self.hdr == other.hdr && self.pszUrl == other.pszUrl } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] impl ::core::cmp::Eq for HHN_NOTIFY {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Controls"))] unsafe impl ::windows::core::Abi for HHN_NOTIFY { type Abi = Self; } pub const HHWIN_BUTTON_BACK: u32 = 4u32; pub const HHWIN_BUTTON_BROWSE_BCK: u32 = 256u32; pub const HHWIN_BUTTON_BROWSE_FWD: u32 = 128u32; pub const HHWIN_BUTTON_CONTENTS: u32 = 1024u32; pub const HHWIN_BUTTON_EXPAND: u32 = 2u32; pub const HHWIN_BUTTON_FAVORITES: u32 = 131072u32; pub const HHWIN_BUTTON_FORWARD: u32 = 8u32; pub const HHWIN_BUTTON_HISTORY: u32 = 65536u32; pub const HHWIN_BUTTON_HOME: u32 = 64u32; pub const HHWIN_BUTTON_INDEX: u32 = 16384u32; pub const HHWIN_BUTTON_JUMP1: u32 = 262144u32; pub const HHWIN_BUTTON_JUMP2: u32 = 524288u32; pub const HHWIN_BUTTON_NOTES: u32 = 512u32; pub const HHWIN_BUTTON_OPTIONS: u32 = 4096u32; pub const HHWIN_BUTTON_PRINT: u32 = 8192u32; pub const HHWIN_BUTTON_REFRESH: u32 = 32u32; pub const HHWIN_BUTTON_SEARCH: u32 = 32768u32; pub const HHWIN_BUTTON_STOP: u32 = 16u32; pub const HHWIN_BUTTON_SYNC: u32 = 2048u32; pub const HHWIN_BUTTON_TOC_NEXT: u32 = 2097152u32; pub const HHWIN_BUTTON_TOC_PREV: u32 = 4194304u32; pub const HHWIN_BUTTON_ZOOM: u32 = 1048576u32; pub const HHWIN_NAVTAB_BOTTOM: i32 = 2i32; pub const HHWIN_NAVTAB_LEFT: i32 = 1i32; pub const HHWIN_NAVTAB_TOP: i32 = 0i32; pub const HHWIN_NAVTYPE_AUTHOR: i32 = 5i32; pub const HHWIN_NAVTYPE_CUSTOM_FIRST: i32 = 11i32; pub const HHWIN_NAVTYPE_FAVORITES: i32 = 3i32; pub const HHWIN_NAVTYPE_HISTORY: i32 = 4i32; pub const HHWIN_NAVTYPE_INDEX: i32 = 1i32; pub const HHWIN_NAVTYPE_SEARCH: i32 = 2i32; pub const HHWIN_NAVTYPE_TOC: i32 = 0i32; pub const HHWIN_PARAM_CUR_TAB: u32 = 8192u32; pub const HHWIN_PARAM_EXPANSION: u32 = 512u32; pub const HHWIN_PARAM_EXSTYLES: u32 = 8u32; pub const HHWIN_PARAM_HISTORY_COUNT: u32 = 4096u32; pub const HHWIN_PARAM_INFOTYPES: u32 = 128u32; pub const HHWIN_PARAM_NAV_WIDTH: u32 = 32u32; pub const HHWIN_PARAM_PROPERTIES: u32 = 2u32; pub const HHWIN_PARAM_RECT: u32 = 16u32; pub const HHWIN_PARAM_SHOWSTATE: u32 = 64u32; pub const HHWIN_PARAM_STYLES: u32 = 4u32; pub const HHWIN_PARAM_TABORDER: u32 = 2048u32; pub const HHWIN_PARAM_TABPOS: u32 = 1024u32; pub const HHWIN_PARAM_TB_FLAGS: u32 = 256u32; pub const HHWIN_PROP_AUTO_SYNC: u32 = 256u32; pub const HHWIN_PROP_CHANGE_TITLE: u32 = 8192u32; pub const HHWIN_PROP_MENU: u32 = 65536u32; pub const HHWIN_PROP_NAV_ONLY_WIN: u32 = 16384u32; pub const HHWIN_PROP_NODEF_EXSTYLES: u32 = 16u32; pub const HHWIN_PROP_NODEF_STYLES: u32 = 8u32; pub const HHWIN_PROP_NOTB_TEXT: u32 = 64u32; pub const HHWIN_PROP_NOTITLEBAR: u32 = 4u32; pub const HHWIN_PROP_NO_TOOLBAR: u32 = 32768u32; pub const HHWIN_PROP_ONTOP: u32 = 2u32; pub const HHWIN_PROP_POST_QUIT: u32 = 128u32; pub const HHWIN_PROP_TAB_ADVSEARCH: u32 = 131072u32; pub const HHWIN_PROP_TAB_AUTOHIDESHOW: u32 = 1u32; pub const HHWIN_PROP_TAB_CUSTOM1: u32 = 524288u32; pub const HHWIN_PROP_TAB_CUSTOM2: u32 = 1048576u32; pub const HHWIN_PROP_TAB_CUSTOM3: u32 = 2097152u32; pub const HHWIN_PROP_TAB_CUSTOM4: u32 = 4194304u32; pub const HHWIN_PROP_TAB_CUSTOM5: u32 = 8388608u32; pub const HHWIN_PROP_TAB_CUSTOM6: u32 = 16777216u32; pub const HHWIN_PROP_TAB_CUSTOM7: u32 = 33554432u32; pub const HHWIN_PROP_TAB_CUSTOM8: u32 = 67108864u32; pub const HHWIN_PROP_TAB_CUSTOM9: u32 = 134217728u32; pub const HHWIN_PROP_TAB_FAVORITES: u32 = 4096u32; pub const HHWIN_PROP_TAB_HISTORY: u32 = 2048u32; pub const HHWIN_PROP_TAB_SEARCH: u32 = 1024u32; pub const HHWIN_PROP_TRACKING: u32 = 512u32; pub const HHWIN_PROP_TRI_PANE: u32 = 32u32; pub const HHWIN_PROP_USER_POS: u32 = 262144u32; pub const HHWIN_TB_MARGIN: u32 = 268435456u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HH_AKLINK { pub cbStruct: i32, pub fReserved: super::super::Foundation::BOOL, pub pszKeywords: *mut i8, pub pszUrl: *mut i8, pub pszMsgText: *mut i8, pub pszMsgTitle: *mut i8, pub pszWindow: *mut i8, pub fIndexOnFail: super::super::Foundation::BOOL, } #[cfg(feature = "Win32_Foundation")] impl HH_AKLINK {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HH_AKLINK { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HH_AKLINK { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HH_AKLINK") .field("cbStruct", &self.cbStruct) .field("fReserved", &self.fReserved) .field("pszKeywords", &self.pszKeywords) .field("pszUrl", &self.pszUrl) .field("pszMsgText", &self.pszMsgText) .field("pszMsgTitle", &self.pszMsgTitle) .field("pszWindow", &self.pszWindow) .field("fIndexOnFail", &self.fIndexOnFail) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HH_AKLINK { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.fReserved == other.fReserved && self.pszKeywords == other.pszKeywords && self.pszUrl == other.pszUrl && self.pszMsgText == other.pszMsgText && self.pszMsgTitle == other.pszMsgTitle && self.pszWindow == other.pszWindow && self.fIndexOnFail == other.fIndexOnFail } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HH_AKLINK {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HH_AKLINK { type Abi = Self; } pub const HH_ALINK_LOOKUP: u32 = 19u32; pub const HH_CLOSE_ALL: u32 = 18u32; pub const HH_DISPLAY_INDEX: u32 = 2u32; pub const HH_DISPLAY_SEARCH: u32 = 3u32; pub const HH_DISPLAY_TEXT_POPUP: u32 = 14u32; pub const HH_DISPLAY_TOC: u32 = 1u32; pub const HH_DISPLAY_TOPIC: u32 = 0u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HH_ENUM_CAT { pub cbStruct: i32, pub pszCatName: super::super::Foundation::PSTR, pub pszCatDescription: super::super::Foundation::PSTR, } #[cfg(feature = "Win32_Foundation")] impl HH_ENUM_CAT {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HH_ENUM_CAT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HH_ENUM_CAT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HH_ENUM_CAT").field("cbStruct", &self.cbStruct).field("pszCatName", &self.pszCatName).field("pszCatDescription", &self.pszCatDescription).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HH_ENUM_CAT { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.pszCatName == other.pszCatName && self.pszCatDescription == other.pszCatDescription } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HH_ENUM_CAT {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HH_ENUM_CAT { type Abi = Self; } pub const HH_ENUM_CATEGORY: u32 = 21u32; pub const HH_ENUM_CATEGORY_IT: u32 = 22u32; pub const HH_ENUM_INFO_TYPE: u32 = 7u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HH_ENUM_IT { pub cbStruct: i32, pub iType: i32, pub pszCatName: super::super::Foundation::PSTR, pub pszITName: super::super::Foundation::PSTR, pub pszITDescription: super::super::Foundation::PSTR, } #[cfg(feature = "Win32_Foundation")] impl HH_ENUM_IT {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HH_ENUM_IT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HH_ENUM_IT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HH_ENUM_IT").field("cbStruct", &self.cbStruct).field("iType", &self.iType).field("pszCatName", &self.pszCatName).field("pszITName", &self.pszITName).field("pszITDescription", &self.pszITDescription).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HH_ENUM_IT { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.iType == other.iType && self.pszCatName == other.pszCatName && self.pszITName == other.pszITName && self.pszITDescription == other.pszITDescription } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HH_ENUM_IT {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HH_ENUM_IT { type Abi = Self; } pub const HH_FTS_DEFAULT_PROXIMITY: i32 = -1i32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HH_FTS_QUERY { pub cbStruct: i32, pub fUniCodeStrings: super::super::Foundation::BOOL, pub pszSearchQuery: *mut i8, pub iProximity: i32, pub fStemmedSearch: super::super::Foundation::BOOL, pub fTitleOnly: super::super::Foundation::BOOL, pub fExecute: super::super::Foundation::BOOL, pub pszWindow: *mut i8, } #[cfg(feature = "Win32_Foundation")] impl HH_FTS_QUERY {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HH_FTS_QUERY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HH_FTS_QUERY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HH_FTS_QUERY") .field("cbStruct", &self.cbStruct) .field("fUniCodeStrings", &self.fUniCodeStrings) .field("pszSearchQuery", &self.pszSearchQuery) .field("iProximity", &self.iProximity) .field("fStemmedSearch", &self.fStemmedSearch) .field("fTitleOnly", &self.fTitleOnly) .field("fExecute", &self.fExecute) .field("pszWindow", &self.pszWindow) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HH_FTS_QUERY { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.fUniCodeStrings == other.fUniCodeStrings && self.pszSearchQuery == other.pszSearchQuery && self.iProximity == other.iProximity && self.fStemmedSearch == other.fStemmedSearch && self.fTitleOnly == other.fTitleOnly && self.fExecute == other.fExecute && self.pszWindow == other.pszWindow } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HH_FTS_QUERY {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HH_FTS_QUERY { type Abi = Self; } pub const HH_GET_LAST_ERROR: u32 = 20u32; pub const HH_GET_WIN_HANDLE: u32 = 6u32; pub const HH_GET_WIN_TYPE: u32 = 5u32; #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::clone::Clone for HH_GLOBAL_PROPERTY { fn clone(&self) -> Self { unimplemented!() } } #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] pub struct HH_GLOBAL_PROPERTY { pub id: HH_GPROPID, pub var: super::super::System::Com::VARIANT, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl HH_GLOBAL_PROPERTY {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::default::Default for HH_GLOBAL_PROPERTY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::cmp::PartialEq for HH_GLOBAL_PROPERTY { fn eq(&self, _other: &Self) -> bool { unimplemented!() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] impl ::core::cmp::Eq for HH_GLOBAL_PROPERTY {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com", feature = "Win32_System_Ole"))] unsafe impl ::windows::core::Abi for HH_GLOBAL_PROPERTY { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct HH_GPROPID(pub i32); pub const HH_GPROPID_SINGLETHREAD: HH_GPROPID = HH_GPROPID(1i32); pub const HH_GPROPID_TOOLBAR_MARGIN: HH_GPROPID = HH_GPROPID(2i32); pub const HH_GPROPID_UI_LANGUAGE: HH_GPROPID = HH_GPROPID(3i32); pub const HH_GPROPID_CURRENT_SUBSET: HH_GPROPID = HH_GPROPID(4i32); pub const HH_GPROPID_CONTENT_LANGUAGE: HH_GPROPID = HH_GPROPID(5i32); impl ::core::convert::From<i32> for HH_GPROPID { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for HH_GPROPID { type Abi = Self; } pub const HH_HELP_CONTEXT: u32 = 15u32; pub const HH_HELP_FINDER: u32 = 0u32; pub const HH_INITIALIZE: u32 = 28u32; pub const HH_KEYWORD_LOOKUP: u32 = 13u32; pub const HH_MAX_TABS: u32 = 19u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HH_POPUP { pub cbStruct: i32, pub hinst: super::super::Foundation::HINSTANCE, pub idString: u32, pub pszText: *mut i8, pub pt: super::super::Foundation::POINT, pub clrForeground: u32, pub clrBackground: u32, pub rcMargins: super::super::Foundation::RECT, pub pszFont: *mut i8, } #[cfg(feature = "Win32_Foundation")] impl HH_POPUP {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HH_POPUP { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HH_POPUP { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HH_POPUP") .field("cbStruct", &self.cbStruct) .field("hinst", &self.hinst) .field("idString", &self.idString) .field("pszText", &self.pszText) .field("pt", &self.pt) .field("clrForeground", &self.clrForeground) .field("clrBackground", &self.clrBackground) .field("rcMargins", &self.rcMargins) .field("pszFont", &self.pszFont) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HH_POPUP { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.hinst == other.hinst && self.idString == other.idString && self.pszText == other.pszText && self.pt == other.pt && self.clrForeground == other.clrForeground && self.clrBackground == other.clrBackground && self.rcMargins == other.rcMargins && self.pszFont == other.pszFont } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HH_POPUP {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HH_POPUP { type Abi = Self; } pub const HH_PRETRANSLATEMESSAGE: u32 = 253u32; pub const HH_RESERVED1: u32 = 10u32; pub const HH_RESERVED2: u32 = 11u32; pub const HH_RESERVED3: u32 = 12u32; pub const HH_RESET_IT_FILTER: u32 = 23u32; pub const HH_SAFE_DISPLAY_TOPIC: u32 = 32u32; pub const HH_SET_EXCLUSIVE_FILTER: u32 = 25u32; pub const HH_SET_GLOBAL_PROPERTY: u32 = 252u32; pub const HH_SET_INCLUSIVE_FILTER: u32 = 24u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HH_SET_INFOTYPE { pub cbStruct: i32, pub pszCatName: super::super::Foundation::PSTR, pub pszInfoTypeName: super::super::Foundation::PSTR, } #[cfg(feature = "Win32_Foundation")] impl HH_SET_INFOTYPE {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HH_SET_INFOTYPE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HH_SET_INFOTYPE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HH_SET_INFOTYPE").field("cbStruct", &self.cbStruct).field("pszCatName", &self.pszCatName).field("pszInfoTypeName", &self.pszInfoTypeName).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HH_SET_INFOTYPE { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.pszCatName == other.pszCatName && self.pszInfoTypeName == other.pszInfoTypeName } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HH_SET_INFOTYPE {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HH_SET_INFOTYPE { type Abi = Self; } pub const HH_SET_INFO_TYPE: u32 = 8u32; pub const HH_SET_QUERYSERVICE: u32 = 30u32; pub const HH_SET_WIN_TYPE: u32 = 4u32; pub const HH_SYNC: u32 = 9u32; pub const HH_TAB_AUTHOR: i32 = 5i32; pub const HH_TAB_CONTENTS: i32 = 0i32; pub const HH_TAB_CUSTOM_FIRST: i32 = 11i32; pub const HH_TAB_CUSTOM_LAST: i32 = 19i32; pub const HH_TAB_FAVORITES: i32 = 3i32; pub const HH_TAB_HISTORY: i32 = 4i32; pub const HH_TAB_INDEX: i32 = 1i32; pub const HH_TAB_SEARCH: i32 = 2i32; pub const HH_TP_HELP_CONTEXTMENU: u32 = 16u32; pub const HH_TP_HELP_WM_HELP: u32 = 17u32; pub const HH_UNINITIALIZE: u32 = 29u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct HH_WINTYPE { pub cbStruct: i32, pub fUniCodeStrings: super::super::Foundation::BOOL, pub pszType: *mut i8, pub fsValidMembers: u32, pub fsWinProperties: u32, pub pszCaption: *mut i8, pub dwStyles: u32, pub dwExStyles: u32, pub rcWindowPos: super::super::Foundation::RECT, pub nShowState: i32, pub hwndHelp: super::super::Foundation::HWND, pub hwndCaller: super::super::Foundation::HWND, pub paInfoTypes: *mut u32, pub hwndToolBar: super::super::Foundation::HWND, pub hwndNavigation: super::super::Foundation::HWND, pub hwndHTML: super::super::Foundation::HWND, pub iNavWidth: i32, pub rcHTML: super::super::Foundation::RECT, pub pszToc: *mut i8, pub pszIndex: *mut i8, pub pszFile: *mut i8, pub pszHome: *mut i8, pub fsToolBarFlags: u32, pub fNotExpanded: super::super::Foundation::BOOL, pub curNavType: i32, pub tabpos: i32, pub idNotify: i32, pub tabOrder: [u8; 20], pub cHistory: i32, pub pszJump1: *mut i8, pub pszJump2: *mut i8, pub pszUrlJump1: *mut i8, pub pszUrlJump2: *mut i8, pub rcMinSize: super::super::Foundation::RECT, pub cbInfoTypes: i32, pub pszCustomTabs: *mut i8, } #[cfg(feature = "Win32_Foundation")] impl HH_WINTYPE {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for HH_WINTYPE { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for HH_WINTYPE { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("HH_WINTYPE") .field("cbStruct", &self.cbStruct) .field("fUniCodeStrings", &self.fUniCodeStrings) .field("pszType", &self.pszType) .field("fsValidMembers", &self.fsValidMembers) .field("fsWinProperties", &self.fsWinProperties) .field("pszCaption", &self.pszCaption) .field("dwStyles", &self.dwStyles) .field("dwExStyles", &self.dwExStyles) .field("rcWindowPos", &self.rcWindowPos) .field("nShowState", &self.nShowState) .field("hwndHelp", &self.hwndHelp) .field("hwndCaller", &self.hwndCaller) .field("paInfoTypes", &self.paInfoTypes) .field("hwndToolBar", &self.hwndToolBar) .field("hwndNavigation", &self.hwndNavigation) .field("hwndHTML", &self.hwndHTML) .field("iNavWidth", &self.iNavWidth) .field("rcHTML", &self.rcHTML) .field("pszToc", &self.pszToc) .field("pszIndex", &self.pszIndex) .field("pszFile", &self.pszFile) .field("pszHome", &self.pszHome) .field("fsToolBarFlags", &self.fsToolBarFlags) .field("fNotExpanded", &self.fNotExpanded) .field("curNavType", &self.curNavType) .field("tabpos", &self.tabpos) .field("idNotify", &self.idNotify) .field("tabOrder", &self.tabOrder) .field("cHistory", &self.cHistory) .field("pszJump1", &self.pszJump1) .field("pszJump2", &self.pszJump2) .field("pszUrlJump1", &self.pszUrlJump1) .field("pszUrlJump2", &self.pszUrlJump2) .field("rcMinSize", &self.rcMinSize) .field("cbInfoTypes", &self.cbInfoTypes) .field("pszCustomTabs", &self.pszCustomTabs) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for HH_WINTYPE { fn eq(&self, other: &Self) -> bool { self.cbStruct == other.cbStruct && self.fUniCodeStrings == other.fUniCodeStrings && self.pszType == other.pszType && self.fsValidMembers == other.fsValidMembers && self.fsWinProperties == other.fsWinProperties && self.pszCaption == other.pszCaption && self.dwStyles == other.dwStyles && self.dwExStyles == other.dwExStyles && self.rcWindowPos == other.rcWindowPos && self.nShowState == other.nShowState && self.hwndHelp == other.hwndHelp && self.hwndCaller == other.hwndCaller && self.paInfoTypes == other.paInfoTypes && self.hwndToolBar == other.hwndToolBar && self.hwndNavigation == other.hwndNavigation && self.hwndHTML == other.hwndHTML && self.iNavWidth == other.iNavWidth && self.rcHTML == other.rcHTML && self.pszToc == other.pszToc && self.pszIndex == other.pszIndex && self.pszFile == other.pszFile && self.pszHome == other.pszHome && self.fsToolBarFlags == other.fsToolBarFlags && self.fNotExpanded == other.fNotExpanded && self.curNavType == other.curNavType && self.tabpos == other.tabpos && self.idNotify == other.idNotify && self.tabOrder == other.tabOrder && self.cHistory == other.cHistory && self.pszJump1 == other.pszJump1 && self.pszJump2 == other.pszJump2 && self.pszUrlJump1 == other.pszUrlJump1 && self.pszUrlJump2 == other.pszUrlJump2 && self.rcMinSize == other.rcMinSize && self.cbInfoTypes == other.cbInfoTypes && self.pszCustomTabs == other.pszCustomTabs } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for HH_WINTYPE {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for HH_WINTYPE { type Abi = Self; } pub const IDTB_BACK: u32 = 204u32; pub const IDTB_BROWSE_BACK: u32 = 212u32; pub const IDTB_BROWSE_FWD: u32 = 211u32; pub const IDTB_CONTENTS: u32 = 213u32; pub const IDTB_CONTRACT: u32 = 201u32; pub const IDTB_CUSTOMIZE: u32 = 221u32; pub const IDTB_EXPAND: u32 = 200u32; pub const IDTB_FAVORITES: u32 = 217u32; pub const IDTB_FORWARD: u32 = 209u32; pub const IDTB_HISTORY: u32 = 216u32; pub const IDTB_HOME: u32 = 205u32; pub const IDTB_INDEX: u32 = 214u32; pub const IDTB_JUMP1: u32 = 218u32; pub const IDTB_JUMP2: u32 = 219u32; pub const IDTB_NOTES: u32 = 210u32; pub const IDTB_OPTIONS: u32 = 208u32; pub const IDTB_PRINT: u32 = 207u32; pub const IDTB_REFRESH: u32 = 203u32; pub const IDTB_SEARCH: u32 = 215u32; pub const IDTB_STOP: u32 = 202u32; pub const IDTB_SYNC: u32 = 206u32; pub const IDTB_TOC_NEXT: u32 = 223u32; pub const IDTB_TOC_PREV: u32 = 224u32; pub const IDTB_ZOOM: u32 = 222u32; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IITDatabase(pub ::windows::core::IUnknown); impl IITDatabase { #[cfg(feature = "Win32_Foundation")] pub unsafe fn Open<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, lpszhost: Param0, lpszmoniker: Param1, dwflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), lpszhost.into_param().abi(), lpszmoniker.into_param().abi(), ::core::mem::transmute(dwflags)).ok() } pub unsafe fn Close(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn CreateObject(&self, rclsid: *const ::windows::core::GUID, pdwobjinstance: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(rclsid), ::core::mem::transmute(pdwobjinstance)).ok() } pub unsafe fn GetObject(&self, dwobjinstance: u32, riid: *const ::windows::core::GUID, ppvobj: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwobjinstance), ::core::mem::transmute(riid), ::core::mem::transmute(ppvobj)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetObjectPersistence<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, lpwszobject: Param0, dwobjinstance: u32, ppvpersistence: *mut *mut ::core::ffi::c_void, fstream: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), lpwszobject.into_param().abi(), ::core::mem::transmute(dwobjinstance), ::core::mem::transmute(ppvpersistence), fstream.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IITDatabase { type Vtable = IITDatabase_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8fa0d5a2_dedf_11d0_9a61_00c04fb68bf7); } impl ::core::convert::From<IITDatabase> for ::windows::core::IUnknown { fn from(value: IITDatabase) -> Self { value.0 } } impl ::core::convert::From<&IITDatabase> for ::windows::core::IUnknown { fn from(value: &IITDatabase) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IITDatabase { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IITDatabase { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IITDatabase_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpszhost: super::super::Foundation::PWSTR, lpszmoniker: super::super::Foundation::PWSTR, dwflags: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rclsid: *const ::windows::core::GUID, pdwobjinstance: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwobjinstance: u32, riid: *const ::windows::core::GUID, ppvobj: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpwszobject: super::super::Foundation::PWSTR, dwobjinstance: u32, ppvpersistence: *mut *mut ::core::ffi::c_void, fstream: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(C)] #[derive(:: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy)] pub struct IITGroup(pub u8); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IITPropList(pub ::windows::core::IUnknown); impl IITPropList { pub unsafe fn GetClassID(&self) -> ::windows::core::Result<::windows::core::GUID> { let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::GUID>(result__) } pub unsafe fn IsDirty(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_System_Com")] pub unsafe fn Load<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::Com::IStream>>(&self, pstm: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), pstm.into_param().abi()).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe fn Save<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::Com::IStream>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, pstm: Param0, fcleardirty: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), pstm.into_param().abi(), fcleardirty.into_param().abi()).ok() } pub unsafe fn GetSizeMax(&self) -> ::windows::core::Result<u64> { let mut result__: <u64 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u64>(result__) } pub unsafe fn InitNew(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Set<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, propid: u32, lpszwstring: Param1, dwoperation: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid), lpszwstring.into_param().abi(), ::core::mem::transmute(dwoperation)).ok() } pub unsafe fn Set2(&self, propid: u32, lpvdata: *mut ::core::ffi::c_void, cbdata: u32, dwoperation: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid), ::core::mem::transmute(lpvdata), ::core::mem::transmute(cbdata), ::core::mem::transmute(dwoperation)).ok() } pub unsafe fn Set3(&self, propid: u32, dwdata: u32, dwoperation: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid), ::core::mem::transmute(dwdata), ::core::mem::transmute(dwoperation)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Add(&self, prop: *mut CProperty) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(prop)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Get(&self, propid: u32, property: *mut CProperty) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid), ::core::mem::transmute(property)).ok() } pub unsafe fn Clear(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPersist<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, fpersist: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), fpersist.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn SetPersist2<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, propid: u32, fpersist: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid), fpersist.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetFirst(&self, property: *mut CProperty) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(property)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNext(&self, property: *mut CProperty) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(property)).ok() } pub unsafe fn GetPropCount(&self, cprop: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(cprop)).ok() } pub unsafe fn SaveHeader(&self, lpvdata: *mut ::core::ffi::c_void, dwhdrsize: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpvdata), ::core::mem::transmute(dwhdrsize)).ok() } pub unsafe fn SaveData(&self, lpvheader: *mut ::core::ffi::c_void, dwhdrsize: u32, lpvdata: *mut ::core::ffi::c_void, dwbufsize: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpvheader), ::core::mem::transmute(dwhdrsize), ::core::mem::transmute(lpvdata), ::core::mem::transmute(dwbufsize)).ok() } pub unsafe fn GetHeaderSize(&self, dwhdrsize: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwhdrsize)).ok() } pub unsafe fn GetDataSize(&self, lpvheader: *mut ::core::ffi::c_void, dwhdrsize: u32, dwdatasize: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpvheader), ::core::mem::transmute(dwhdrsize), ::core::mem::transmute(dwdatasize)).ok() } #[cfg(feature = "Win32_System_Com")] pub unsafe fn SaveDataToStream<'a, Param2: ::windows::core::IntoParam<'a, super::super::System::Com::IStream>>(&self, lpvheader: *mut ::core::ffi::c_void, dwhdrsize: u32, pstream: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpvheader), ::core::mem::transmute(dwhdrsize), pstream.into_param().abi()).ok() } pub unsafe fn LoadFromMem(&self, lpvdata: *mut ::core::ffi::c_void, dwbufsize: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpvdata), ::core::mem::transmute(dwbufsize)).ok() } pub unsafe fn SaveToMem(&self, lpvdata: *mut ::core::ffi::c_void, dwbufsize: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpvdata), ::core::mem::transmute(dwbufsize)).ok() } } unsafe impl ::windows::core::Interface for IITPropList { type Vtable = IITPropList_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1f403bb1_9997_11d0_a850_00aa006c7d01); } impl ::core::convert::From<IITPropList> for ::windows::core::IUnknown { fn from(value: IITPropList) -> Self { value.0 } } impl ::core::convert::From<&IITPropList> for ::windows::core::IUnknown { fn from(value: &IITPropList) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IITPropList { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IITPropList { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[cfg(feature = "Win32_System_Com")] impl ::core::convert::From<IITPropList> for super::super::System::Com::IPersistStreamInit { fn from(value: IITPropList) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Win32_System_Com")] impl ::core::convert::From<&IITPropList> for super::super::System::Com::IPersistStreamInit { fn from(value: &IITPropList) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Win32_System_Com")] impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IPersistStreamInit> for IITPropList { fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IPersistStreamInit> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Win32_System_Com")] impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IPersistStreamInit> for &IITPropList { fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IPersistStreamInit> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Win32_System_Com")] impl ::core::convert::From<IITPropList> for super::super::System::Com::IPersist { fn from(value: IITPropList) -> Self { unsafe { ::core::mem::transmute(value) } } } #[cfg(feature = "Win32_System_Com")] impl ::core::convert::From<&IITPropList> for super::super::System::Com::IPersist { fn from(value: &IITPropList) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } #[cfg(feature = "Win32_System_Com")] impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IPersist> for IITPropList { fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IPersist> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } #[cfg(feature = "Win32_System_Com")] impl<'a> ::windows::core::IntoParam<'a, super::super::System::Com::IPersist> for &IITPropList { fn into_param(self) -> ::windows::core::Param<'a, super::super::System::Com::IPersist> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct IITPropList_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pclassid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstm: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_System_Com"))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Com"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstm: ::windows::core::RawPtr, fcleardirty: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Com")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcbsize: *mut u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32, lpszwstring: super::super::Foundation::PWSTR, dwoperation: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32, lpvdata: *mut ::core::ffi::c_void, cbdata: u32, dwoperation: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32, dwdata: u32, dwoperation: u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, prop: *mut CProperty) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32, property: *mut CProperty) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fpersist: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32, fpersist: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, property: *mut CProperty) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, property: *mut CProperty) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, cprop: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpvdata: *mut ::core::ffi::c_void, dwhdrsize: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpvheader: *mut ::core::ffi::c_void, dwhdrsize: u32, lpvdata: *mut ::core::ffi::c_void, dwbufsize: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwhdrsize: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpvheader: *mut ::core::ffi::c_void, dwhdrsize: u32, dwdatasize: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpvheader: *mut ::core::ffi::c_void, dwhdrsize: u32, pstream: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_System_Com"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpvdata: *mut ::core::ffi::c_void, dwbufsize: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpvdata: *mut ::core::ffi::c_void, dwbufsize: u32) -> ::windows::core::HRESULT, ); #[repr(C)] #[derive(:: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy)] pub struct IITQuery(pub u8); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IITResultSet(pub ::windows::core::IUnknown); impl IITResultSet { pub unsafe fn SetColumnPriority(&self, lcolumnindex: i32, columnpriority: PRIORITY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(lcolumnindex), ::core::mem::transmute(columnpriority)).ok() } pub unsafe fn SetColumnHeap(&self, lcolumnindex: i32, lpvheap: *mut ::core::ffi::c_void, pfncolheapfree: ::core::option::Option<PFNCOLHEAPFREE>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(lcolumnindex), ::core::mem::transmute(lpvheap), ::core::mem::transmute(pfncolheapfree)).ok() } pub unsafe fn SetKeyProp(&self, propid: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid)).ok() } pub unsafe fn Add(&self, propid: u32, dwdefaultdata: u32, priority: PRIORITY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid), ::core::mem::transmute(dwdefaultdata), ::core::mem::transmute(priority)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Add2<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, propid: u32, lpszwdefault: Param1, priority: PRIORITY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid), lpszwdefault.into_param().abi(), ::core::mem::transmute(priority)).ok() } pub unsafe fn Add3(&self, propid: u32, lpvdefaultdata: *mut ::core::ffi::c_void, cbdata: u32, priority: PRIORITY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid), ::core::mem::transmute(lpvdefaultdata), ::core::mem::transmute(cbdata), ::core::mem::transmute(priority)).ok() } pub unsafe fn Add4(&self, lpvhdr: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpvhdr)).ok() } pub unsafe fn Append(&self, lpvhdr: *mut ::core::ffi::c_void, lpvdata: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpvhdr), ::core::mem::transmute(lpvdata)).ok() } pub unsafe fn Set(&self, lrowindex: i32, lcolumnindex: i32, lpvdata: *mut ::core::ffi::c_void, cbdata: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(lrowindex), ::core::mem::transmute(lcolumnindex), ::core::mem::transmute(lpvdata), ::core::mem::transmute(cbdata)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Set2<'a, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, lrowindex: i32, lcolumnindex: i32, lpwstr: Param2) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(lrowindex), ::core::mem::transmute(lcolumnindex), lpwstr.into_param().abi()).ok() } pub unsafe fn Set3(&self, lrowindex: i32, lcolumnindex: i32, dwdata: usize) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(lrowindex), ::core::mem::transmute(lcolumnindex), ::core::mem::transmute(dwdata)).ok() } pub unsafe fn Set4(&self, lrowindex: i32, lpvhdr: *mut ::core::ffi::c_void, lpvdata: *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(lrowindex), ::core::mem::transmute(lpvhdr), ::core::mem::transmute(lpvdata)).ok() } pub unsafe fn Copy<'a, Param0: ::windows::core::IntoParam<'a, IITResultSet>>(&self, prscopy: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), prscopy.into_param().abi()).ok() } pub unsafe fn AppendRows<'a, Param0: ::windows::core::IntoParam<'a, IITResultSet>>(&self, pressrc: Param0, lrowsrcfirst: i32, csrcrows: i32, lrowfirstdest: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), pressrc.into_param().abi(), ::core::mem::transmute(lrowsrcfirst), ::core::mem::transmute(csrcrows), ::core::mem::transmute(lrowfirstdest)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Get(&self, lrowindex: i32, lcolumnindex: i32, prop: *mut CProperty) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(lrowindex), ::core::mem::transmute(lcolumnindex), ::core::mem::transmute(prop)).ok() } pub unsafe fn GetKeyProp(&self, keypropid: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(keypropid)).ok() } pub unsafe fn GetColumnPriority(&self, lcolumnindex: i32, columnpriority: *mut PRIORITY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(lcolumnindex), ::core::mem::transmute(columnpriority)).ok() } pub unsafe fn GetRowCount(&self, lnumberofrows: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(lnumberofrows)).ok() } pub unsafe fn GetColumnCount(&self, lnumberofcolumns: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(lnumberofcolumns)).ok() } pub unsafe fn GetColumn(&self, lcolumnindex: i32, propid: *mut u32, dwtype: *mut u32, lpvdefaultvalue: *mut *mut ::core::ffi::c_void, cbsize: *mut u32, columnpriority: *mut PRIORITY) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).22)(::core::mem::transmute_copy(self), ::core::mem::transmute(lcolumnindex), ::core::mem::transmute(propid), ::core::mem::transmute(dwtype), ::core::mem::transmute(lpvdefaultvalue), ::core::mem::transmute(cbsize), ::core::mem::transmute(columnpriority)).ok() } pub unsafe fn GetColumn2(&self, lcolumnindex: i32, propid: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).23)(::core::mem::transmute_copy(self), ::core::mem::transmute(lcolumnindex), ::core::mem::transmute(propid)).ok() } pub unsafe fn GetColumnFromPropID(&self, propid: u32, lcolumnindex: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).24)(::core::mem::transmute_copy(self), ::core::mem::transmute(propid), ::core::mem::transmute(lcolumnindex)).ok() } pub unsafe fn Clear(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).25)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn ClearRows(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).26)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Free(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).27)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn IsCompleted(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).28)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn Cancel(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).29)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Pause<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, fpause: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).30)(::core::mem::transmute_copy(self), fpause.into_param().abi()).ok() } pub unsafe fn GetRowStatus(&self, lrowfirst: i32, crows: i32, lprowstatus: *mut ROWSTATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).31)(::core::mem::transmute_copy(self), ::core::mem::transmute(lrowfirst), ::core::mem::transmute(crows), ::core::mem::transmute(lprowstatus)).ok() } pub unsafe fn GetColumnStatus(&self, lpcolstatus: *mut COLUMNSTATUS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).32)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpcolstatus)).ok() } } unsafe impl ::windows::core::Interface for IITResultSet { type Vtable = IITResultSet_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3bb91d41_998b_11d0_a850_00aa006c7d01); } impl ::core::convert::From<IITResultSet> for ::windows::core::IUnknown { fn from(value: IITResultSet) -> Self { value.0 } } impl ::core::convert::From<&IITResultSet> for ::windows::core::IUnknown { fn from(value: &IITResultSet) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IITResultSet { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IITResultSet { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IITResultSet_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lcolumnindex: i32, columnpriority: PRIORITY) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lcolumnindex: i32, lpvheap: *mut ::core::ffi::c_void, pfncolheapfree: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32, dwdefaultdata: u32, priority: PRIORITY) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32, lpszwdefault: super::super::Foundation::PWSTR, priority: PRIORITY) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32, lpvdefaultdata: *mut ::core::ffi::c_void, cbdata: u32, priority: PRIORITY) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpvhdr: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpvhdr: *mut ::core::ffi::c_void, lpvdata: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lrowindex: i32, lcolumnindex: i32, lpvdata: *mut ::core::ffi::c_void, cbdata: u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lrowindex: i32, lcolumnindex: i32, lpwstr: super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lrowindex: i32, lcolumnindex: i32, dwdata: usize) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lrowindex: i32, lpvhdr: *mut ::core::ffi::c_void, lpvdata: *mut ::core::ffi::c_void) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, prscopy: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pressrc: ::windows::core::RawPtr, lrowsrcfirst: i32, csrcrows: i32, lrowfirstdest: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lrowindex: i32, lcolumnindex: i32, prop: *mut CProperty) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, keypropid: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lcolumnindex: i32, columnpriority: *mut PRIORITY) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lnumberofrows: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lnumberofcolumns: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lcolumnindex: i32, propid: *mut u32, dwtype: *mut u32, lpvdefaultvalue: *mut *mut ::core::ffi::c_void, cbsize: *mut u32, columnpriority: *mut PRIORITY) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lcolumnindex: i32, propid: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, propid: u32, lcolumnindex: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, fpause: super::super::Foundation::BOOL) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lrowfirst: i32, crows: i32, lprowstatus: *mut ROWSTATUS) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpcolstatus: *mut COLUMNSTATUS) -> ::windows::core::HRESULT, ); #[repr(C)] #[derive(:: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug, :: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy)] pub struct IITStopWordList(pub u8); pub const IITWBC_BREAK_ACCEPT_WILDCARDS: u32 = 1u32; pub const IITWBC_BREAK_AND_STEM: u32 = 2u32; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IITWordWheel(pub ::windows::core::IUnknown); impl IITWordWheel { #[cfg(feature = "Win32_Foundation")] pub unsafe fn Open<'a, Param0: ::windows::core::IntoParam<'a, IITDatabase>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, lpitdb: Param0, lpszmoniker: Param1, dwflags: WORD_WHEEL_OPEN_FLAGS) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), lpitdb.into_param().abi(), lpszmoniker.into_param().abi(), ::core::mem::transmute(dwflags)).ok() } pub unsafe fn Close(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn GetLocaleInfo(&self, pdwcodepageid: *mut u32, plcid: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwcodepageid), ::core::mem::transmute(plcid)).ok() } pub unsafe fn GetSorterInstance(&self, pdwobjinstance: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwobjinstance)).ok() } pub unsafe fn Count(&self, pcentries: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(pcentries)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Lookup<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::BOOL>>(&self, lpcvprefix: *const ::core::ffi::c_void, fexactmatch: Param1, plentry: *mut i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(lpcvprefix), fexactmatch.into_param().abi(), ::core::mem::transmute(plentry)).ok() } pub unsafe fn Lookup2<'a, Param1: ::windows::core::IntoParam<'a, IITResultSet>>(&self, lentry: i32, lpitresult: Param1, centries: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), ::core::mem::transmute(lentry), lpitresult.into_param().abi(), ::core::mem::transmute(centries)).ok() } pub unsafe fn Lookup3(&self, lentry: i32, lpvkeybuf: *mut ::core::ffi::c_void, cbkeybuf: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(lentry), ::core::mem::transmute(lpvkeybuf), ::core::mem::transmute(cbkeybuf)).ok() } pub unsafe fn SetGroup(&self, piitgroup: *mut IITGroup) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(piitgroup)).ok() } pub unsafe fn GetGroup(&self, ppiitgroup: *mut *mut IITGroup) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(ppiitgroup)).ok() } pub unsafe fn GetDataCount(&self, lentry: i32, pdwcount: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(lentry), ::core::mem::transmute(pdwcount)).ok() } pub unsafe fn GetData<'a, Param1: ::windows::core::IntoParam<'a, IITResultSet>>(&self, lentry: i32, lpitresult: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), ::core::mem::transmute(lentry), lpitresult.into_param().abi()).ok() } pub unsafe fn GetDataColumns<'a, Param0: ::windows::core::IntoParam<'a, IITResultSet>>(&self, prs: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), prs.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for IITWordWheel { type Vtable = IITWordWheel_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8fa0d5a4_dedf_11d0_9a61_00c04fb68bf7); } impl ::core::convert::From<IITWordWheel> for ::windows::core::IUnknown { fn from(value: IITWordWheel) -> Self { value.0 } } impl ::core::convert::From<&IITWordWheel> for ::windows::core::IUnknown { fn from(value: &IITWordWheel) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IITWordWheel { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IITWordWheel { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IITWordWheel_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpitdb: ::windows::core::RawPtr, lpszmoniker: super::super::Foundation::PWSTR, dwflags: WORD_WHEEL_OPEN_FLAGS) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwcodepageid: *mut u32, plcid: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwobjinstance: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pcentries: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lpcvprefix: *const ::core::ffi::c_void, fexactmatch: super::super::Foundation::BOOL, plentry: *mut i32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lentry: i32, lpitresult: ::windows::core::RawPtr, centries: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lentry: i32, lpvkeybuf: *mut ::core::ffi::c_void, cbkeybuf: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, piitgroup: *mut IITGroup) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppiitgroup: *mut *mut IITGroup) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lentry: i32, pdwcount: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, lentry: i32, lpitresult: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, prs: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IStemSink(pub ::windows::core::IUnknown); impl IStemSink { #[cfg(feature = "Win32_Foundation")] pub unsafe fn PutAltWord<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwcinbuf: Param0, cwc: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pwcinbuf.into_param().abi(), ::core::mem::transmute(cwc)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn PutWord<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(&self, pwcinbuf: Param0, cwc: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), pwcinbuf.into_param().abi(), ::core::mem::transmute(cwc)).ok() } } unsafe impl ::windows::core::Interface for IStemSink { type Vtable = IStemSink_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfe77c330_7f42_11ce_be57_00aa0051fe20); } impl ::core::convert::From<IStemSink> for ::windows::core::IUnknown { fn from(value: IStemSink) -> Self { value.0 } } impl ::core::convert::From<&IStemSink> for ::windows::core::IUnknown { fn from(value: &IStemSink) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IStemSink { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IStemSink { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IStemSink_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwcinbuf: super::super::Foundation::PWSTR, cwc: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwcinbuf: super::super::Foundation::PWSTR, cwc: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IStemmerConfig(pub ::windows::core::IUnknown); impl IStemmerConfig { pub unsafe fn SetLocaleInfo(&self, dwcodepageid: u32, lcid: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwcodepageid), ::core::mem::transmute(lcid)).ok() } pub unsafe fn GetLocaleInfo(&self, pdwcodepageid: *mut u32, plcid: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwcodepageid), ::core::mem::transmute(plcid)).ok() } pub unsafe fn SetControlInfo(&self, grfstemflags: u32, dwreserved: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(grfstemflags), ::core::mem::transmute(dwreserved)).ok() } pub unsafe fn GetControlInfo(&self, pgrfstemflags: *mut u32, pdwreserved: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pgrfstemflags), ::core::mem::transmute(pdwreserved)).ok() } #[cfg(feature = "Win32_System_Com")] pub unsafe fn LoadExternalStemmerData<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::Com::IStream>>(&self, pstream: Param0, dwextdatatype: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), pstream.into_param().abi(), ::core::mem::transmute(dwextdatatype)).ok() } } unsafe impl ::windows::core::Interface for IStemmerConfig { type Vtable = IStemmerConfig_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8fa0d5a7_dedf_11d0_9a61_00c04fb68bf7); } impl ::core::convert::From<IStemmerConfig> for ::windows::core::IUnknown { fn from(value: IStemmerConfig) -> Self { value.0 } } impl ::core::convert::From<&IStemmerConfig> for ::windows::core::IUnknown { fn from(value: &IStemmerConfig) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IStemmerConfig { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IStemmerConfig { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IStemmerConfig_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwcodepageid: u32, lcid: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwcodepageid: *mut u32, plcid: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, grfstemflags: u32, dwreserved: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pgrfstemflags: *mut u32, pdwreserved: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstream: ::windows::core::RawPtr, dwextdatatype: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_System_Com"))] usize, ); pub const ITWW_CBKEY_MAX: u32 = 1024u32; pub const ITWW_OPEN_NOCONNECT: u32 = 1u32; pub const IT_EXCLUSIVE: i32 = 1i32; pub const IT_HIDDEN: i32 = 2i32; pub const IT_INCLUSIVE: i32 = 0i32; #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IWordBreakerConfig(pub ::windows::core::IUnknown); impl IWordBreakerConfig { pub unsafe fn SetLocaleInfo(&self, dwcodepageid: u32, lcid: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwcodepageid), ::core::mem::transmute(lcid)).ok() } pub unsafe fn GetLocaleInfo(&self, pdwcodepageid: *mut u32, plcid: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwcodepageid), ::core::mem::transmute(plcid)).ok() } pub unsafe fn SetBreakWordType(&self, dwbreakwordtype: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(dwbreakwordtype)).ok() } pub unsafe fn GetBreakWordType(&self, pdwbreakwordtype: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(pdwbreakwordtype)).ok() } pub unsafe fn SetControlInfo(&self, grfbreakflags: u32, dwreserved: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(grfbreakflags), ::core::mem::transmute(dwreserved)).ok() } pub unsafe fn GetControlInfo(&self, pgrfbreakflags: *mut u32, pdwreserved: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(pgrfbreakflags), ::core::mem::transmute(pdwreserved)).ok() } #[cfg(feature = "Win32_System_Com")] pub unsafe fn LoadExternalBreakerData<'a, Param0: ::windows::core::IntoParam<'a, super::super::System::Com::IStream>>(&self, pstream: Param0, dwextdatatype: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), pstream.into_param().abi(), ::core::mem::transmute(dwextdatatype)).ok() } #[cfg(feature = "Win32_System_Search")] pub unsafe fn SetWordStemmer<'a, Param1: ::windows::core::IntoParam<'a, super::super::System::Search::IStemmer>>(&self, rclsid: *const ::windows::core::GUID, pstemmer: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(rclsid), pstemmer.into_param().abi()).ok() } #[cfg(feature = "Win32_System_Search")] pub unsafe fn GetWordStemmer(&self) -> ::windows::core::Result<super::super::System::Search::IStemmer> { let mut result__: <super::super::System::Search::IStemmer as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::System::Search::IStemmer>(result__) } } unsafe impl ::windows::core::Interface for IWordBreakerConfig { type Vtable = IWordBreakerConfig_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8fa0d5a6_dedf_11d0_9a61_00c04fb68bf7); } impl ::core::convert::From<IWordBreakerConfig> for ::windows::core::IUnknown { fn from(value: IWordBreakerConfig) -> Self { value.0 } } impl ::core::convert::From<&IWordBreakerConfig> for ::windows::core::IUnknown { fn from(value: &IWordBreakerConfig) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IWordBreakerConfig { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IWordBreakerConfig { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IWordBreakerConfig_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwcodepageid: u32, lcid: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwcodepageid: *mut u32, plcid: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, dwbreakwordtype: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pdwbreakwordtype: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, grfbreakflags: u32, dwreserved: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pgrfbreakflags: *mut u32, pdwreserved: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_System_Com")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pstream: ::windows::core::RawPtr, dwextdatatype: u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_System_Com"))] usize, #[cfg(feature = "Win32_System_Search")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, rclsid: *const ::windows::core::GUID, pstemmer: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_System_Search"))] usize, #[cfg(feature = "Win32_System_Search")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppstemmer: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_System_Search"))] usize, ); pub const MAX_COLUMNS: u32 = 256u32; pub type PFNCOLHEAPFREE = unsafe extern "system" fn(param0: *mut ::core::ffi::c_void) -> i32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct PRIORITY(pub i32); pub const PRIORITY_LOW: PRIORITY = PRIORITY(0i32); pub const PRIORITY_NORMAL: PRIORITY = PRIORITY(1i32); pub const PRIORITY_HIGH: PRIORITY = PRIORITY(2i32); impl ::core::convert::From<i32> for PRIORITY { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for PRIORITY { type Abi = Self; } pub const PROP_ADD: u32 = 0u32; pub const PROP_DELETE: u32 = 1u32; pub const PROP_UPDATE: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct ROWSTATUS { pub lRowFirst: i32, pub cRows: i32, pub cProperties: i32, pub cRowsTotal: i32, } impl ROWSTATUS {} impl ::core::default::Default for ROWSTATUS { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for ROWSTATUS { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("ROWSTATUS").field("lRowFirst", &self.lRowFirst).field("cRows", &self.cRows).field("cProperties", &self.cProperties).field("cRowsTotal", &self.cRowsTotal).finish() } } impl ::core::cmp::PartialEq for ROWSTATUS { fn eq(&self, other: &Self) -> bool { self.lRowFirst == other.lRowFirst && self.cRows == other.cRows && self.cProperties == other.cProperties && self.cRowsTotal == other.cRowsTotal } } impl ::core::cmp::Eq for ROWSTATUS {} unsafe impl ::windows::core::Abi for ROWSTATUS { type Abi = Self; } pub const STDPROP_DISPLAYKEY: u32 = 101u32; pub const STDPROP_INDEX_BREAK: u32 = 204u32; pub const STDPROP_INDEX_DTYPE: u32 = 202u32; pub const STDPROP_INDEX_LENGTH: u32 = 203u32; pub const STDPROP_INDEX_TERM: u32 = 210u32; pub const STDPROP_INDEX_TERM_RAW_LENGTH: u32 = 211u32; pub const STDPROP_INDEX_TEXT: u32 = 200u32; pub const STDPROP_INDEX_VFLD: u32 = 201u32; pub const STDPROP_KEY: u32 = 4u32; pub const STDPROP_SORTKEY: u32 = 100u32; pub const STDPROP_SORTORDINAL: u32 = 102u32; pub const STDPROP_TITLE: u32 = 2u32; pub const STDPROP_UID: u32 = 1u32; pub const STDPROP_USERDATA: u32 = 3u32; pub const STDPROP_USERPROP_BASE: u32 = 65536u32; pub const STDPROP_USERPROP_MAX: u32 = 2147483647u32; pub const TYPE_POINTER: u32 = 1u32; pub const TYPE_STRING: u32 = 2u32; pub const TYPE_VALUE: u32 = 0u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct WORD_WHEEL_OPEN_FLAGS(pub u32); pub const ITWW_OPEN_CONNECT: WORD_WHEEL_OPEN_FLAGS = WORD_WHEEL_OPEN_FLAGS(0u32); impl ::core::convert::From<u32> for WORD_WHEEL_OPEN_FLAGS { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for WORD_WHEEL_OPEN_FLAGS { type Abi = Self; } impl ::core::ops::BitOr for WORD_WHEEL_OPEN_FLAGS { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for WORD_WHEEL_OPEN_FLAGS { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for WORD_WHEEL_OPEN_FLAGS { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for WORD_WHEEL_OPEN_FLAGS { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for WORD_WHEEL_OPEN_FLAGS { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } }
//! CLI config for the router using the RPC write path use crate::{ gossip::GossipConfig, ingester_address::IngesterAddress, single_tenant::{ CONFIG_AUTHZ_ENV_NAME, CONFIG_AUTHZ_FLAG, CONFIG_CST_ENV_NAME, CONFIG_CST_FLAG, }, }; use std::{ num::{NonZeroUsize, ParseIntError}, time::Duration, }; /// CLI config for the router using the RPC write path #[derive(Debug, Clone, clap::Parser)] #[allow(missing_copy_implementations)] pub struct RouterConfig { /// Gossip config. #[clap(flatten)] pub gossip_config: GossipConfig, /// Addr for connection to authz #[clap( long = CONFIG_AUTHZ_FLAG, env = CONFIG_AUTHZ_ENV_NAME, requires("single_tenant_deployment"), )] pub authz_address: Option<String>, /// Differential handling based upon deployment to CST vs MT. /// /// At minimum, differs in supports of v1 endpoint. But also includes /// differences in namespace handling, etc. #[clap( long = CONFIG_CST_FLAG, env = CONFIG_CST_ENV_NAME, default_value = "false", requires_if("true", "authz_address") )] pub single_tenant_deployment: bool, /// The maximum number of simultaneous requests the HTTP server is /// configured to accept. /// /// This number of requests, multiplied by the maximum request body size the /// HTTP server is configured with gives the rough amount of memory a HTTP /// server will use to buffer request bodies in memory. /// /// A default maximum of 200 requests, multiplied by the default 10MiB /// maximum for HTTP request bodies == ~2GiB. #[clap( long = "max-http-requests", env = "INFLUXDB_IOX_MAX_HTTP_REQUESTS", default_value = "200", action )] pub http_request_limit: usize, /// gRPC address for the router to talk with the ingesters. For /// example: /// /// "http://127.0.0.1:8083" /// /// or /// /// "http://10.10.10.1:8083,http://10.10.10.2:8083" /// /// for multiple addresses. #[clap( long = "ingester-addresses", env = "INFLUXDB_IOX_INGESTER_ADDRESSES", required = true, num_args=1.., value_delimiter = ',' )] pub ingester_addresses: Vec<IngesterAddress>, /// Retention period to use when auto-creating namespaces. /// For infinite retention, leave this unset and it will default to `None`. /// Setting it to zero will not make it infinite. /// Ignored if namespace-autocreation-enabled is set to false. #[clap( long = "new-namespace-retention-hours", env = "INFLUXDB_IOX_NEW_NAMESPACE_RETENTION_HOURS", action )] pub new_namespace_retention_hours: Option<u64>, /// When writing data to a non-existent namespace, should the router auto-create the namespace /// or reject the write? Set to false to disable namespace autocreation. #[clap( long = "namespace-autocreation-enabled", env = "INFLUXDB_IOX_NAMESPACE_AUTOCREATION_ENABLED", default_value = "true", action )] pub namespace_autocreation_enabled: bool, /// Specify the timeout in seconds for a single RPC write request to an /// ingester. #[clap( long = "rpc-write-timeout-seconds", env = "INFLUXDB_IOX_RPC_WRITE_TIMEOUT_SECONDS", default_value = "3", value_parser = parse_duration )] pub rpc_write_timeout_seconds: Duration, /// Specify the maximum allowed outgoing RPC write message size when /// communicating with the Ingester. #[clap( long = "rpc-write-max-outgoing-bytes", env = "INFLUXDB_IOX_RPC_WRITE_MAX_OUTGOING_BYTES", default_value = "104857600", // 100MiB )] pub rpc_write_max_outgoing_bytes: usize, /// Enable optional replication for each RPC write. /// /// This value specifies the total number of copies of data after /// replication, defaulting to 1. /// /// If the desired replication level is not achieved, a partial write error /// will be returned to the user. The write MAY be queryable after a partial /// write failure. #[clap( long = "rpc-write-replicas", env = "INFLUXDB_IOX_RPC_WRITE_REPLICAS", default_value = "1" )] pub rpc_write_replicas: NonZeroUsize, /// Specify the maximum number of probe requests to be sent per second. /// /// At least 20% of these requests must succeed within a second for the /// endpoint to be considered healthy. #[clap( long = "rpc-write-health-num-probes", env = "INFLUXDB_IOX_RPC_WRITE_HEALTH_NUM_PROBES", default_value = "10" )] pub rpc_write_health_num_probes: u64, } /// Map a string containing an integer number of seconds into a [`Duration`]. fn parse_duration(input: &str) -> Result<Duration, ParseIntError> { input.parse().map(Duration::from_secs) }
#![allow(unused_imports)] #![allow(dead_code)] use std::collections::HashMap; use std::str; use rand::rngs::OsRng; use rsa::pkcs1::{ToRsaPrivateKey, ToRsaPublicKey}; use rsa::{RsaPrivateKey}; use super::digest::*; use super::system::*; // #[ derive( Debug, Clone, Serialize, Deserialize, PartialEq ) ] pub struct Wallet { pub name : String, pub public_key : Digest, pub private_key : Digest, } // impl Wallet { // pub fn new< 'a, 'b >( _wallets : &'a mut HashMap< String, Wallet >, _name : &'b String ) -> Option< &'a Wallet > { None /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/4 test : https://github.com/Learn-Together-Pro/Blockchain/blob/main/rust/blockchain/test/wallet_test.rs#L11 complexity : mid stage : late */ } // pub fn keys_pair_generate() -> ( Digest, Digest ) { /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/3 test : https://github.com/Learn-Together-Pro/Blockchain/blob/main/rust/blockchain/test/wallet_test.rs#L66 complexity : mid stage : mid */ let mut rng = OsRng; let bits = 2048; let private_key = RsaPrivateKey::new(&mut rng, bits) .expect("failed to generate private key"); let pub_key = RsaPrivateKey::to_public_key(&private_key).to_pkcs1_pem() .expect("failed to generate public key"); let private_key_pem = private_key.to_pkcs1_pem() .expect("failed to convert private to pem"); ( Digest::from(pub_key.as_bytes().to_vec()), Digest::from( private_key_pem.as_bytes().to_vec() )) } // } // impl System { // pub fn wallet_create( &mut self, name : &String ) -> Option< &Wallet > { Wallet::new( &mut self.wallets, name ) } // }
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::sync::Arc; use common_catalog::table::Table; use common_exception::Result; use common_expression::types::number::NumberColumnBuilder; use common_expression::types::number::NumberScalar; use common_expression::types::string::StringColumnBuilder; use common_expression::types::DataType; use common_expression::types::NumberDataType; use common_expression::types::StringType; use common_expression::BlockEntry; use common_expression::Column; use common_expression::DataBlock; use common_expression::FromOptData; use common_expression::Scalar; use common_expression::TableDataType; use common_expression::TableField; use common_expression::TableSchema; use common_expression::TableSchemaRefExt; use common_expression::Value; use futures_util::TryStreamExt; use storages_common_table_meta::meta::TableSnapshot; use crate::io::MetaReaders; use crate::io::SegmentsIO; use crate::io::SnapshotHistoryReader; use crate::sessions::TableContext; use crate::FuseTable; pub struct FuseBlock<'a> { pub ctx: Arc<dyn TableContext>, pub table: &'a FuseTable, pub snapshot_id: Option<String>, } impl<'a> FuseBlock<'a> { pub fn new( ctx: Arc<dyn TableContext>, table: &'a FuseTable, snapshot_id: Option<String>, ) -> Self { Self { ctx, table, snapshot_id, } } pub async fn get_blocks(&self) -> Result<DataBlock> { let tbl = self.table; let maybe_snapshot = tbl.read_table_snapshot().await?; if let Some(snapshot) = maybe_snapshot { if self.snapshot_id.is_none() { return self.to_block(snapshot).await; } // prepare the stream of snapshot let snapshot_version = tbl.snapshot_format_version().await?; let snapshot_location = tbl .meta_location_generator .snapshot_location_from_uuid(&snapshot.snapshot_id, snapshot_version)?; let reader = MetaReaders::table_snapshot_reader(tbl.get_operator()); let mut snapshot_stream = reader.snapshot_history( snapshot_location, snapshot_version, tbl.meta_location_generator().clone(), ); // find the element by snapshot_id in stream while let Some(snapshot) = snapshot_stream.try_next().await? { if snapshot.snapshot_id.simple().to_string() == self.snapshot_id.clone().unwrap() { return self.to_block(snapshot).await; } } } Ok(DataBlock::empty_with_schema(Arc::new( Self::schema().into(), ))) } async fn to_block(&self, snapshot: Arc<TableSnapshot>) -> Result<DataBlock> { let len = snapshot.summary.block_count as usize; let snapshot_id = snapshot.snapshot_id.simple().to_string().into_bytes(); let timestamp = snapshot.timestamp.unwrap_or_default().timestamp_micros(); let mut block_location = StringColumnBuilder::with_capacity(len, len); let mut block_size = NumberColumnBuilder::with_capacity(&NumberDataType::UInt64, len); let mut file_size = NumberColumnBuilder::with_capacity(&NumberDataType::UInt64, len); let mut row_count = NumberColumnBuilder::with_capacity(&NumberDataType::UInt64, len); let mut bloom_filter_location = vec![]; let mut bloom_filter_size = NumberColumnBuilder::with_capacity(&NumberDataType::UInt64, len); let segments_io = SegmentsIO::create( self.ctx.clone(), self.table.operator.clone(), self.table.schema(), ); let segments = segments_io.read_segments(&snapshot.segments).await?; for segment in segments { let segment = segment?; segment.blocks.iter().for_each(|block| { let block = block.as_ref(); block_location.put_slice(block.location.0.as_bytes()); block_location.commit_row(); block_size.push(NumberScalar::UInt64(block.block_size)); file_size.push(NumberScalar::UInt64(block.file_size)); row_count.push(NumberScalar::UInt64(block.row_count)); bloom_filter_location.push( block .bloom_filter_index_location .as_ref() .map(|s| s.0.as_bytes().to_vec()), ); bloom_filter_size.push(NumberScalar::UInt64(block.bloom_filter_index_size)); }); } Ok(DataBlock::new( vec![ BlockEntry { data_type: DataType::String, value: Value::Scalar(Scalar::String(snapshot_id.to_vec())), }, BlockEntry { data_type: DataType::Nullable(Box::new(DataType::Timestamp)), value: Value::Scalar(Scalar::Timestamp(timestamp)), }, BlockEntry { data_type: DataType::String, value: Value::Column(Column::String(block_location.build())), }, BlockEntry { data_type: DataType::Number(NumberDataType::UInt64), value: Value::Column(Column::Number(block_size.build())), }, BlockEntry { data_type: DataType::Number(NumberDataType::UInt64), value: Value::Column(Column::Number(file_size.build())), }, BlockEntry { data_type: DataType::Number(NumberDataType::UInt64), value: Value::Column(Column::Number(row_count.build())), }, BlockEntry { data_type: DataType::String.wrap_nullable(), value: Value::Column(StringType::from_opt_data(bloom_filter_location)), }, BlockEntry { data_type: DataType::Number(NumberDataType::UInt64), value: Value::Column(Column::Number(bloom_filter_size.build())), }, ], len, )) } pub fn schema() -> Arc<TableSchema> { TableSchemaRefExt::create(vec![ TableField::new("snapshot_id", TableDataType::String), TableField::new("timestamp", TableDataType::Timestamp.wrap_nullable()), TableField::new("block_location", TableDataType::String), TableField::new("block_size", TableDataType::Number(NumberDataType::UInt64)), TableField::new("file_size", TableDataType::Number(NumberDataType::UInt64)), TableField::new("row_count", TableDataType::Number(NumberDataType::UInt64)), TableField::new( "bloom_filter_location", TableDataType::String.wrap_nullable(), ), TableField::new( "bloom_filter_size", TableDataType::Number(NumberDataType::UInt64), ), ]) } }
mod managed_program; pub use managed_program::*; mod program_asset_schema; pub use program_asset_schema::*;
//! Convenient utility methods, mostly for printing `syntect` data structures //! prettily to the terminal. use highlighting::Style; use std::fmt::Write; #[cfg(feature = "parsing")] use parsing::ScopeStackOp; /// Formats the styled fragments using 24-bit colour /// terminal escape codes. Meant for debugging and testing. /// It's currently fairly inefficient in its use of escape codes. /// /// Note that this does not currently ever un-set the colour so that /// the end of a line will also get highlighted with the background. /// This means if you might want to use `println!("\x1b[0m");` after /// to clear the colouring. /// /// If `bg` is true then the background is also set pub fn as_24_bit_terminal_escaped(v: &[(Style, &str)], bg: bool) -> String { let mut s: String = String::new(); for &(ref style, text) in v.iter() { if bg { write!(s, "\x1b[48;2;{};{};{}m", style.background.r, style.background.g, style.background.b) .unwrap(); } write!(s, "\x1b[38;2;{};{};{}m{}", style.foreground.r, style.foreground.g, style.foreground.b, text) .unwrap(); } // s.push_str("\x1b[0m"); s } /// Print out the various push and pop operations in a vector /// with visual alignment to the line. Obviously for debugging. #[cfg(feature = "parsing")] pub fn debug_print_ops(line: &str, ops: &[(usize, ScopeStackOp)]) { for &(i, ref op) in ops.iter() { println!("{}", line.trim_right()); print!("{: <1$}", "", i); match *op { ScopeStackOp::Push(s) => { println!("^ +{}", s); } ScopeStackOp::Pop(count) => { println!("^ pop {}", count); } ScopeStackOp::Clear(amount) => { println!("^ clear {:?}", amount); } ScopeStackOp::Restore => println!("^ restore"), ScopeStackOp::Noop => println!("noop"), } } }
use druid::kurbo::{BezPath}; use druid::piet::{FontFamily, FontStyle, ImageFormat, InterpolationMode}; use druid::kurbo; use druid::widget::prelude::*; use druid::{ Affine, AppLauncher, ArcStr, Color, Data, FontDescriptor, LocalizedString, MouseEvent, Point as DruidPoint, TextLayout, WindowDesc, }; use klein::{ApplyTo, Plane, Point, Rotor}; #[derive(Default)] struct CustomWidget { lower_y: f64, upper_y: f64, left_x: f64, right_x: f64, lower_plane: Plane, upper_plane: Plane, left_plane: Plane, right_plane: Plane, //center_point: Rc<PGA3D>, center_point: Point, left: f64, top: f64, scale: f64, window_pixels: kurbo::Size, } impl CustomWidget { fn to_druid_point(&self, p: &Point) -> DruidPoint { let pn = p; //.normalized(); DruidPoint::new( (pn.x() as f64 - self.left) / self.scale, (self.top - pn.y() as f64) / self.scale, ) } fn new() -> CustomWidget { CustomWidget { lower_y: -2., upper_y: 2., left_x: -2., right_x: 2., ..Default::default() } } pub fn set_window_boundary_planes(&mut self, _state: &State, window: &kurbo::Size) { let desired_width = self.right_x - self.left_x; let desired_height = self.upper_y - self.lower_y; let desired_aspect_ratio = desired_width / desired_height; let center_x = (self.right_x + self.left_x) / 2.; let center_y = (self.upper_y + self.lower_y) / 2.; self.window_pixels = *window; let window_aspect_ratio = window.width / window.height; self.top = self.upper_y; self.left = self.left_x; let mut right = self.right_x; let mut bottom = self.lower_y; if window_aspect_ratio > desired_aspect_ratio { // actual window is wider than desired viewport self.scale = desired_height / window.height; let half_width = self.scale * 0.5 * window.width; right = center_x + half_width; self.left = center_x - half_width; } else { // actual window is taller than desired viewport self.scale = desired_width / window.width; let half_height = self.scale * 0.5 * window.height; self.top = center_y + half_height; bottom = center_y - half_height; } self.lower_plane = Plane::new(0., 1., 0., bottom as f32); self.upper_plane = Plane::new(0., 1., 0., self.top as f32); self.left_plane = Plane::new(1., 0., 0., self.left as f32); self.right_plane = Plane::new(1., 0., 0., right as f32); self.center_point = Point::new(center_x as f32, center_y as f32, 0.); } pub fn mouse_move(&self, mouse: &MouseEvent, data: &mut State) { let x_portion = mouse.pos.x / self.window_pixels.width; let x_coord = self.left_plane.x() * self.left_plane.d() * (1. - x_portion as f32) + (self.right_plane.x() * self.right_plane.d()) * x_portion as f32; let y_portion = mouse.pos.y / self.window_pixels.height; let y_coord = self.upper_plane.y() * self.upper_plane.d() * (1. - y_portion as f32) + self.lower_plane.y() * self.lower_plane.d() * y_portion as f32; // let mouse_point = (x_plane^y_plane.normalized()^PGA3D::e3()); // let mouse_y = mouse.pos.y; // let y_plane = let mouse = Point::new(x_coord, y_coord, 0.); data.mouse_over = None; for (i, p) in data.points.iter().enumerate() { // println!("mouse point {} {}",i, (mouse & *p).norm()); if (mouse & *p).norm() < 0.07 { println!("over point {}", i); data.mouse_over = Some(i); } } // println!("mosue pos {} {}",mouse_point.get032(), mouse_point.get013()) } } use std::rc::Rc; #[derive(Clone, Data, Default)] struct State { points: Rc<Vec<Point>>, mouse_over: Option<usize>, mesh: Rc<Vec<Point>>, indices: Rc<Vec<Vec<usize>>>, time: f64, } impl Widget<State> for CustomWidget { fn event(&mut self, ctx: &mut EventCtx, event: &Event, data: &mut State, _env: &Env) { match event { Event::WindowConnected => { ctx.request_focus(); ctx.request_anim_frame(); } Event::KeyDown(e) => { println!("key down event {:?}", e); } Event::MouseMove(e) => { let old = data.mouse_over; self.mouse_move(e, data); if data.mouse_over != old { ctx.request_paint(); } } Event::AnimFrame(_interval) => { data.time += 0.01; ctx.request_paint(); ctx.request_anim_frame(); } _ => { println!("unhandled input event {:?}", event); } } } fn lifecycle(&mut self, ctx: &mut LifeCycleCtx, event: &LifeCycle, data: &State, _env: &Env) { match event { LifeCycle::Size(s) => { self.set_window_boundary_planes(data, s); } LifeCycle::WidgetAdded => { ctx.register_for_focus(); } _ => println!("unhandled lifecycle event: {:?}", event), } } fn update(&mut self, _ctx: &mut UpdateCtx, _old_data: &State, _data: &State, _env: &Env) { // println!("update event: {}", ); } fn layout( &mut self, _layout_ctx: &mut LayoutCtx, bc: &BoxConstraints, _data: &State, _env: &Env, ) -> Size { // BoxConstraints are passed by the parent widget. // This method can return any Size within those constraints: // bc.constrain(my_size) // // To check if a dimension is infinite or not (e.g. scrolling): // bc.is_width_bounded() / bc.is_height_bounded() bc.max() } // The paint method gets called last, after an event flow. // It goes event -> update -> layout -> paint, and each method can influence the next. // Basically, anything that changes the appearance of a widget causes a paint. fn paint(&mut self, ctx: &mut PaintCtx, data: &State, env: &Env) { // Let's draw a picture with Piet! // Clear the whole widget with the color of your choice // (ctx.size() returns the size of the layout rect we're painting in) let size = ctx.size(); let rect = size.to_rect(); ctx.fill(rect, &Color::BLACK); // // for p in (&data.points).borrow().iter() { // for p in (&data.points).iter() { // println!("label: {}", p.label); // } // Note: ctx also has a `clear` method, but that clears the whole context, // and we only want to clear this widget's area. let fill_color = Color::rgba8(0xa3, 0xa3, 0xa3, 0xFF); let r = Rotor::rotor(data.time as f32, 1., -1., 0.5); for p in data.indices.iter() { let mut path = BezPath::new(); path.move_to(self.to_druid_point(&r.apply_to(data.mesh[p[0]]))); path.line_to(self.to_druid_point(&r.apply_to(data.mesh[p[1]]))); path.line_to(self.to_druid_point(&r.apply_to(data.mesh[p[2]]))); path.line_to(self.to_druid_point(&r.apply_to(data.mesh[p[0]]))); let stroke_color = Color::rgb8(240, 240, 240); ctx.stroke(path, &stroke_color, 4.0); } // Text is easy; in real use TextLayout should be stored in the widget // and reused. let mut layout = TextLayout::<ArcStr>::from_text("klein rust"); //data.to_owned()); layout.set_font( FontDescriptor::new(FontFamily::SANS_SERIF) .with_size(24.0) //.with_weight(FontWeight::BOLD) .with_style(FontStyle::Italic), ); layout.set_text_color(fill_color); // layout.set_text_style(FontStyle::Italic); layout.rebuild_if_needed(ctx.text(), env); // Let's rotate our text slightly. First we save our current (default) context: ctx.with_save(|ctx| { // Now we can rotate the context (or set a clip path, for instance): ctx.transform(Affine::rotate(0.0)); layout.draw(ctx, (80.0, 40.0)); }); // Let's burn some CPU to make a (partially transparent) image buffer let image_data = make_image_data(256, 256); let image = ctx .make_image(256, 256, &image_data, ImageFormat::RgbaSeparate) .unwrap(); // The image is automatically scaled to fit the rect you pass to draw_image ctx.draw_image(&image, size.to_rect(), InterpolationMode::Bilinear); } } pub fn main() { let window = WindowDesc::new(|| CustomWidget::new()).title( LocalizedString::new("custom-widget-demo-window-title").with_placeholder("klein rust demo"), ); let mut s = State { ..Default::default() }; let ps = Rc::get_mut(&mut s.points).unwrap(); ps.push(Point::new(0., 0.6, 0.)); ps.push(Point::new(0.94, 0., 0.)); let y1 = Point::new(0., 1., 0.); let p1 = Rotor::rotor(f32::acos(-1. / 3.), 1., 0., 0.).apply_to(y1); let r = Rotor::rotor(f32::acos(-0.5), 0., 1., 0.); let p2 = r.apply_to(p1); let mesh = Rc::get_mut(&mut s.mesh).unwrap(); mesh.push(y1); mesh.push(p1); mesh.push(p2); mesh.push(r.apply_to(p2)); let indices = Rc::get_mut(&mut s.indices).unwrap(); indices.push(vec![0, 1, 2]); indices.push(vec![0, 2, 3]); indices.push(vec![0, 3, 1]); indices.push(vec![1, 3, 2]); AppLauncher::with_window(window) .use_simple_logger() .launch(s) // .launch("Druid + Piet".to_string()) .expect("launch failed"); } fn make_image_data(width: usize, height: usize) -> Vec<u8> { let mut result = vec![0; width * height * 4]; for y in 0..height { for x in 0..width { let ix = (y * width + x) * 4; result[ix] = x as u8; result[ix + 1] = y as u8; result[ix + 2] = !(x as u8); result[ix + 3] = 127; } } result }
pub mod lexer; pub mod parser; pub mod resolver; pub mod types;
use crate::spec::{RelroLevel, TargetOptions}; pub fn opts() -> TargetOptions { TargetOptions { os: "linux".into(), dynamic_linking: true, families: vec!["unix".into()], has_rpath: true, position_independent_executables: true, relro_level: RelroLevel::Full, has_thread_local: true, crt_static_respected: true, ..Default::default() } }
use std::convert::Infallible; use warp::Rejection; use warp::{hyper::StatusCode, reply::json, Filter, Reply}; use crate::{with_context, AppContext}; fn get_actor_id( context: AppContext, ) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone { warp::path!("actor" / u32) .and(warp::get()) .and(with_context(context)) .and_then(get_actor) } fn post_actor( context: AppContext, ) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone { warp::path!("actor") .and(warp::post()) .and(with_context(context)) .and_then(create_actor) } fn get_all_actors( context: AppContext, ) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone { warp::path!("actor") .and(warp::get()) .and(with_context(context)) .and_then(get_all) } fn trigger_actor(context: AppContext) -> impl Filter<Extract = impl warp::Reply, Error = warp::Rejection> + Clone { warp::path!("actor" / u32) .and(warp::post()) .and(with_context(context)) .and_then(trigger) } async fn get_actor(id: u32, context: AppContext) -> Result<Box<dyn Reply>, Infallible> { let state = context.lock().await; match state.get_actor(id) { Some(actor) => Ok(Box::new(json(actor))), None => Ok(Box::new(StatusCode::NOT_FOUND)), } } async fn create_actor(context: AppContext) -> Result<impl Reply, Infallible> { let mut state = context.lock().await; state.add_actor(); Ok(warp::reply::reply()) } async fn get_all(context: AppContext) -> Result<Box<dyn Reply>, Infallible> { let state = context.lock().await; let actors = json(&state.get_actors()); Ok(Box::new(actors)) } async fn trigger(id: u32, context: AppContext) -> Result<impl Reply, Infallible> { context.trigger_action(id).await; Ok(warp::reply::reply()) } pub fn routes(context: AppContext) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone { get_all_actors(context.clone()) .or(get_actor_id(context.clone())) .or(trigger_actor(context.clone())) .or(post_actor(context)) }
mod day_1; mod day_2; mod day_3; mod day_4; mod day_5; mod day_8; mod day_9; use day_1::{find_three_items_that_sum_2020, find_two_items_that_sum_2020}; use day_2::{number_of_valid_passwords, PolicyStrategy}; use day_3::{count_trees, tree_product}; use day_4::{count_valid_passports, CountType}; use day_9::{all_numbers_valid, encryption_weakness}; fn main() { println!("Day 1 part 1"); let day_1_input = day_1::load_input_file("day_1.txt").expect("Missing input file"); if let Some(numbers) = find_two_items_that_sum_2020(&day_1_input) { let answer = numbers.0 * numbers.1; println!("Answer is {}", answer) }; println!("Day 1 part 2"); if let Some(numbers) = find_three_items_that_sum_2020(&day_1_input) { let answer = numbers[0] * numbers[1] * numbers[2]; println!("Answer is {}", answer) }; println!("Day 2 part 1"); let day_2_input = day_2::load_input_file("day_2.txt").expect("Missing input file"); let answer = number_of_valid_passwords(&day_2_input, PolicyStrategy::MinMax); println!("Answer is {}", answer); println!("Day 2 part 2"); let answer = number_of_valid_passwords(&day_2_input, PolicyStrategy::Position); println!("Answer is {}", answer); println!("Day 3 part 1"); let day_3_input = day_3::load_input_file("day_3.txt").expect("Missing input file"); let answer = count_trees(&day_3_input, (3, 1)); println!("Answer is {}", answer); println!("Day 3 part 2"); let slopes = Vec::from([(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]); let answer = tree_product(&day_3_input, &slopes); println!("Answer is {}", answer); println!("Day 4 part 1"); let day_4_input = day_4::load_input_file("day_4.txt").expect("Missing input file"); let answer = count_valid_passports(&day_4_input, CountType::KeysOnly); println!("Answer is {}", answer); println!("Day 4 part 2"); let answer = count_valid_passports(&day_4_input, CountType::KeysAndValues); println!("Answer is {}", answer); println!("Day 9 part 1"); let day_9_input = day_9::load_input_file("day_9.txt").expect("Missing input file"); let answer_1 = all_numbers_valid(&day_9_input, 25); println!("Answer is {}", answer_1.1.unwrap()); println!("Day 9 part 2"); let answer_2 = encryption_weakness(&day_9_input, answer_1.1.unwrap()); println!("Answer is {}", answer_2.unwrap()); }
mod utils; fn main() { let data = utils::load_input("./data/day_3.txt").unwrap(); let lines: Vec<&str> = data.split("\n").collect(); let configs = [[1, 1], [3, 1], [5, 1], [7, 1], [1, 2]]; let mut answer: u32 = 1; for config in configs.iter() { answer *= slop(&lines, config[0], config[1]); } println!("Answer : {}", answer); } fn slop(lines: &Vec<&str>, right: usize, down: usize) -> u32 { let mut tree_count = 0; let mut line_index = down; // first line is ignored let mut index = right; loop { let line = match lines.get(line_index) { Some(x) => x, None => break, }; let spot = match line.chars().nth(index) { Some(x) => x, None => { let line_length = line.len(); if line_length == 0 { break; } index = index - line_length; continue; } }; if spot == '#' { tree_count += 1; } index += right; line_index += down; } println!("Right {}, Down {}, Tree {}", right, down, tree_count); tree_count }
//! Stream protocol implementation use std::{ io, marker::Unpin, pin::Pin, task::{Context, Poll}, }; use bytes::{Buf, BufMut, BytesMut}; use futures::ready; use tokio::io::{AsyncRead, AsyncWrite, ReadBuf}; use crate::crypto::v1::{Cipher, CipherKind}; // use super::BUFFER_SIZE; /// Reader wrapper that will decrypt data automatically pub struct DecryptedReader { cipher: Cipher, } impl DecryptedReader { pub fn new(method: CipherKind, key: &[u8], iv: &[u8]) -> DecryptedReader { let cipher = Cipher::new(method, key, iv); DecryptedReader { cipher } } /// Attempt to read decrypted data from reader pub fn poll_read_decrypted<R>( &mut self, ctx: &mut Context<'_>, r: &mut R, dst: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>> where R: AsyncRead + Unpin, { let filled = dst.filled().len(); ready!(Pin::new(r).poll_read(ctx, dst))?; // Decrypt inplace let m = &mut dst.filled_mut()[filled..]; if !m.is_empty() { assert_eq!(self.cipher.decrypt_packet(m), true); } Poll::Ready(Ok(())) } } enum EncryptWriteStep { Nothing, Writing, } /// Writer wrapper that will encrypt data automatically pub struct EncryptedWriter { cipher: Cipher, steps: EncryptWriteStep, buf: BytesMut, } impl EncryptedWriter { /// Creates a new EncryptedWriter pub fn new(method: CipherKind, key: &[u8], iv: &[u8]) -> EncryptedWriter { // iv should be sent with the first packet let mut buf = BytesMut::with_capacity(iv.len()); buf.put(iv); EncryptedWriter { cipher: Cipher::new(method, key, &iv), steps: EncryptWriteStep::Nothing, buf, } } pub fn poll_write_encrypted<W>(&mut self, ctx: &mut Context<'_>, w: &mut W, data: &[u8]) -> Poll<io::Result<usize>> where W: AsyncWrite + Unpin, { ready!(self.poll_write_all_encrypted(ctx, w, data))?; Poll::Ready(Ok(data.len())) } fn poll_write_all_encrypted<W>(&mut self, ctx: &mut Context<'_>, w: &mut W, data: &[u8]) -> Poll<io::Result<()>> where W: AsyncWrite + Unpin, { // FIXME: How about finalize? loop { match self.steps { EncryptWriteStep::Nothing => { let mut payload = data.to_vec(); self.cipher.encrypt_packet(&mut payload); self.buf.put_slice(&payload); self.steps = EncryptWriteStep::Writing; } EncryptWriteStep::Writing => { while self.buf.has_remaining() { let n = ready!(Pin::new(&mut *w).poll_write(ctx, self.buf.bytes()))?; self.buf.advance(n); if n == 0 { use std::io::ErrorKind; return Poll::Ready(Err(ErrorKind::UnexpectedEof.into())); } } self.steps = EncryptWriteStep::Nothing; return Poll::Ready(Ok(())); } } } } }
//! stat implementation for Redox, following http://pubs.opengroup.org/onlinepubs/7908799/xsh/sysstat.h.html #![no_std] extern crate platform; use platform::types::*; pub const S_IFMT: c_int = 00170000; pub const S_IFBLK: c_int = 0060000; pub const S_IFCHR: c_int = 0020000; pub const S_IFIFO: c_int = 0010000; pub const S_IFREG: c_int = 0100000; pub const S_IFDIR: c_int = 0040000; pub const S_IFLNK: c_int = 0120000; pub const S_IRWXU: c_int = 00700; pub const S_IRUSR: c_int = 00400; pub const S_IWUSR: c_int = 00200; pub const S_IXUSR: c_int = 00100; pub const S_IRWXG: c_int = 00070; pub const S_IRGRP: c_int = 00040; pub const S_IWGRP: c_int = 00020; pub const S_IXGRP: c_int = 00010; pub const S_IRWXO: c_int = 00007; pub const S_IROTH: c_int = 00004; pub const S_IWOTH: c_int = 00002; pub const S_IXOTH: c_int = 00001; pub const S_ISUID: c_int = 04000; pub const S_ISGID: c_int = 02000; pub const S_ISVTX: c_int = 01000; #[repr(C)] pub struct stat { pub st_dev: dev_t, pub st_ino: ino_t, pub st_nlink: nlink_t, pub st_mode: mode_t, pub st_uid: uid_t, pub st_gid: gid_t, pub st_rdev: dev_t, pub st_size: off_t, pub st_blksize: blksize_t, pub st_atim: time_t, pub st_mtim: time_t, pub st_ctim: time_t, pub st_blocks: blkcnt_t, } #[no_mangle] pub extern "C" fn chmod(path: *const c_char, mode: mode_t) -> c_int { platform::chmod(path, mode) } #[no_mangle] pub extern "C" fn fchmod(fildes: c_int, mode: mode_t) -> c_int { platform::fchmod(fildes, mode) } #[no_mangle] pub extern "C" fn fstat(fildes: c_int, buf: *mut platform::types::stat) -> c_int { platform::fstat(fildes, buf) } #[no_mangle] pub extern "C" fn lstat(path: *const c_char, buf: *mut platform::types::stat) -> c_int { platform::lstat(path, buf) } #[no_mangle] pub extern "C" fn mkdir(path: *const c_char, mode: mode_t) -> c_int { platform::mkdir(path, mode) } #[no_mangle] pub extern "C" fn mkfifo(path: *const c_char, mode: mode_t) -> c_int { platform::mkfifo(path, mode) } #[no_mangle] pub extern "C" fn mknod(path: *const c_char, mode: mode_t, dev: dev_t) -> c_int { unimplemented!(); } #[no_mangle] pub extern "C" fn stat(file: *const c_char, buf: *mut platform::types::stat) -> c_int { platform::stat(file, buf) } #[no_mangle] pub extern "C" fn umask(mask: mode_t) -> mode_t { unimplemented!(); } /* #[no_mangle] pub extern "C" fn func(args) -> c_int { unimplemented!(); } */
#[macro_use] extern crate fawkes_crypto; #[macro_use] extern crate fawkes_crypto_derive; #[macro_use] extern crate serde; pub mod circuit; pub mod native; pub mod constants; use crate::native::gen_test_data::gen_test_data; use crate::{ circuit::{CWithdrawPub, CWithdrawSec, c_withdraw}, native::{WithdrawPub, WithdrawSec, MixerParams} }; use typenum::{U16}; use pairing::bn256::{Fr}; use fawkes_crypto::native::poseidon::PoseidonParams; use lazy_static::lazy_static; lazy_static! { pub static ref MIXER_PARAMS: MixerParams<Fr> = MixerParams::<Fr> { hash: PoseidonParams::<Fr>::new(2, 8, 53), compress: PoseidonParams::<Fr>::new(3, 8, 53) }; } groth16_circuit_bindings!(cli, WithdrawPub<Fr>, CWithdrawPub, WithdrawSec<Fr, U16>, CWithdrawSec, MIXER_PARAMS, c_withdraw, gen_test_data); fn main() { cli::cli_main() }
// Copyright 2021 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::io::SeekFrom; use common_arrow::parquet::metadata::ThriftFileMetaData; use common_exception::ErrorCode; use common_exception::Result; use common_expression::TableSchemaRef; use futures::AsyncRead; use futures::AsyncSeek; use futures_util::AsyncReadExt; use futures_util::AsyncSeekExt; use opendal::Operator; use opendal::Reader; use storages_common_cache::InMemoryItemCacheReader; use storages_common_cache::LoadParams; use storages_common_cache::Loader; use storages_common_cache_manager::CacheManager; use storages_common_index::BloomIndexMeta; use storages_common_table_meta::meta::SegmentInfo; use storages_common_table_meta::meta::SegmentInfoVersion; use storages_common_table_meta::meta::SnapshotVersion; use storages_common_table_meta::meta::TableSnapshot; use storages_common_table_meta::meta::TableSnapshotStatistics; use storages_common_table_meta::meta::TableSnapshotStatisticsVersion; use super::versioned_reader::VersionedReader; use crate::io::read::meta::meta_readers::thrift_file_meta_read::read_thrift_file_metadata; pub type TableSnapshotStatisticsReader = InMemoryItemCacheReader<TableSnapshotStatistics, LoaderWrapper<Operator>>; pub type BloomIndexMetaReader = InMemoryItemCacheReader<BloomIndexMeta, LoaderWrapper<Operator>>; pub type TableSnapshotReader = InMemoryItemCacheReader<TableSnapshot, LoaderWrapper<Operator>>; pub type SegmentInfoReader = InMemoryItemCacheReader<SegmentInfo, LoaderWrapper<(Operator, TableSchemaRef)>>; pub struct MetaReaders; impl MetaReaders { pub fn segment_info_reader(dal: Operator, schema: TableSchemaRef) -> SegmentInfoReader { SegmentInfoReader::new( CacheManager::instance().get_table_segment_cache(), LoaderWrapper((dal, schema)), ) } pub fn table_snapshot_reader(dal: Operator) -> TableSnapshotReader { TableSnapshotReader::new( CacheManager::instance().get_table_snapshot_cache(), LoaderWrapper(dal), ) } pub fn table_snapshot_statistics_reader(dal: Operator) -> TableSnapshotStatisticsReader { TableSnapshotStatisticsReader::new( CacheManager::instance().get_table_snapshot_statistics_cache(), LoaderWrapper(dal), ) } pub fn bloom_index_meta_reader(dal: Operator) -> BloomIndexMetaReader { BloomIndexMetaReader::new( CacheManager::instance().get_bloom_index_meta_cache(), LoaderWrapper(dal), ) } } // workaround for the orphan rules // Loader and types of table meta data are all defined outside (of this crate) pub struct LoaderWrapper<T>(T); #[async_trait::async_trait] impl Loader<TableSnapshot> for LoaderWrapper<Operator> { async fn load(&self, params: &LoadParams) -> Result<TableSnapshot> { let reader = bytes_reader(&self.0, params.location.as_str(), params.len_hint).await?; let version = SnapshotVersion::try_from(params.ver)?; version.read(reader).await } } #[async_trait::async_trait] impl Loader<TableSnapshotStatistics> for LoaderWrapper<Operator> { async fn load(&self, params: &LoadParams) -> Result<TableSnapshotStatistics> { let version = TableSnapshotStatisticsVersion::try_from(params.ver)?; let reader = bytes_reader(&self.0, params.location.as_str(), params.len_hint).await?; version.read(reader).await } } #[async_trait::async_trait] impl Loader<SegmentInfo> for LoaderWrapper<(Operator, TableSchemaRef)> { async fn load(&self, params: &LoadParams) -> Result<SegmentInfo> { let version = SegmentInfoVersion::try_from(params.ver)?; let LoaderWrapper((operator, schema)) = &self; let reader = bytes_reader(operator, params.location.as_str(), params.len_hint).await?; (version, schema.clone()).read(reader).await } } #[async_trait::async_trait] impl Loader<BloomIndexMeta> for LoaderWrapper<Operator> { async fn load(&self, params: &LoadParams) -> Result<BloomIndexMeta> { let mut reader = bytes_reader(&self.0, params.location.as_str(), params.len_hint).await?; // read the ThriftFileMetaData, omit unnecessary conversions let meta = read_thrift_file_metadata(&mut reader) .await .map_err(|err| { ErrorCode::StorageOther(format!( "read file meta failed, {}, {:?}", params.location, err )) })?; BloomIndexMeta::try_from(meta) } } async fn bytes_reader(op: &Operator, path: &str, len_hint: Option<u64>) -> Result<Reader> { let reader = if let Some(len) = len_hint { op.range_reader(path, 0..len).await? } else { op.reader(path).await? }; Ok(reader) } mod thrift_file_meta_read { use common_arrow::parquet::error::Error; use parquet_format_safe::thrift::protocol::TCompactInputProtocol; use super::*; // the following code is copied from crate `parquet2`, with slight modification: // return a ThriftFileMetaData instead of FileMetaData while reading parquet metadata, // to avoid unnecessary conversions. const HEADER_SIZE: u64 = PARQUET_MAGIC.len() as u64; const FOOTER_SIZE: u64 = 8; const PARQUET_MAGIC: [u8; 4] = [b'P', b'A', b'R', b'1']; /// The number of bytes read at the end of the parquet file on first read const DEFAULT_FOOTER_READ_SIZE: u64 = 64 * 1024; async fn stream_len( seek: &mut (impl AsyncSeek + std::marker::Unpin), ) -> std::result::Result<u64, std::io::Error> { let old_pos = seek.seek(SeekFrom::Current(0)).await?; let len = seek.seek(SeekFrom::End(0)).await?; // Avoid seeking a third time when we were already at the end of the // stream. The branch is usually way cheaper than a seek operation. if old_pos != len { seek.seek(SeekFrom::Start(old_pos)).await?; } Ok(len) } fn metadata_len(buffer: &[u8], len: usize) -> i32 { i32::from_le_bytes(buffer[len - 8..len - 4].try_into().unwrap()) } pub async fn read_thrift_file_metadata<R: AsyncRead + AsyncSeek + Send + std::marker::Unpin>( reader: &mut R, ) -> common_arrow::parquet::error::Result<ThriftFileMetaData> { let file_size = stream_len(reader).await?; if file_size < HEADER_SIZE + FOOTER_SIZE { return Err(Error::OutOfSpec( "A parquet file must contain a header and footer with at least 12 bytes".into(), )); } // read and cache up to DEFAULT_FOOTER_READ_SIZE bytes from the end and process the footer let default_end_len = std::cmp::min(DEFAULT_FOOTER_READ_SIZE, file_size) as usize; reader .seek(SeekFrom::End(-(default_end_len as i64))) .await?; let mut buffer = vec![]; buffer.try_reserve(default_end_len)?; reader .take(default_end_len as u64) .read_to_end(&mut buffer) .await?; // check this is indeed a parquet file if buffer[default_end_len - 4..] != PARQUET_MAGIC { return Err(Error::OutOfSpec( "Invalid Parquet file. Corrupt footer".into(), )); } let metadata_len = metadata_len(&buffer, default_end_len); let metadata_len: u64 = metadata_len.try_into()?; let footer_len = FOOTER_SIZE + metadata_len; if footer_len > file_size { return Err(Error::OutOfSpec( "The footer size must be smaller or equal to the file's size".into(), )); } let reader = if (footer_len as usize) < buffer.len() { // the whole metadata is in the bytes we already read let remaining = buffer.len() - footer_len as usize; &buffer[remaining..] } else { // the end of file read by default is not long enough, read again including the metadata. reader.seek(SeekFrom::End(-(footer_len as i64))).await?; buffer.clear(); buffer.try_reserve(footer_len as usize)?; reader.take(footer_len).read_to_end(&mut buffer).await?; &buffer }; // a highly nested but sparse struct could result in many allocations let max_size = reader.len() * 2 + 1024; let mut prot = TCompactInputProtocol::new(reader, max_size); let meta = ThriftFileMetaData::read_from_in_protocol(&mut prot)?; Ok(meta) } }
fn main() { let a = "a".parse::<i32>(); match a { Ok(val) => println!("{:?}", val), Err(e) => println!("{:#?}", e), } //println!("{:?}", a); }
use super::schema::NewsSourceType; use super::schema::news; #[derive(Queryable, Debug, Clone)] pub struct SourceAtom { pub id: i32, pub url: Option<String>, pub display_name: Option<String>, pub color: Option<String>, } #[derive(Queryable, Debug, Clone)] pub struct SourceRss { pub id: i32, pub url: Option<String>, pub display_name: Option<String>, pub color: Option<String>, } #[derive(Debug)] pub struct SourceHttp { pub url: Option<String>, pub display_name: Option<String>, pub color: Option<String>, pub news_source_type: NewsSourceType, pub news_source_id: i32 } impl From<SourceAtom> for SourceHttp { fn from(item: SourceAtom) -> Self { SourceHttp { url: item.url, display_name: item.display_name, color: item.color, news_source_type: NewsSourceType::Atom, news_source_id: item.id, } } } impl From<SourceRss> for SourceHttp { fn from(item: SourceRss) -> Self { SourceHttp { url: item.url, display_name: item.display_name, color: item.color, news_source_type: NewsSourceType::Rss, news_source_id: item.id, } } } #[derive(Queryable, Debug)] pub struct News { pub id: Option<i32>, pub guid: Option<String>, pub news_source_type: Option<NewsSourceType>, pub news_source_id: Option<i32>, pub insert_date: Option<chrono::NaiveDateTime>, pub title: Option<i32>, pub content: Option<String>, pub link: Option<String>, pub color: Option<String>, } #[derive(Insertable)] #[table_name="news"] pub struct NewNews <'a>{ pub guid: &'a str, pub source_type: &'a NewsSourceType, pub source_id: &'a i32, pub insert_date: &'a chrono::NaiveDateTime, pub title: &'a str, pub content: &'a str, pub link: &'a str, pub color: &'a str, }
use std::io; use std::path; use std::fs; pub fn create_cache_dir(cache_config: &super::CacheDirConfig) -> io::Result<path::PathBuf> { use std::error::Error; let default_config = !cache_config.app_cache && !cache_config.user_cache && !cache_config.sys_cache && !cache_config.tmp_cache && !cache_config.mem_cache; let user_cache = if default_config { true } else { cache_config.user_cache }; let mut last_io_error = io::ErrorKind::NotFound; let mut errors_buffer = String::new(); if cache_config.app_cache && cache_config.app_cache_path.is_some() { match CacheDirImpl::create_app_cache_dir(&cache_config.cache_name, &cache_config.app_cache_path.unwrap()) { Ok(result) => return Ok(result), Err(err) => { last_io_error = err.kind(); errors_buffer.push_str(err.description()); } } } if user_cache { match CacheDirImpl::create_user_cache_dir(&cache_config.cache_name) { Ok(result) => return Ok(result), Err(err) => { last_io_error = err.kind(); errors_buffer.push_str(err.description()); } } } if cache_config.sys_cache { match CacheDirImpl::create_system_cache_dir(&cache_config.cache_name) { Ok(result) => return Ok(result), Err(err) => { last_io_error = err.kind(); errors_buffer.push_str(err.description()); } } } if cache_config.tmp_cache { match CacheDirImpl::create_tmp_cache_dir(&cache_config.cache_name) { Ok(result) => return Ok(result), Err(err) => { last_io_error = err.kind(); errors_buffer.push_str(err.description()); } } } if cache_config.mem_cache { match CacheDirImpl::create_memory_cache_dir(&cache_config.cache_name) { Ok(result) => return Ok(result), Err(err) => { last_io_error = err.kind(); errors_buffer.push_str(err.description()); } } } Err(io::Error::new(last_io_error, errors_buffer)) } // ===== Private ===== #[cfg(unix)] #[path = "unix_cache.rs"] mod cache_impl; #[cfg(windows)] #[path = "windows_cache.rs"] mod cache_impl; #[cfg(target_os = "redox")] #[path = "redox_cache.rs"] mod cache_impl; #[cfg(not(any(unix, windows, target_os = "redox")))] #[path = "unknown_os_cache.rs"] mod cache_impl; // All os-specific modules implement `CacheDirOperations` on the `CacheDirImpl` structure struct CacheDirImpl; // The functions that should be implemented by all os-specific modules trait CacheDirOperations { fn create_app_cache_dir(cache_name: &path::Path, app_cache_dir: &path::Path) -> io::Result<path::PathBuf>; fn create_user_cache_dir(cache_name: &path::Path) -> io::Result<path::PathBuf>; fn create_system_cache_dir(cache_name: &path::Path) -> io::Result<path::PathBuf>; fn create_tmp_cache_dir(cache_name: &path::Path) -> io::Result<path::PathBuf>; fn create_memory_cache_dir(cache_name: &path::Path) -> io::Result<path::PathBuf>; } // Common function shared between all implementations of the CacheDirOperations trait fn create_dir_helper(dirs: &[path::PathBuf], path: &path::Path) -> io::Result<path::PathBuf> { // Sadly, we don't have something like `static_assert` debug_assert!(!dirs.is_empty(), "Code-logic error: the slice of directories should not be empty"); if dirs.is_empty() { return Err(io::Error::new(io::ErrorKind::NotFound, "Could not create the cache directory")); } // This is a buffer of all the errors(attempts) to create a cache directory. // The `PermissionDenied` error will be returned with this buffer only if all the attempts fail let mut attempted_paths_error = String::new(); let mut last_io_error = io::ErrorKind::NotFound; for parent_cache_dir in dirs { if !parent_cache_dir.exists() { last_io_error = io::ErrorKind::NotFound; attempted_paths_error.push_str( &format!("\n[NotFound]: Parent cache directory does not exist: {}", parent_cache_dir.display())); } else { if !parent_cache_dir.is_dir() { last_io_error = io::ErrorKind::AlreadyExists; attempted_paths_error.push_str( &format!("\n[AlreadyExists]: Parent cache path is not a directory: {}", parent_cache_dir.display()) ); } else { let final_cache_path = &parent_cache_dir.join(path); if let Err(err) = fs::create_dir_all(&final_cache_path) { last_io_error = err.kind(); attempted_paths_error.push_str( &format!("\n[{:?}]: Failed to create the cache directory: {}", err.kind(), final_cache_path.display())); } else { return Ok(path::PathBuf::from(final_cache_path)); } } } } Err(io::Error::new(last_io_error, attempted_paths_error)) } // Making sure that the `CacheDirOperations` trait was implemented on `CacheDirImpl` mod testing { #![allow(dead_code)] use super::{ CacheDirImpl, CacheDirOperations }; fn is_trait_implemented<T: CacheDirOperations>(_cache_dir_impl: T) {} fn assert_trait_impl() { is_trait_implemented(CacheDirImpl); } }
#![cfg_attr(not(feature = "std"), no_std)] use ink_env::Environment; use ink_lang as ink; use ink_prelude::vec::Vec; pub use contract_types::*; pub type Quantity = u64; pub type ClassId = u32; pub type TokenId = u64; pub type Metadata = Vec<u8>; pub type Chars = Vec<u8>; pub type Balance = <ink_env::DefaultEnvironment as Environment>::Balance; pub type BlockNumber = <ink_env::DefaultEnvironment as Environment>::BlockNumber; #[derive(Debug, Copy, Clone, PartialEq, Eq, scale::Encode, scale::Decode)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum NFTMartErr { Fail, } impl ink_env::chain_extension::FromStatusCode for NFTMartErr { fn from_status_code(status_code: u32) -> Result<(), Self> { match status_code { 0 => Ok(()), 1 => Err(Self::Fail), _ => panic!("encountered unknown status code"), } } } #[derive(Debug, Clone, PartialEq, Eq)] #[cfg_attr(feature = "std", derive(scale_info::TypeInfo))] pub enum CustomEnvironment {} impl Environment for CustomEnvironment { const MAX_EVENT_TOPICS: usize = <ink_env::DefaultEnvironment as Environment>::MAX_EVENT_TOPICS; type AccountId = <ink_env::DefaultEnvironment as Environment>::AccountId; type Balance = <ink_env::DefaultEnvironment as Environment>::Balance; type Hash = <ink_env::DefaultEnvironment as Environment>::Hash; type BlockNumber = <ink_env::DefaultEnvironment as Environment>::BlockNumber; type Timestamp = <ink_env::DefaultEnvironment as Environment>::Timestamp; type ChainExtension = NFTMart; type RentFraction=<ink_env::DefaultEnvironment as Environment>::RentFraction; } #[ink::chain_extension] pub trait NFTMart { type ErrorCode = NFTMartErr; /// Runtime generates a random number, which is based on the latest 81 block hash value, which can be used in some low-security occasions. #[ink(extension = 2001, returns_result = false)] fn fetch_random() -> [u8; 32]; /// Create an NFT portfolio, which is a collection used by creators to distinguish different NFT works /// metadata: metadata of the class /// name: the name of the class /// description: description of the class /// properties: properties of the class #[ink(extension = 2022, returns_result = false)] fn create_class(metadata: Metadata, name: Chars, description: Chars, properties: u8) -> (ink_env::AccountId, ClassId); /// Create an NFT /// to: Who is the created work for? /// class_id: The class to which the work belongs /// metadata: metadata of the work /// quantity: How many works are created with the same data? /// charg_royalty: Whether to charge royalties #[ink(extension = 2003, returns_result = false)] fn proxy_mint( to: &ink_env::AccountId, class_id: ClassId, metadata: Metadata, quantity: Quantity, charge_royalty: Option<bool>, ) -> (ink_env::AccountId, ink_env::AccountId, ClassId, TokenId, Quantity); /// Transfer NFT to another account /// to: The target account of the transfer /// class_id: the class of the transferred NFT /// token_id: The ID of the NFT being transferred /// quantity: the number of transfers #[ink(extension = 2004, returns_result = false)] fn transfer(to: &ink_env::AccountId, class_id: ClassId, token_id: TokenId, quantity: Quantity) -> (); /// Return the information of the specified NFT, including the holder /// class_id: the class of the queried NFT /// token_id: the id of the NFT being queried #[ink(extension = 1001, handle_status = false, returns_result = false)] fn tokens(class_id: ClassId, token_id: TokenId) -> Option<ContractTokenInfo< Metadata, Quantity, Balance, BlockNumber, ink_env::AccountId, >>; }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::sync::Arc; use spin::Mutex; use alloc::vec::Vec; use alloc::collections::btree_map::BTreeMap; use alloc::string::ToString; use super::super::super::qlib::common::*; use super::super::super::qlib::linux_def::*; use super::super::super::qlib::auth::*; use super::super::super::kernel::kernel::*; use super::super::super::task::*; use super::super::fsutil::file::readonly_file::*; use super::super::fsutil::inode::simple_file_inode::*; use super::super::file::*; use super::super::flags::*; use super::super::dirent::*; use super::super::mount::*; use super::super::inode::*; use super::sys::*; pub fn NewPossible(task: &Task, msrc: &Arc<Mutex<MountSource>>) -> Inode { let v = NewPossibleSimpleFileInode(task, &ROOT_OWNER, &FilePermissions::FromMode(FileMode(0o400)), FSMagic::PROC_SUPER_MAGIC); return NewFile(&Arc::new(v), msrc) } pub fn NewPossibleSimpleFileInode(task: &Task, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> SimpleFileInode<PossibleData> { let fs = PossibleData{}; return SimpleFileInode::New(task, owner, perms, typ, false, fs) } pub struct PossibleData { } impl PossibleData { pub fn GenSnapshot(&self, _task: &Task) -> Vec<u8> { let kernel = GetKernel(); let maxCore = kernel.applicationCores - 1; let ret = format!("0-{}\n", maxCore); return ret.as_bytes().to_vec(); } } impl SimpleFileTrait for PossibleData { fn GetFile(&self, task: &Task, _dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { let fops = NewSnapshotReadonlyFileOperations(self.GenSnapshot(task)); let file = File::New(dirent, &flags, fops); return Ok(file); } } pub fn NewCPU(task: &Task, msrc: &Arc<Mutex<MountSource>>) -> Inode { let mut m = BTreeMap::new(); m.insert("online".to_string(), NewPossible(task, msrc)); m.insert("possible".to_string(), NewPossible(task, msrc)); m.insert("present".to_string(), NewPossible(task, msrc)); let kernel = GetKernel(); let cores = kernel.applicationCores; for i in 0..cores { let name = format!("cpu{}", i); m.insert(name, NewDir(task, msrc, BTreeMap::new())); } return NewDir(task, msrc, m) } pub fn NewSystemDir(task: &Task, msrc: &Arc<Mutex<MountSource>>) -> Inode { let mut m = BTreeMap::new(); m.insert("cpu".to_string(), NewCPU(task, msrc)); //m.insert("node".to_string(), NewCPU(task, msrc)); return NewDir(task, msrc, m) } pub fn NewDevicesDir(task: &Task, msrc: &Arc<Mutex<MountSource>>) -> Inode { let mut m = BTreeMap::new(); m.insert("system".to_string(), NewSystemDir(task, msrc)); return NewDir(task, msrc, m) }
// auto generated, do not modify. // created: Wed Jan 20 00:44:03 2016 // src-file: /QtNetwork/qsslcipher.h // dst-file: /src/network/qsslcipher.rs // // header block begin => #![feature(libc)] #![feature(core)] #![feature(collections)] extern crate libc; use self::libc::*; // <= header block end // main block begin => // <= main block end // use block begin => use std::ops::Deref; use super::super::core::qstring::QString; // 771 // <= use block end // ext block begin => // #[link(name = "Qt5Core")] // #[link(name = "Qt5Gui")] // #[link(name = "Qt5Widgets")] // #[link(name = "QtInline")] extern { fn QSslCipher_Class_Size() -> c_int; // proto: QString QSslCipher::name(); fn _ZNK10QSslCipher4nameEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QSslCipher::~QSslCipher(); fn _ZN10QSslCipherD2Ev(qthis: u64 /* *mut c_void*/); // proto: void QSslCipher::QSslCipher(); fn _ZN10QSslCipherC2Ev(qthis: u64 /* *mut c_void*/); // proto: void QSslCipher::QSslCipher(const QString & name); fn _ZN10QSslCipherC2ERK7QString(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QString QSslCipher::protocolString(); fn _ZNK10QSslCipher14protocolStringEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: int QSslCipher::supportedBits(); fn _ZNK10QSslCipher13supportedBitsEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: int QSslCipher::usedBits(); fn _ZNK10QSslCipher8usedBitsEv(qthis: u64 /* *mut c_void*/) -> c_int; // proto: void QSslCipher::swap(QSslCipher & other); fn _ZN10QSslCipher4swapERS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QString QSslCipher::keyExchangeMethod(); fn _ZNK10QSslCipher17keyExchangeMethodEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: void QSslCipher::QSslCipher(const QSslCipher & other); fn _ZN10QSslCipherC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void); // proto: QString QSslCipher::authenticationMethod(); fn _ZNK10QSslCipher20authenticationMethodEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; // proto: bool QSslCipher::isNull(); fn _ZNK10QSslCipher6isNullEv(qthis: u64 /* *mut c_void*/) -> c_char; // proto: QString QSslCipher::encryptionMethod(); fn _ZNK10QSslCipher16encryptionMethodEv(qthis: u64 /* *mut c_void*/) -> *mut c_void; } // <= ext block end // body block begin => // class sizeof(QSslCipher)=1 #[derive(Default)] pub struct QSslCipher { // qbase: None, pub qclsinst: u64 /* *mut c_void*/, } impl /*struct*/ QSslCipher { pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QSslCipher { return QSslCipher{qclsinst: qthis, ..Default::default()}; } } // proto: QString QSslCipher::name(); impl /*struct*/ QSslCipher { pub fn name<RetType, T: QSslCipher_name<RetType>>(& self, overload_args: T) -> RetType { return overload_args.name(self); // return 1; } } pub trait QSslCipher_name<RetType> { fn name(self , rsthis: & QSslCipher) -> RetType; } // proto: QString QSslCipher::name(); impl<'a> /*trait*/ QSslCipher_name<QString> for () { fn name(self , rsthis: & QSslCipher) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QSslCipher4nameEv()}; let mut ret = unsafe {_ZNK10QSslCipher4nameEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QSslCipher::~QSslCipher(); impl /*struct*/ QSslCipher { pub fn free<RetType, T: QSslCipher_free<RetType>>(& self, overload_args: T) -> RetType { return overload_args.free(self); // return 1; } } pub trait QSslCipher_free<RetType> { fn free(self , rsthis: & QSslCipher) -> RetType; } // proto: void QSslCipher::~QSslCipher(); impl<'a> /*trait*/ QSslCipher_free<()> for () { fn free(self , rsthis: & QSslCipher) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QSslCipherD2Ev()}; unsafe {_ZN10QSslCipherD2Ev(rsthis.qclsinst)}; // return 1; } } // proto: void QSslCipher::QSslCipher(); impl /*struct*/ QSslCipher { pub fn new<T: QSslCipher_new>(value: T) -> QSslCipher { let rsthis = value.new(); return rsthis; // return 1; } } pub trait QSslCipher_new { fn new(self) -> QSslCipher; } // proto: void QSslCipher::QSslCipher(); impl<'a> /*trait*/ QSslCipher_new for () { fn new(self) -> QSslCipher { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QSslCipherC2Ev()}; let ctysz: c_int = unsafe{QSslCipher_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; unsafe {_ZN10QSslCipherC2Ev(qthis_ph)}; let qthis: u64 = qthis_ph; let rsthis = QSslCipher{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: void QSslCipher::QSslCipher(const QString & name); impl<'a> /*trait*/ QSslCipher_new for (&'a QString) { fn new(self) -> QSslCipher { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QSslCipherC2ERK7QString()}; let ctysz: c_int = unsafe{QSslCipher_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN10QSslCipherC2ERK7QString(qthis_ph, arg0)}; let qthis: u64 = qthis_ph; let rsthis = QSslCipher{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QString QSslCipher::protocolString(); impl /*struct*/ QSslCipher { pub fn protocolString<RetType, T: QSslCipher_protocolString<RetType>>(& self, overload_args: T) -> RetType { return overload_args.protocolString(self); // return 1; } } pub trait QSslCipher_protocolString<RetType> { fn protocolString(self , rsthis: & QSslCipher) -> RetType; } // proto: QString QSslCipher::protocolString(); impl<'a> /*trait*/ QSslCipher_protocolString<QString> for () { fn protocolString(self , rsthis: & QSslCipher) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QSslCipher14protocolStringEv()}; let mut ret = unsafe {_ZNK10QSslCipher14protocolStringEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: int QSslCipher::supportedBits(); impl /*struct*/ QSslCipher { pub fn supportedBits<RetType, T: QSslCipher_supportedBits<RetType>>(& self, overload_args: T) -> RetType { return overload_args.supportedBits(self); // return 1; } } pub trait QSslCipher_supportedBits<RetType> { fn supportedBits(self , rsthis: & QSslCipher) -> RetType; } // proto: int QSslCipher::supportedBits(); impl<'a> /*trait*/ QSslCipher_supportedBits<i32> for () { fn supportedBits(self , rsthis: & QSslCipher) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QSslCipher13supportedBitsEv()}; let mut ret = unsafe {_ZNK10QSslCipher13supportedBitsEv(rsthis.qclsinst)}; return ret as i32; // return 1; } } // proto: int QSslCipher::usedBits(); impl /*struct*/ QSslCipher { pub fn usedBits<RetType, T: QSslCipher_usedBits<RetType>>(& self, overload_args: T) -> RetType { return overload_args.usedBits(self); // return 1; } } pub trait QSslCipher_usedBits<RetType> { fn usedBits(self , rsthis: & QSslCipher) -> RetType; } // proto: int QSslCipher::usedBits(); impl<'a> /*trait*/ QSslCipher_usedBits<i32> for () { fn usedBits(self , rsthis: & QSslCipher) -> i32 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QSslCipher8usedBitsEv()}; let mut ret = unsafe {_ZNK10QSslCipher8usedBitsEv(rsthis.qclsinst)}; return ret as i32; // return 1; } } // proto: void QSslCipher::swap(QSslCipher & other); impl /*struct*/ QSslCipher { pub fn swap<RetType, T: QSslCipher_swap<RetType>>(& self, overload_args: T) -> RetType { return overload_args.swap(self); // return 1; } } pub trait QSslCipher_swap<RetType> { fn swap(self , rsthis: & QSslCipher) -> RetType; } // proto: void QSslCipher::swap(QSslCipher & other); impl<'a> /*trait*/ QSslCipher_swap<()> for (&'a QSslCipher) { fn swap(self , rsthis: & QSslCipher) -> () { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QSslCipher4swapERS_()}; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN10QSslCipher4swapERS_(rsthis.qclsinst, arg0)}; // return 1; } } // proto: QString QSslCipher::keyExchangeMethod(); impl /*struct*/ QSslCipher { pub fn keyExchangeMethod<RetType, T: QSslCipher_keyExchangeMethod<RetType>>(& self, overload_args: T) -> RetType { return overload_args.keyExchangeMethod(self); // return 1; } } pub trait QSslCipher_keyExchangeMethod<RetType> { fn keyExchangeMethod(self , rsthis: & QSslCipher) -> RetType; } // proto: QString QSslCipher::keyExchangeMethod(); impl<'a> /*trait*/ QSslCipher_keyExchangeMethod<QString> for () { fn keyExchangeMethod(self , rsthis: & QSslCipher) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QSslCipher17keyExchangeMethodEv()}; let mut ret = unsafe {_ZNK10QSslCipher17keyExchangeMethodEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: void QSslCipher::QSslCipher(const QSslCipher & other); impl<'a> /*trait*/ QSslCipher_new for (&'a QSslCipher) { fn new(self) -> QSslCipher { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZN10QSslCipherC2ERKS_()}; let ctysz: c_int = unsafe{QSslCipher_Class_Size()}; let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64; let arg0 = self.qclsinst as *mut c_void; unsafe {_ZN10QSslCipherC2ERKS_(qthis_ph, arg0)}; let qthis: u64 = qthis_ph; let rsthis = QSslCipher{qclsinst: qthis, ..Default::default()}; return rsthis; // return 1; } } // proto: QString QSslCipher::authenticationMethod(); impl /*struct*/ QSslCipher { pub fn authenticationMethod<RetType, T: QSslCipher_authenticationMethod<RetType>>(& self, overload_args: T) -> RetType { return overload_args.authenticationMethod(self); // return 1; } } pub trait QSslCipher_authenticationMethod<RetType> { fn authenticationMethod(self , rsthis: & QSslCipher) -> RetType; } // proto: QString QSslCipher::authenticationMethod(); impl<'a> /*trait*/ QSslCipher_authenticationMethod<QString> for () { fn authenticationMethod(self , rsthis: & QSslCipher) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QSslCipher20authenticationMethodEv()}; let mut ret = unsafe {_ZNK10QSslCipher20authenticationMethodEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // proto: bool QSslCipher::isNull(); impl /*struct*/ QSslCipher { pub fn isNull<RetType, T: QSslCipher_isNull<RetType>>(& self, overload_args: T) -> RetType { return overload_args.isNull(self); // return 1; } } pub trait QSslCipher_isNull<RetType> { fn isNull(self , rsthis: & QSslCipher) -> RetType; } // proto: bool QSslCipher::isNull(); impl<'a> /*trait*/ QSslCipher_isNull<i8> for () { fn isNull(self , rsthis: & QSslCipher) -> i8 { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QSslCipher6isNullEv()}; let mut ret = unsafe {_ZNK10QSslCipher6isNullEv(rsthis.qclsinst)}; return ret as i8; // return 1; } } // proto: QString QSslCipher::encryptionMethod(); impl /*struct*/ QSslCipher { pub fn encryptionMethod<RetType, T: QSslCipher_encryptionMethod<RetType>>(& self, overload_args: T) -> RetType { return overload_args.encryptionMethod(self); // return 1; } } pub trait QSslCipher_encryptionMethod<RetType> { fn encryptionMethod(self , rsthis: & QSslCipher) -> RetType; } // proto: QString QSslCipher::encryptionMethod(); impl<'a> /*trait*/ QSslCipher_encryptionMethod<QString> for () { fn encryptionMethod(self , rsthis: & QSslCipher) -> QString { // let qthis: *mut c_void = unsafe{calloc(1, 32)}; // unsafe{_ZNK10QSslCipher16encryptionMethodEv()}; let mut ret = unsafe {_ZNK10QSslCipher16encryptionMethodEv(rsthis.qclsinst)}; let mut ret1 = QString::inheritFrom(ret as u64); return ret1; // return 1; } } // <= body block end
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::any::Any; use std::sync::Arc; use common_base::base::tokio; use common_catalog::catalog::Catalog; use common_catalog::catalog::StorageDescription; use common_catalog::database::Database; use common_catalog::table::Table; use common_catalog::table_args::TableArgs; use common_catalog::table_function::TableFunction; use common_exception::ErrorCode; use common_exception::Result; use common_hive_meta_store::Partition; use common_hive_meta_store::TThriftHiveMetastoreSyncClient; use common_hive_meta_store::ThriftHiveMetastoreSyncClient; use common_meta_app::schema::CountTablesReply; use common_meta_app::schema::CountTablesReq; use common_meta_app::schema::CreateDatabaseReply; use common_meta_app::schema::CreateDatabaseReq; use common_meta_app::schema::CreateTableReq; use common_meta_app::schema::DropDatabaseReq; use common_meta_app::schema::DropTableByIdReq; use common_meta_app::schema::DropTableReply; use common_meta_app::schema::GetTableCopiedFileReply; use common_meta_app::schema::GetTableCopiedFileReq; use common_meta_app::schema::RenameDatabaseReply; use common_meta_app::schema::RenameDatabaseReq; use common_meta_app::schema::RenameTableReply; use common_meta_app::schema::RenameTableReq; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use common_meta_app::schema::TruncateTableReply; use common_meta_app::schema::TruncateTableReq; use common_meta_app::schema::UndropDatabaseReply; use common_meta_app::schema::UndropDatabaseReq; use common_meta_app::schema::UndropTableReply; use common_meta_app::schema::UndropTableReq; use common_meta_app::schema::UpdateTableMetaReply; use common_meta_app::schema::UpdateTableMetaReq; use common_meta_app::schema::UpsertTableOptionReply; use common_meta_app::schema::UpsertTableOptionReq; use common_meta_types::*; use thrift::protocol::*; use thrift::transport::*; use super::hive_database::HiveDatabase; use crate::hive_table::HiveTable; pub const HIVE_CATALOG: &str = "hive"; #[derive(Clone)] pub struct HiveCatalog { /// address of hive meta store service client_address: String, } impl HiveCatalog { pub fn try_create(hms_address: impl Into<String>) -> Result<HiveCatalog> { Ok(HiveCatalog { client_address: hms_address.into(), }) } pub fn get_client(&self) -> Result<impl TThriftHiveMetastoreSyncClient> { let mut c = TTcpChannel::new(); c.open(self.client_address.as_str()) .map_err(from_thrift_error)?; let (i_chan, o_chan) = c.split().map_err(from_thrift_error)?; let i_tran = TBufferedReadTransport::new(i_chan); let o_tran = TBufferedWriteTransport::new(o_chan); let i_prot = TBinaryInputProtocol::new(i_tran, true); let o_prot = TBinaryOutputProtocol::new(o_tran, true); Ok(ThriftHiveMetastoreSyncClient::new(i_prot, o_prot)) } pub async fn get_partitions( &self, db: String, table: String, partition_names: Vec<String>, ) -> Result<Vec<Partition>> { let client = self.get_client()?; tokio::task::spawn_blocking(move || { Self::do_get_partitions(client, db, table, partition_names) }) .await .unwrap() } pub fn do_get_partitions( client: impl TThriftHiveMetastoreSyncClient, db_name: String, tbl_name: String, partition_names: Vec<String>, ) -> Result<Vec<Partition>> { let mut client = client; let max_partitions = 10_000; let partitions = partition_names .chunks(max_partitions) .flat_map(|names| { client .get_partitions_by_names(db_name.clone(), tbl_name.clone(), names.to_vec()) .map_err(from_thrift_error) .unwrap() }) .collect::<Vec<_>>(); Ok(partitions) } #[tracing::instrument(level = "info", skip(self))] pub async fn get_partition_names( &self, db: String, table: String, max_parts: i16, ) -> Result<Vec<String>> { let client = self.get_client()?; tokio::task::spawn_blocking(move || { Self::do_get_partition_names(client, db, table, max_parts) }) .await .unwrap() } pub fn do_get_partition_names( client: impl TThriftHiveMetastoreSyncClient, db: String, table: String, max_parts: i16, ) -> Result<Vec<String>> { let mut client = client; client .get_partition_names(db, table, max_parts) .map_err(from_thrift_error) } fn do_get_table( client: impl TThriftHiveMetastoreSyncClient, db_name: String, table_name: String, ) -> Result<Arc<dyn Table>> { let mut client = client; let table = client.get_table(db_name.clone(), table_name.clone()); let table_meta = match table { Ok(table_meta) => table_meta, Err(e) => { if let thrift::Error::User(err) = &e { if let Some(e) = err.downcast_ref::<common_hive_meta_store::NoSuchObjectException>() { return Err(ErrorCode::TableInfoError( e.message.clone().unwrap_or_default(), )); } } return Err(from_thrift_error(e)); } }; if let Some(sd) = table_meta.sd.as_ref() { if let Some(input_format) = sd.input_format.as_ref() { if input_format != "org.apache.hadoop.hive.ql.io.parquet.MapredParquetInputFormat" { return Err(ErrorCode::Unimplemented(format!( "only support parquet, {} not support", input_format ))); } } } if let Some(t) = table_meta.table_type.as_ref() { if t == "VIRTUAL_VIEW" { return Err(ErrorCode::Unimplemented("not support view table")); } } let fields = client .get_schema(db_name, table_name) .map_err(from_thrift_error)?; let table_info: TableInfo = super::converters::try_into_table_info(table_meta, fields)?; let res: Arc<dyn Table> = Arc::new(HiveTable::try_create(table_info)?); Ok(res) } fn do_get_database( client: impl TThriftHiveMetastoreSyncClient, db_name: String, ) -> Result<Arc<dyn Database>> { let mut client = client; let thrift_db_meta = client.get_database(db_name).map_err(from_thrift_error)?; let hive_database: HiveDatabase = thrift_db_meta.into(); let res: Arc<dyn Database> = Arc::new(hive_database); Ok(res) } } fn from_thrift_error(error: thrift::Error) -> ErrorCode { ErrorCode::from_std_error(error) } #[async_trait::async_trait] impl Catalog for HiveCatalog { fn as_any(&self) -> &dyn Any { self } #[tracing::instrument(level = "info", skip(self))] async fn get_database(&self, _tenant: &str, db_name: &str) -> Result<Arc<dyn Database>> { let client = self.get_client()?; let _tenant = _tenant.to_string(); let db_name = db_name.to_string(); tokio::task::spawn_blocking(move || Self::do_get_database(client, db_name)) .await .unwrap() } // Get all the databases. async fn list_databases(&self, _tenant: &str) -> Result<Vec<Arc<dyn Database>>> { todo!() } // Operation with database. async fn create_database(&self, _req: CreateDatabaseReq) -> Result<CreateDatabaseReply> { Err(ErrorCode::Unimplemented( "Cannot create database in HIVE catalog", )) } async fn drop_database(&self, _req: DropDatabaseReq) -> Result<()> { Err(ErrorCode::Unimplemented( "Cannot drop database in HIVE catalog", )) } async fn undrop_database(&self, _req: UndropDatabaseReq) -> Result<UndropDatabaseReply> { Err(ErrorCode::Unimplemented( "Cannot undrop database in HIVE catalog", )) } async fn rename_database(&self, _req: RenameDatabaseReq) -> Result<RenameDatabaseReply> { Err(ErrorCode::Unimplemented( "Cannot rename database in HIVE catalog", )) } fn get_table_by_info(&self, table_info: &TableInfo) -> Result<Arc<dyn Table>> { let res: Arc<dyn Table> = Arc::new(HiveTable::try_create(table_info.clone())?); Ok(res) } async fn get_table_meta_by_id( &self, _table_id: MetaId, ) -> Result<(TableIdent, Arc<TableMeta>)> { Err(ErrorCode::Unimplemented( "Cannot get table by id in HIVE catalog", )) } // Get one table by db and table name. #[tracing::instrument(level = "info", skip(self))] async fn get_table( &self, _tenant: &str, db_name: &str, table_name: &str, ) -> Result<Arc<dyn Table>> { let client = self.get_client()?; let db_name = db_name.to_string(); let table_name = table_name.to_string(); tokio::task::spawn_blocking(move || Self::do_get_table(client, db_name, table_name)) .await .unwrap() } async fn list_tables(&self, _tenant: &str, _db_name: &str) -> Result<Vec<Arc<dyn Table>>> { todo!() } async fn list_tables_history( &self, _tenant: &str, _db_name: &str, ) -> Result<Vec<Arc<dyn Table>>> { Err(ErrorCode::Unimplemented( "Cannot list table history in HIVE catalog", )) } async fn create_table(&self, _req: CreateTableReq) -> Result<()> { Err(ErrorCode::Unimplemented( "Cannot create table in HIVE catalog", )) } async fn drop_table_by_id(&self, _req: DropTableByIdReq) -> Result<DropTableReply> { Err(ErrorCode::Unimplemented( "Cannot drop table in HIVE catalog", )) } async fn undrop_table(&self, _req: UndropTableReq) -> Result<UndropTableReply> { Err(ErrorCode::Unimplemented( "Cannot undrop table in HIVE catalog", )) } async fn rename_table(&self, _req: RenameTableReq) -> Result<RenameTableReply> { Err(ErrorCode::Unimplemented( "Cannot rename table in HIVE catalog", )) } // Check a db.table is exists or not. async fn exists_table(&self, tenant: &str, db_name: &str, table_name: &str) -> Result<bool> { // TODO refine this match self.get_table(tenant, db_name, table_name).await { Ok(_) => Ok(true), Err(err) => { if err.code() == ErrorCode::UNKNOWN_TABLE { Ok(false) } else { Err(err) } } } } async fn upsert_table_option( &self, _tenant: &str, _db_name: &str, _req: UpsertTableOptionReq, ) -> Result<UpsertTableOptionReply> { Err(ErrorCode::Unimplemented( "Cannot upsert table option in HIVE catalog", )) } async fn update_table_meta( &self, _table_info: &TableInfo, _req: UpdateTableMetaReq, ) -> Result<UpdateTableMetaReply> { Err(ErrorCode::Unimplemented( "Cannot update table meta in HIVE catalog", )) } async fn get_table_copied_file_info( &self, _tenant: &str, _db_name: &str, _req: GetTableCopiedFileReq, ) -> Result<GetTableCopiedFileReply> { unimplemented!() } async fn truncate_table( &self, _table_info: &TableInfo, _req: TruncateTableReq, ) -> Result<TruncateTableReply> { unimplemented!() } async fn count_tables(&self, _req: CountTablesReq) -> Result<CountTablesReply> { unimplemented!() } /// Table function // Get function by name. fn get_table_function( &self, _func_name: &str, _tbl_args: TableArgs, ) -> Result<Arc<dyn TableFunction>> { unimplemented!() } // List all table functions' names. fn list_table_functions(&self) -> Vec<String> { vec![] } // Get table engines fn get_table_engines(&self) -> Vec<StorageDescription> { unimplemented!() } }
use wasm_bindgen_test::*; use js_sys::*; #[wasm_bindgen_test] fn validate() { assert!(!WebAssembly::validate(&ArrayBuffer::new(42).into()).unwrap()); assert!(WebAssembly::validate(&2.into()).is_err()); }
#![no_std] #![no_main] #![feature(global_asm)] mod arch; mod panic; // The virt arch global_asm!(include_str!("arch/aarch64/qemu_virt/start.s")); pub use arch::aarch64::qemu_virt::QEMU_UART0_VIRT; mod kdriver; // Kernel public functions pub use kdriver::serial::{serial_log, serialc}; use kdriver::{kfs, uri_sys}; mod config; pub const CONFIG: &str = include_str!("/home/able/Projects/echOS-arm/root/kernel_config.json"); /// The main function called at runtime by the assembly #[no_mangle] pub extern "C" fn boot() { uri_sys::init(); kfs::init(); config::get_config(); serial_log("> kernel fully loaded"); serial_log("SPIN CPU INFINITLY"); loop {} // If commented out the kernel panics }
extern crate image; extern crate nalgebra as na; use std::mem::swap; use shape; //use tf; use tf::Pose; #[derive(Debug)] pub struct GraphicsContext { pub tf_root: na::Matrix4<f32>, pub projection: na::Perspective3<f32>, pub img_width: u32, pub img_height: u32, pub imgbuf: image::RgbImage, } impl GraphicsContext { pub fn unproject_point(&self, p: na::Point2<u32>) -> shape::Ray { // Normalize pixel range from [0, width] t0 [-1, 1] let norm_px_x = (p.x - self.img_width/2) as f32 / self.img_width as f32; let norm_px_y = (p.y - self.img_height/2) as f32 / self.img_height as f32; // Compute two points in clip-space. // "ndc" = normalized device coordinates. let near_ndc_point = na::Point3::new(norm_px_x, norm_px_y, -1.0); let far_ndc_point = na::Point3::new(norm_px_x, norm_px_y, 1.0); // Unproject them to view-space. let near_view_point = self.projection.unproject_point(&near_ndc_point); let far_view_point = self.projection.unproject_point(&far_ndc_point); // Compute the view-space line parameters. let line_direction = far_view_point - near_view_point; shape::Ray { origin: near_view_point, direction: line_direction, } } pub fn project_point(&self, p: na::Vector3<f32>) -> na::Vector2<i64> { // Project and transform "Normalized Device Coordinates" (-1, 1) to (0, 1) let img_pt = (self.projection.project_vector(&p) + na::Vector3::new(1.0, 1.0, 1.0)) / 2.0; // Transform (0, 1) to (0, img_width) and (0, img_height) let px_x = (img_pt[0] * (self.img_width as f32)).round() as i64; let px_y = (img_pt[1] * (self.img_height as f32)).round() as i64; na::Vector2::new(px_x, px_y) } pub fn put_pixel(&mut self, x: i64, y: i64, color: image::Rgb<u8>) { if x >= 0 && x < self.img_width as i64 && y >= 0 && y < self.img_height as i64 { self.put_pixel_unchecked(x, y, color); } } pub fn put_pixel_unchecked(&mut self, x: i64, y: i64, color: image::Rgb<u8>) { self.imgbuf.put_pixel(x as u32, y as u32, color); } pub fn save(&self, image_file: &str) { &self.imgbuf.save(image_file); } } pub fn draw_line( p0: &na::Matrix4<f32>, p1: &na::Matrix4<f32>, color: image::Rgb<u8>, context: &mut GraphicsContext, ) { draw_line_vec(&p0.translation().clone_owned(), &p1.translation().clone_owned(), color, context) } pub fn draw_line_vec( p0: &na::Vector3<f32>, p1: &na::Vector3<f32>, color: image::Rgb<u8>, context: &mut GraphicsContext, ) { let p0_px = context.project_point(p0.clone()); let p1_px = context.project_point(p1.clone()); let mut x0: i64 = p0_px[0]; let mut y0: i64 = p0_px[1]; let mut x1: i64 = p1_px[0]; let mut y1: i64 = p1_px[1]; let mut steep = false; // if the line is steep, we transpose the image if (x0 - x1).abs() < (y0 - y1).abs() { swap(&mut x0, &mut y0); swap(&mut x1, &mut y1); steep = true; } // make it left-to-right if x0 > x1 { swap(&mut x0, &mut x1); swap(&mut y0, &mut y1); } if x0 == x1 { x1 += 1; } for mut x in x0..x1 { let t = (x - x0) as f32 / ((x1 - x0) as f32); let mut y = ((y0 as f32) * (1.0 - t) + (y1 as f32) * t).round() as i64; if steep { // if transposed, de-transpose swap(&mut x, &mut y); } context.put_pixel(x, y, color); } } pub fn draw_axes( tf: &na::Matrix4<f32>, size: f32, mut context: &mut GraphicsContext, ) { let r = image::Rgb([255, 0, 0]); let g = image::Rgb([0, 255, 0]); let b = image::Rgb([0, 0, 255]); let unit_x_w = tf.append_translation(&na::Vector3::new(size, 0.0, 0.0)); let unit_y_w = tf.append_translation(&na::Vector3::new(0.0, size, 0.0)); let unit_z_w = tf.append_translation(&na::Vector3::new(0.0, 0.0, size)); draw_line(&tf, &unit_x_w, r, &mut context); draw_line(&tf, &unit_y_w, g, &mut context); draw_line(&tf, &unit_z_w, b, &mut context); } pub fn _draw_circle( tf: &na::Matrix4<f32>, radius: f32, context: &mut GraphicsContext, ) { let circle_pt_count = 64; for idx in 0..(circle_pt_count) { let angle = 2.0 * ::std::f32::consts::PI * (idx as f32 / circle_pt_count as f32); let world_pt_d = na::Vector3::new(radius * angle.cos(), radius * angle.sin(), 0.0); let world_pt = tf.clone().prepend_translation(&world_pt_d); let px = context.project_point( world_pt.translation().clone_owned(), ); if 0 < px[0] && px[0] < context.img_width as i64 && 0 < px[1] && px[1] < context.img_height as i64 { context.put_pixel(px[0] as i64, px[1] as i64, image::Rgb([255, 255, 255])); } else { error!("Pixels outside image! {}, {}", px[0], px[1]); } } } pub fn draw_cube( tf: &na::Matrix4<f32>, size: f32, color: image::Rgb<u8>, mut context: &mut GraphicsContext, ) { let dp = size / 2.0; let dn = size / -2.0; let corners: [na::Matrix4<f32>; 8] = [ tf * na::Matrix4::new_translation(&na::Vector3::new(dp, dp, dp)), // 0 tf * na::Matrix4::new_translation(&na::Vector3::new(dn, dp, dp)), // 1 tf * na::Matrix4::new_translation(&na::Vector3::new(dn, dn, dp)), // 2 tf * na::Matrix4::new_translation(&na::Vector3::new(dp, dn, dp)), // 3 tf * na::Matrix4::new_translation(&na::Vector3::new(dp, dp, dn)), // 4 tf * na::Matrix4::new_translation(&na::Vector3::new(dn, dp, dn)), // 5 tf * na::Matrix4::new_translation(&na::Vector3::new(dn, dn, dn)), // 6 tf * na::Matrix4::new_translation(&na::Vector3::new(dp, dn, dn)), // 7 ]; // Top draw_line(&corners[0], &corners[1], color, &mut context); draw_line(&corners[1], &corners[2], color, &mut context); draw_line(&corners[2], &corners[3], color, &mut context); draw_line(&corners[3], &corners[0], color, &mut context); // Bottom draw_line(&corners[4], &corners[5], color, &mut context); draw_line(&corners[5], &corners[6], color, &mut context); draw_line(&corners[6], &corners[7], color, &mut context); draw_line(&corners[7], &corners[4], color, &mut context); // Sides draw_line(&corners[0], &corners[4], color, &mut context); draw_line(&corners[1], &corners[5], color, &mut context); draw_line(&corners[2], &corners[6], color, &mut context); draw_line(&corners[3], &corners[7], color, &mut context); }
extern crate parse_obj; use parse_obj::*; static TRIANGLE_OBJ: &'static str = r#" v -1.0 -1.0 0.0 v 1.0 -1.0 0.0 v 0.0 1.0 0.0 f 1// 2// 3// "#; static TRIANGLE_WITH_NORM: &'static str = r#" v -1.0 -1.0 0.0 v 1.0 -1.0 0.0 v 0.0 1.0 0.0 vt 1.0 1.0 1.0 vn 1.0 0.0 0.0 f 1/1/1 2/1/1 3/1/1 "#; #[test] fn test_iterator() { { let obj = Obj::from_str(TRIANGLE_OBJ).unwrap(); let mut face_iter = obj.faces(); let mut face = face_iter.next().unwrap(); assert!(face_iter.next().is_none()); assert_eq!(Some(((-1.0, -1.0, 0.0, 1.0), None, None)), face.next()); assert_eq!(Some(((1.0, -1.0, 0.0, 1.0), None, None)), face.next()); assert_eq!(Some(((0.0, 1.0, 0.0, 1.0), None, None)), face.next()); } { let obj = Obj::from_str(TRIANGLE_WITH_NORM).unwrap(); let mut face_iter = obj.faces(); let mut face = face_iter.next().unwrap(); assert!(face_iter.next().is_none()); assert_eq!(Some(((-1.0, -1.0, 0.0, 1.0), Some((1.0, 1.0, 1.0)), Some((1.0, 0.0, 0.0)))), face.next()); assert_eq!(Some(((1.0, -1.0, 0.0, 1.0), Some((1.0, 1.0, 1.0)), Some((1.0, 0.0, 0.0)))), face.next()); assert_eq!(Some(((0.0, 1.0, 0.0, 1.0), Some((1.0, 1.0, 1.0)), Some((1.0, 0.0, 0.0)))), face.next()); } }
#![feature(asm)] #![feature(naked_functions)] #![feature(termination_trait_lib)] #![feature(thread_local)] #![feature(alloc_layout_extra)] #[cfg(not(unix))] compile_error!("lumen_rt_minimal is only supported on unix targets!"); #[macro_use] mod macros; mod config; mod logging; mod scheduler; mod sys; mod distribution; mod process; use bus::Bus; use log::Level; use std::thread; use lumen_rt_core as rt_core; use self::config::Config; use self::scheduler::Scheduler; use self::sys::break_handler::{self, Signal}; #[liblumen_core::entry] fn main() -> impl ::std::process::Termination + 'static { let name = env!("CARGO_PKG_NAME"); let version = env!("CARGO_PKG_VERSION"); main_internal(name, version, std::env::args().collect()) } fn main_internal(name: &str, version: &str, argv: Vec<String>) -> Result<(), ()> { // Load system configuration let _config = match Config::from_argv(name.to_string(), version.to_string(), argv) { Ok(config) => config, Err(err) => { eprintln!("Config error: {}", err); return Err(()); } }; // This bus is used to receive signals across threads in the system let mut bus: Bus<break_handler::Signal> = Bus::new(1); // Each thread needs a reader let mut rx1 = bus.add_rx(); // Initialize the break handler with the bus, which will broadcast on it break_handler::init(bus); // Start logger let level_filter = Level::Info.to_level_filter(); logging::init(level_filter).expect("Unexpected failure initializing logger"); let scheduler = <Scheduler as rt_core::Scheduler>::current(); loop { // Run the scheduler for a cycle let scheduled = scheduler.run_once(); // Check for system signals, and terminate if needed if let Ok(sig) = rx1.try_recv() { match sig { // For now, SIGINT initiates a controlled shutdown Signal::INT => { // If an error occurs, report it before shutdown if let Err(err) = scheduler.shutdown() { eprintln!("System error: {}", err); return Err(()); } else { break; } } // Technically, we may never see these signals directly, // we may just be terminated out of hand; but just in case, // we handle them explicitly by immediately terminating, so // that we are good citizens of the operating system sig if sig.should_terminate() => { return Err(()); } // All other signals can be surfaced to other parts of the // system for custom use, e.g. SIGCHLD, SIGALRM, SIGUSR1/2 _ => (), } } // If the scheduler scheduled a process this cycle, then we're busy // and should keep working until we have an idle period if scheduled { continue; } // Otherwise, // In some configurations, it makes more sense for us to spin and use // spin_loop_hint here instead; namely when we're supposed to be the primary // software on a system, and threads are pinned to cores, it makes no sense // to yield to the system scheduler. However on a system with contention for // system resources, or where threads aren't pinned to cores, we're better off // explicitly yielding to the scheduler, rather than waiting to be preempted at // a potentially inopportune time. // // In any case, for now, we always explicitly yield until we've got proper support // for configuring the system thread::yield_now() } Ok(()) }
use std::fs; fn main() { let data = fs::read_to_string("input").expect("Error"); let mut numbers: Vec<u32> = data.lines().map(|x| x.parse::<u32>().unwrap()).collect(); numbers.sort_unstable(); numbers = numbers .iter() .enumerate() .map(|(idx, x)| x - previous(idx, &numbers)) .collect(); let ones = numbers.iter().filter(|x| x == &&1).count(); let threes = numbers.iter().filter(|x| x == &&3).count() + 1; println!("Ones {}", ones); println!("Threes {}", threes); println!("The result is {}", ones * threes); } fn previous(idx: usize, vec: &[u32]) -> u32 { match idx { 0 => 0, _ => vec[idx - 1], } }
//Tutorial developed by Philipp Oppermann - https://os.phil-opp.com/freestanding-rust-binary/ //Disabling std library from build. #![no_std] //Overwriting Entry Point #![no_main] use core::panic::PanicInfo; //Using our own Rust module for handling printing mod vga_buffer; //Function to be called when panic. #[panic_handler] fn panic(_info: &PanicInfo) -> ! { println!("{}",_info); loop{} } /* Overwriting OS entry point with our own No mangle disables name mangling so rust compiler outputs func name as _start - otherwise the compiler would name it with a criptic name so it would be ensured - as a unique name. Also marking with (extern "C") so the compiler uses the C calling conversion and not the - Rust one. Naming the function (_start) because its an entry point name for most systems The ! return type means that the function is diverging, which means it is not allowed to ever return - this is required due to the fact that the entry point is invoked directly by the OS or bootloader - and not by a function. Instead of returning, the (exit) system call should be invoked. */ static HELLO: &[u8] = b"Hello World!"; #[no_mangle] pub extern "C" fn _start() -> ! { // //Raw pointer pointing to VGA buffer // let vga_buffer = 0xb8000 as *mut u8; // //Iterating through bytes of string // for (i, &byte) in HELLO.iter().enumerate() { // // Rust compiler can't tell if raw pointer is valid // //so unsafe is used meaning we are sure that the raw pointer is valid // unsafe { // //Writting the string byte // *vga_buffer.offset(i as isize * 2) = byte; // //Writting string byte color (Light cyan) // *vga_buffer.offset(i as isize * 2 + 1) = 0xb; // } // } println!("Hello world{}", "!"); println!(); panic!("Generic panic message"); loop{} }
use std::collections::HashMap; use color_eyre::eyre::{eyre, Result, WrapErr}; use execute::shell; use serde::Deserialize; use crate::git::branch_name_from_issue; use crate::semver::get_version; use crate::State; /// Describes a value that you can replace an arbitrary string with when running a command. #[derive(Debug, Deserialize)] pub(crate) enum Variable { /// Uses the first supported version found in your project. Version, /// The generated branch name for the selected issue. Note that this means the workflow must /// already be in [`State::IssueSelected`] when this variable is used. IssueBranch, } /// Run the command string `command` in the current shell after replacing the keys of `variables` /// with the values that the [`Variable`]s represent. pub(crate) fn run_command( state: State, mut command: String, variables: Option<HashMap<String, Variable>>, ) -> Result<State> { if let Some(variables) = variables { command = replace_variables(command, variables, &state) .wrap_err("While getting current version")?; } let status = shell(command).status()?; if status.success() { return Ok(state); } Err(eyre!("Got error status {} when running command", status)) } /// Replace declared variables in the command string and return command. fn replace_variables( mut command: String, variables: HashMap<String, Variable>, state: &State, ) -> Result<String> { for (var_name, var_type) in variables { match var_type { Variable::Version => command = command.replace(&var_name, &get_version()?.to_string()), Variable::IssueBranch => { match state { State::Initial(_) => return Err(eyre!("Cannot use the variable IssueBranch unless the current workflow state is IssueSelected")), State::IssueSelected(state_data) => { command = command.replace(&var_name, &branch_name_from_issue(&state_data.issue)) } } } } } Ok(command) } #[cfg(test)] mod test_run_command { use super::*; use tempfile::NamedTempFile; #[test] fn test() { let file = NamedTempFile::new().unwrap(); let command = format!("cat {}", file.path().to_str().unwrap()); let result = run_command(State::new(None, None), command.clone(), None); assert!(result.is_ok()); file.close().unwrap(); let result = run_command(State::new(None, None), command, None); assert!(result.is_err()); } } #[cfg(test)] mod test_replace_variables { use super::*; use crate::issues::Issue; use crate::state::{GitHub, Initial, IssueSelected}; #[test] fn multiple_variables() { let command = "blah $$ branch_name".to_string(); let mut variables = HashMap::new(); variables.insert("$$".to_string(), Variable::Version); variables.insert("branch_name".to_string(), Variable::IssueBranch); let issue = Issue { key: "13".to_string(), summary: "1234".to_string(), }; let expected_branch_name = branch_name_from_issue(&issue); let state = State::IssueSelected(IssueSelected { jira_config: None, github_state: GitHub::New, github_config: None, issue, }); let command = replace_variables(command, variables, &state).unwrap(); assert_eq!( command, format!( "blah {} {}", get_version().unwrap().to_string(), expected_branch_name ) ) } #[test] fn replace_version() { let command = "blah $$ other blah".to_string(); let mut variables = HashMap::new(); variables.insert("$$".to_string(), Variable::Version); let state = State::Initial(Initial { jira_config: None, github_state: GitHub::New, github_config: None, }); let command = replace_variables(command, variables, &state).unwrap(); assert_eq!( command, format!("blah {} other blah", get_version().unwrap().to_string(),) ) } #[test] fn replace_issue_branch() { let command = "blah $$ other blah".to_string(); let mut variables = HashMap::new(); variables.insert("$$".to_string(), Variable::IssueBranch); let issue = Issue { key: "13".to_string(), summary: "1234".to_string(), }; let expected_branch_name = branch_name_from_issue(&issue); let state = State::IssueSelected(IssueSelected { jira_config: None, github_state: GitHub::New, github_config: None, issue, }); let command = replace_variables(command, variables, &state).unwrap(); assert_eq!(command, format!("blah {} other blah", expected_branch_name)) } }
use std::collections::HashMap; use std::collections::HashSet; pub fn run(path: &str) { let input = std::fs::read_to_string(path).expect("Couldn't read data file"); let (steps, _) = parser::parse_steps(&input).expect("Couldn't parse input steps"); let mut step_deps = build_step_deps(&steps); let step_order: String = step_order(&mut step_deps).into_iter().collect(); println!("Day 7, part 1: {}", step_order); let mut step_deps = build_step_deps(&steps); let part_2_solution = duration(&mut step_deps, 5, 60); println!("Day 7, part 2: {}", part_2_solution); } type Step = char; type StepDeps = HashMap<Step, HashSet<Step>>; fn build_step_deps(step_lines: &[(Step, Step)]) -> StepDeps { step_lines .iter() .fold(HashMap::new(), |mut step_deps, (dep, step)| { step_deps .entry(*step) .and_modify(|deps| { deps.insert(*dep); }).or_insert_with(|| { let mut deps = HashSet::new(); deps.insert(*dep); deps }); step_deps.entry(*dep).or_insert_with(|| HashSet::new()); step_deps }) } fn get_available_steps(step_deps: &StepDeps) -> Vec<Step> { step_deps .iter() .filter_map( |(&step, deps)| { if deps.len() == 0 { Some(step) } else { None } }, ).collect() } fn do_step(step: Step, step_deps: &mut StepDeps) { step_deps.remove(&step); step_deps.iter_mut().for_each(|(_, deps)| { deps.remove(&step); }); } fn step_order(step_deps: &mut StepDeps) -> Vec<Step> { let mut done_steps = Vec::new(); while step_deps.len() > 0 { let mut available_steps = get_available_steps(step_deps); available_steps.sort(); let step = available_steps.remove(0); done_steps.push(step); do_step(step, step_deps); } done_steps } fn step_cost(step: Step, base: u32) -> u32 { step as u32 - 64 + base } #[derive(Debug)] struct Task { step: Step, started_at: u32, } fn duration(step_deps: &mut StepDeps, workers: usize, base_cost: u32) -> u32 { let mut tasks: Vec<Task> = vec![]; for now in 0.. { let (done_tasks, mut tasks_still_running): (Vec<Task>, Vec<Task>) = tasks .into_iter() .partition(|task| now - task.started_at >= step_cost(task.step, base_cost)); for t in done_tasks.iter() { do_step(t.step, step_deps); } let available_workers = workers - tasks_still_running.len(); let new_tasks: Vec<Task> = get_available_steps(step_deps) .iter() .filter(|&step| !tasks_still_running.iter().any(|task| task.step == *step)) .take(available_workers) .map(|&step| Task { step, started_at: now, }).collect(); tasks_still_running.extend(new_tasks); tasks = tasks_still_running; if tasks.len() == 0 { return now; } } 0 } mod parser { use combine::parser::char::{newline, string, upper}; use combine::sep_by; use combine::Parser; // Step P must be finished before step O can begin. pub fn parse_steps( input: &str, ) -> Result< (Vec<(char, char)>, &str), combine::easy::Errors<char, &str, combine::stream::PointerOffset>, > { let step_line = || { ( string("Step "), upper(), string(" must be finished before step "), upper(), string(" can begin."), ) .map(|t| (t.1, t.3)) }; sep_by(step_line(), newline()).easy_parse(input) } } #[cfg(test)] mod test { use super::*; fn get_example_step_deps() -> StepDeps { build_step_deps(&[ ('C', 'A'), ('C', 'F'), ('A', 'B'), ('A', 'D'), ('B', 'E'), ('D', 'E'), ('F', 'E'), ]) } #[test] fn test_get_available_steps() { let step_deps: StepDeps = get_example_step_deps(); assert_eq!(get_available_steps(&step_deps), vec!['C']); } #[test] fn test_do_step() { let mut step_deps: StepDeps = get_example_step_deps(); do_step('C', &mut step_deps); assert!(!step_deps.contains_key(&'C')); assert_eq!(step_deps.get(&'A'), Some(&HashSet::new())); } #[test] fn test_step_order() { let mut step_deps: StepDeps = get_example_step_deps(); assert_eq!( step_order(&mut step_deps), vec!['C', 'A', 'B', 'D', 'F', 'E'] ); } #[test] fn test_step_cost() { assert_eq!(step_cost('A', 0), 1); assert_eq!(step_cost('A', 60), 61); assert_eq!(step_cost('Z', 60), 86); } #[test] fn test_duration() { let mut step_deps: StepDeps = get_example_step_deps(); assert_eq!(duration(&mut step_deps, 2, 0), 15); } }
fn main() { // This is so sad ;-( // https://github.com/rust-lang/cargo/issues/2599 println!("cargo:rerun-if-changed=client/public/channel.html"); println!("cargo:rerun-if-changed=client/public/favicon.ico"); println!("cargo:rerun-if-changed=client/public/login.html"); println!("cargo:rerun-if-changed=client/src/assets/anonymous.png"); println!("cargo:rerun-if-changed=client/src/components/ChannelCreateOrRenameDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/ChannelDeleteDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/ChannelList.vue"); println!("cargo:rerun-if-changed=client/src/components/ChannelTitle.vue"); println!("cargo:rerun-if-changed=client/src/components/GroupCreateOrRenameDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/GroupDeleteDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/GroupLeaveDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/GroupList.vue"); println!("cargo:rerun-if-changed=client/src/components/GroupTitle.vue"); println!("cargo:rerun-if-changed=client/src/components/InviteDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/Message.vue"); println!("cargo:rerun-if-changed=client/src/components/MessageList.vue"); println!("cargo:rerun-if-changed=client/src/components/MessageSender.vue"); println!("cargo:rerun-if-changed=client/src/components/ModalDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/NoGroupsDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/Popper.vue"); println!("cargo:rerun-if-changed=client/src/components/StatusMessage.vue"); println!("cargo:rerun-if-changed=client/src/components/User.vue"); println!("cargo:rerun-if-changed=client/src/components/UserDeleteDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/UserList.vue"); println!("cargo:rerun-if-changed=client/src/components/UserRenameDialog.vue"); println!("cargo:rerun-if-changed=client/src/components/UserTitle.vue"); println!("cargo:rerun-if-changed=client/src/pages/channel/App.vue"); println!("cargo:rerun-if-changed=client/src/pages/channel/main.js"); println!("cargo:rerun-if-changed=client/vue.config.js"); let build = match std::env::var("PROFILE").unwrap().as_str() { "debug" => "build-dev", "release" => "build-prod", _ => panic!() }; let status = std::process::Command::new("npm") .arg("run") .arg(build) .current_dir("client") .status() .unwrap(); assert!(status.success()); }
use gtk::*; pub fn open_file_dialog(window: ApplicationWindow) -> Option<String> { let open_dialog = FileChooserDialog::with_buttons( "Load image", Some(&window), FileChooserAction::Open, &[ ("_Cancel", ResponseType::Cancel), ("_Open", ResponseType::Accept) ] ); open_dialog.add_filter(&create_image_filter()); let result = open_dialog.clone().run(); open_dialog.close(); match result { -3 => Some(open_dialog.get_filename()?.to_str()?.to_owned()), _ => None } } pub fn save_file_dialog(window: ApplicationWindow) -> Option<String> { let save_dialog = FileChooserDialog::with_buttons( "Save PNG image", Some(&window), FileChooserAction::Save, &[ ("_Cancel", ResponseType::Cancel), ("_Save", ResponseType::Accept) ] ); save_dialog.add_filter(&create_image_filter()); save_dialog.set_do_overwrite_confirmation(true); let result = save_dialog.clone().run(); save_dialog.close(); match result { -3 => Some(save_dialog.get_filename()?.to_str()?.to_owned()), _ => None } } fn create_image_filter() -> FileFilter { let filter = FileFilter::new(); filter.add_mime_type("image/png"); filter.add_mime_type("image/jpeg"); filter.add_mime_type("image/jpg"); filter.set_name("Image files (PNG, JPG)"); filter }
use std::sync::atomic::{AtomicUsize, Ordering}; use std::time::{Duration, Instant}; use std::{env, net}; use actix_web::{web, App, HttpRequest, HttpServer, Responder}; use tokio::time; static DEFAULT_ADDR: &str = "127.0.0.1:8080"; static COUNTER: AtomicUsize = AtomicUsize::new(0usize); async fn index(_req: HttpRequest) -> impl Responder { format!("{}", COUNTER.fetch_add(1, Ordering::SeqCst)) } async fn do_main<T: net::ToSocketAddrs>(addr: T) -> std::io::Result<()> { let handle = async { let mut instant = Instant::now(); let mut interval = time::interval(Duration::from_secs(1)); loop { interval.tick().await; let rate = COUNTER.swap(0, Ordering::SeqCst) as f64 / (instant.elapsed().as_millis() + 1) as f64 * 1000.0; instant = Instant::now(); println!("Rate: {:.3}/s", rate); } }; let server = HttpServer::new(|| App::new().service(web::resource("/").to(index))) .bind(addr)? .run(); tokio::select! { _ = handle => { println!("ticker finished"); } _ = server => { println!("server finished"); } } Ok(()) } #[actix_rt::main] async fn main() -> std::io::Result<()> { let args = env::args().collect::<Vec<_>>(); let addr = args.get(1).map(String::as_str).unwrap_or(DEFAULT_ADDR); println!("listening on {}", addr); do_main(addr).await }
use std::{io, error, iter}; use std::collections::HashSet; use xml; fn find_attr<'a>(a: &'a Vec<xml::attribute::OwnedAttribute>, n: &str) -> Result<&'a str, Box<dyn error::Error>> { a.into_iter() .find(|q| q.name.prefix.is_none() && q.name.local_name == n) .map(|f| &*f.value) .ok_or_else(|| format!("attribute not found: {:?}", n).into()) } struct Arg { name: String, typ: String, idx: i32, is_out: bool, } struct Method { name: String, fn_name: String, iargs: Vec<Arg>, oargs: Vec<Arg>, } struct Prop { name: String, get_fn_name: String, set_fn_name: String, typ: String, access: String, } struct Signal { name: String, args: Vec<Arg>, } struct Intf { origname: String, shortname: String, methods: Vec<Method>, props: Vec<Prop>, signals: Vec<Signal>, } /// Server access code generation option #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum ServerAccess { /// Supply a closure from ref to ref RefClosure, /// Supply a closure from ref to owned object which asrefs AsRefClosure, /// The interface is implemented for MethodInfo MethodInfo } #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum ConnectionType { Ffidisp, Blocking, Nonblock, } /// Code generation options #[derive(Clone, Debug)] pub struct GenOpts { /// Name of dbus crate (used for import) pub dbuscrate: String, /// MethodType for server tree impl, set to none for client impl only pub methodtype: Option<String>, /// Crossroads server handler type, set to none for client impl only pub crhandler: Option<String>, /// Removes a prefix from interface names pub skipprefix: Option<String>, /// Type of server access (tree) pub serveraccess: ServerAccess, /// Tries to make variants generic instead of Variant<Box<Refarg>> pub genericvariant: bool, /// Generates code to work with async / futures 0.3 pub futures: bool, /// Type of connection, for client only pub connectiontype: ConnectionType, /// interface filter. Only matching interface are generated, if non-empty. pub interfaces: Option<HashSet<String>>, /// The command line argument string. This will be inserted into generated source files. pub command_line: String, } impl ::std::default::Default for GenOpts { fn default() -> Self { GenOpts { dbuscrate: "dbus".into(), methodtype: Some("MTFn".into()), skipprefix: None, serveraccess: ServerAccess::RefClosure, genericvariant: false, futures: false, crhandler: None, connectiontype: ConnectionType::Blocking, interfaces: None, command_line: String::new() }} } const RUST_KEYWORDS: [&str; 57] = [ "as", "break", "const", "continue", "crate", "dyn", "else", "enum", "extern", "false", "fn", "for", "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return", "Self", "self", "static", "struct", "super", "trait", "true", "type", "union", "unsafe", "use", "where", "while", "abstract", "alignof", "async", "await", "become", "box", "do", "final", "macro", "offsetof", "override", "priv", "proc", "pure", "sizeof", "try", "typeof", "unsized", "virtual", "yield", ]; fn make_camel(s: &str) -> String { let mut ucase = true; let mut r: String = s.chars().filter_map(|c| match c { 'a'..='z' | 'A'..='Z' | '0'..='9' => { let cc = if ucase { c.to_uppercase().next() } else { Some(c) }; ucase = false; cc } _ => { ucase = true; None } }).collect(); if RUST_KEYWORDS.iter().any(|i| i == &r) { r.push('_') }; r } fn make_snake(s: &str, keyword_check: bool) -> String { let mut lcase = false; let mut r = String::new(); for c in s.chars() { match c { 'a'..='z' | '0'..='9' => { r.push(c); lcase = true; } 'A'..='Z' => { if lcase { r.push('_'); } lcase = false; r.push(c.to_lowercase().next().unwrap()); } _ => { if lcase { r.push('_'); } lcase = false; } } } if r.len() < 2 { r.push('_'); } // Don't interfere with variable names like 'm' and 'i' if keyword_check && RUST_KEYWORDS.iter().any(|i| i == &r) { r.push('_') }; r } fn make_fn_name(intf: &Intf, name: &str) -> String { let mut r = make_snake(name, true); loop { if intf.methods.iter().any(|x| x.fn_name == r) || intf.props.iter().any(|x| x.get_fn_name == r || x.set_fn_name == r) { r.push('_'); } else { return r }; } } struct GenVars { prefix: String, gen: Vec<String>, } fn xml_to_rust_type<I: Iterator<Item=char>>(i: &mut iter::Peekable<I>, out: bool, genvars: &mut Option<GenVars>) -> Result<String, Box<dyn error::Error>> { let c = i.next().ok_or_else(|| "unexpected end of signature")?; Ok(match (c, out) { ('(', _) => { let mut s: Vec<String> = vec!(); while i.peek() != Some(&')') { let n = xml_to_rust_type(i, out, genvars)?; s.push(n); }; i.next().unwrap(); format!("({})", s.join(", ")) }, ('y', _) => "u8".into(), ('b', _) => "bool".into(), ('n', _) => "i16".into(), ('q', _) => "u16".into(), ('i', _) => "i32".into(), ('u', _) => "u32".into(), ('x', _) => "i64".into(), ('t', _) => "u64".into(), ('d', _) => "f64".into(), ('h', _) => "arg::OwnedFd".into(), ('s', false) => "&str".into(), ('s', true) => "String".into(), ('o', false) => "dbus::Path".into(), ('o', true) => "dbus::Path<'static>".into(), ('g', false) => "dbus::Signature".into(), ('g', true) => "dbus::Signature<'static>".into(), ('v', _) => if let &mut Some(ref mut g) = genvars { let t = format!("{}", g.prefix); // let t = format!("arg::Variant<{}>", g.prefix); g.gen.push(g.prefix.clone()); g.prefix = format!("{}X", g.prefix); t } else if out { "arg::Variant<Box<dyn arg::RefArg + 'static>>".into() } else { "arg::Variant<Box<dyn arg::RefArg>>".into() }, ('a', _) => if i.peek() == Some(&'{') { i.next(); let n1 = xml_to_rust_type(i, out, &mut None)?; let n2 = xml_to_rust_type(i, out, &mut None)?; if i.next() != Some('}') { return Err("No end of dict".into()); } format!("::std::collections::HashMap<{}, {}>", n1, n2) } else { format!("Vec<{}>", xml_to_rust_type(i, out, &mut None)?) }, (_, _) => return Err(format!("Unknown character in signature {:?}", c).into()), }) } fn make_type(s: &str, out: bool, genvars: &mut Option<GenVars>) -> Result<String, Box<dyn error::Error>> { let mut i = s.chars().peekable(); let r = xml_to_rust_type(&mut i, out, genvars)?; if i.next().is_some() { Err("Expected type to end".into()) } else { Ok(r) } } impl Arg { fn varname(&self) -> String { if self.name != "" { make_snake(&self.name, true) } else { format!("arg{}", self.idx) } } fn can_wrap_variant(&self, genvar: bool) -> bool { genvar && self.typ.starts_with("v") } fn varname_maybewrap(&self, genvar: bool) -> String { if self.can_wrap_variant(genvar) { format!("arg::Variant({})", self.varname()) } else { self.varname() } } fn typename(&self, genvar: bool) -> Result<(String, Vec<String>), Box<dyn error::Error>> { let mut g = if genvar { Some(GenVars { prefix: format!("{}{}", if self.is_out { 'R' } else { 'I' }, self.idx), gen: vec!(), }) } else { None }; let r = make_type(&self.typ, self.is_out, &mut g)?; Ok((r, g.map(|g| g.gen.iter().map(|s| if self.is_out { format!("{}: for<'b> arg::Get<'b> + 'static", s) } else { format!("{}: arg::Arg + arg::Append", s) } ).collect()).unwrap_or(vec!()))) } fn typename_maybewrap(&self, genvar: bool) -> Result<String, Box<dyn error::Error>> { let t = self.typename(genvar)?.0; Ok(if self.can_wrap_variant(genvar) { format!("arg::Variant<{}>", t) } else { t }) } } impl Prop { fn can_get(&self) -> bool { self.access != "write" } fn can_set(&self) -> bool { self.access == "write" || self.access == "readwrite" } } fn write_method_decl(s: &mut String, m: &Method, opts: &GenOpts) -> Result<(), Box<dyn error::Error>> { let genvar = opts.genericvariant; let g: Vec<String> = if genvar { let mut g = vec!(); for z in m.iargs.iter().chain(m.oargs.iter()) { let (_, mut z) = z.typename(genvar)?; g.append(&mut z); } g } else { vec!() }; *s += &format!(" fn {}{}(&self", m.fn_name, if g.len() > 0 { format!("<{}>", g.join(",")) } else { "".into() } ); for a in m.iargs.iter() { let t = a.typename(genvar)?.0; *s += &format!(", {}: {}", a.varname(), t); } if let Some(crh) = &opts.crhandler { *s += &format!(", info: &cr::{}Info", crh) }; let r = match m.oargs.len() { 0 => "()".to_string(), 1 => m.oargs[0].typename(genvar)?.0, _ => { let v: Result<Vec<String>, _> = m.oargs.iter().map(|z| z.typename(genvar).map(|t| t.0)).collect(); format!("({})", v?.join(", ")) } }; *s += &format!(") -> {}", make_result(&r, opts)); Ok(()) } fn make_result(success: &str, opts: &GenOpts) -> String { if opts.futures { format!("dbusf::MethodReply<{}>", success) } else if opts.crhandler.is_some() { format!("Result<{}, cr::MethodErr>", success) } else if opts.methodtype.is_some() { format!("Result<{}, tree::MethodErr>", success) } else if opts.connectiontype == ConnectionType::Nonblock { format!("nonblock::MethodReply<{}>", success) } else { format!("Result<{}, dbus::Error>", success) } } fn write_prop_decl(s: &mut String, p: &Prop, opts: &GenOpts, set: bool) -> Result<(), Box<dyn error::Error>> { if set { *s += &format!(" fn {}(&self, value: {}) -> {}", p.set_fn_name, make_type(&p.typ, true, &mut None)?, make_result("()", opts)); } else { *s += &format!(" fn {}(&self) -> {}", p.get_fn_name, make_result(&make_type(&p.typ, true, &mut None)?, opts)); }; Ok(()) } fn write_intf(s: &mut String, i: &Intf, opts: &GenOpts) -> Result<(), Box<dyn error::Error>> { let iname = make_camel(&i.shortname); *s += &format!("\npub trait {} {{\n", iname); for m in &i.methods { write_method_decl(s, &m, opts)?; *s += ";\n"; } for p in &i.props { if p.can_get() { write_prop_decl(s, &p, opts, false)?; *s += ";\n"; } if p.can_set() { write_prop_decl(s, &p, opts, true)?; *s += ";\n"; } } *s += "}\n"; Ok(()) } fn write_intf_client(s: &mut String, i: &Intf, opts: &GenOpts) -> Result<(), Box<dyn error::Error>> { let (module, proxy) = match opts.connectiontype { ConnectionType::Ffidisp => ("ffidisp", "ConnPath"), ConnectionType::Blocking => ("blocking", "Proxy"), ConnectionType::Nonblock => ("nonblock", "Proxy"), }; if module == "nonblock" { *s += &format!("\nimpl<'a, T: nonblock::NonblockReply, C: ::std::ops::Deref<Target=T>> {} for {}::{}<'a, C> {{\n", make_camel(&i.shortname), module, proxy); } else if opts.futures { *s += &format!("\nimpl<'a> {} for dbusf::ConnPath<'a> {{\n", make_camel(&i.shortname)); } else if module == "blocking" { *s += &format!("\nimpl<'a, T: blocking::BlockingSender, C: ::std::ops::Deref<Target=T>> {} for {}::{}<'a, C> {{\n", make_camel(&i.shortname), module, proxy); } else { assert_eq!(module, "ffidisp"); *s += &format!("\nimpl<'a, C: ::std::ops::Deref<Target=ffidisp::Connection>> {} for ffidisp::ConnPath<'a, C> {{\n", make_camel(&i.shortname)); } for m in &i.methods { *s += "\n"; write_method_decl(s, &m, opts)?; *s += " {\n"; *s += &format!(" self.method_call(\"{}\", \"{}\", (", i.origname, m.name); for a in m.iargs.iter() { *s += &a.varname_maybewrap(opts.genericvariant); *s += ", "; } *s += "))\n"; let needs_andthen = (m.oargs.len() == 1) || (m.oargs.iter().any(|oa| oa.can_wrap_variant(opts.genericvariant))); if needs_andthen { *s += &" .and_then(|r: ("; for oa in m.oargs.iter() { *s += &oa.typename_maybewrap(opts.genericvariant)?; *s += ", "; } let tuple = m.oargs.len() > 1; *s += &format!(")| Ok({}", if tuple { "(" } else { "" }); for idx in 0..m.oargs.len() { *s += &if m.oargs[idx].can_wrap_variant(opts.genericvariant) { format!("(r.{}).0, ", idx) } else { format!("r.{}, ", idx) }; } *s += &format!("{}))\n", if tuple { ")" } else { "" }); } *s += " }\n"; } let propintf = format!("{}::stdintf::org_freedesktop_dbus::Properties", module); for p in i.props.iter().filter(|p| p.can_get()) { *s += "\n"; write_prop_decl(s, &p, opts, false)?; *s += " {\n"; *s += &format!(" <Self as {}>::get(&self, \"{}\", \"{}\")\n", propintf, i.origname, p.name); *s += " }\n"; } for p in i.props.iter().filter(|p| p.can_set()) { *s += "\n"; write_prop_decl(s, &p, opts, true)?; *s += " {\n"; *s += &format!(" <Self as {}>::set(&self, \"{}\", \"{}\", value)\n", propintf, i.origname, p.name); *s += " }\n"; } *s += "}\n"; Ok(()) } fn write_signal(s: &mut String, i: &Intf, ss: &Signal) -> Result<(), Box<dyn error::Error>> { let structname = format!("{}{}", make_camel(&i.shortname), make_camel(&ss.name)); *s += "\n#[derive(Debug)]\n"; *s += &format!("pub struct {} {{\n", structname); for a in ss.args.iter() { *s += &format!(" pub {}: {},\n", a.varname(), a.typename(false)?.0); } *s += "}\n\n"; *s += &format!("impl arg::AppendAll for {} {{\n", structname); *s += &format!(" fn append(&self, {}: &mut arg::IterAppend) {{\n", if ss.args.len() > 0 {"i"} else {"_"}); for a in ss.args.iter() { *s += &format!(" arg::RefArg::append(&self.{}, i);\n", a.varname()); } *s += " }\n"; *s += "}\n\n"; *s += &format!("impl arg::ReadAll for {} {{\n", structname); *s += &format!(" fn read({}: &mut arg::Iter) -> Result<Self, arg::TypeMismatchError> {{\n", if ss.args.len() > 0 {"i"} else {"_"}); *s += &format!(" Ok({} {{\n", structname); for a in ss.args.iter() { *s += &format!(" {}: i.read()?,\n", a.varname()); } *s += " })\n"; *s += " }\n"; *s += "}\n\n"; *s += &format!("impl dbus::message::SignalArgs for {} {{\n", structname); *s += &format!(" const NAME: &'static str = \"{}\";\n", ss.name); *s += &format!(" const INTERFACE: &'static str = \"{}\";\n", i.origname); *s += "}\n"; Ok(()) } fn write_signals(s: &mut String, i: &Intf) -> Result<(), Box<dyn error::Error>> { for ss in i.signals.iter() { write_signal(s, i, ss)?; } Ok(()) } fn write_server_access(s: &mut String, i: &Intf, saccess: ServerAccess, minfo_is_ref: bool) { let z = if minfo_is_ref {""} else {"&"}; match saccess { ServerAccess::AsRefClosure => { *s += &format!(" let dd = fclone({}minfo);\n", z); *s += " let d = dd.as_ref();\n"; }, ServerAccess::RefClosure => *s += &format!(" let d = fclone({}minfo);\n", z), ServerAccess::MethodInfo => *s += &format!(" let d: &dyn {} = {}minfo;\n", make_camel(&i.shortname), z), } } // Should we implement this for // 1) MethodInfo? That's the only way receiver can check Sender, etc - ServerAccess::MethodInfo // 2) D::ObjectPath? // 3) A user supplied struct? // 4) Something reachable from minfo - ServerAccess::RefClosure fn write_intf_tree(s: &mut String, i: &Intf, mtype: &str, saccess: ServerAccess, genvar: bool) -> Result<(), Box<dyn error::Error>> { let hasf = saccess != ServerAccess::MethodInfo; let hasm = mtype == "MethodType"; let treem: String = if hasm { "M".into() } else { format!("tree::{}<D>", mtype) }; *s += &format!("\npub fn {}_server<{}{}D>(factory: &tree::Factory<{}, D>, data: D::Interface{}) -> tree::Interface<{}, D>\n", make_snake(&i.shortname, false), if hasf {"F, T, "} else {""}, if hasm {"M, "} else {""}, treem, if hasf {", f: F"} else {""}, treem); let mut wheres: Vec<String> = vec!["D: tree::DataType".into(), "D::Method: Default".into()]; if i.props.len() > 0 { wheres.push("D::Property: Default".into()); }; if i.signals.len() > 0 { wheres.push("D::Signal: Default".into()); }; if hasm { wheres.push("M: MethodType<D>".into()); }; match saccess { ServerAccess::RefClosure => { wheres.push(format!("T: {}", make_camel(&i.shortname))); wheres.push(format!("F: 'static + for <'z> Fn(& 'z tree::MethodInfo<tree::{}<D>, D>) -> & 'z T", mtype)); }, ServerAccess::AsRefClosure => { wheres.push(format!("T: AsRef<dyn {}>", make_camel(&i.shortname))); wheres.push(format!("F: 'static + Fn(&tree::MethodInfo<tree::{}<D>, D>) -> T", mtype)); }, ServerAccess::MethodInfo => {}, }; if let ServerAccess::RefClosure | ServerAccess::AsRefClosure = saccess { if mtype == "MTSync" { wheres.push("F: Send + Sync".into()); } } *s += "where\n"; for w in wheres { *s += &format!(" {},\n", w); } *s += "{\n"; *s += &format!(" let i = factory.interface(\"{}\", data);\n", i.origname); if hasf { *s += " let f = ::std::sync::Arc::new(f);"; } for m in &i.methods { if hasf { *s += "\n let fclone = f.clone();\n"; } *s += &format!(" let h = move |minfo: &tree::MethodInfo<{}, D>| {{\n", treem); if m.iargs.len() > 0 { *s += " let mut i = minfo.msg.iter_init();\n"; } for a in &m.iargs { *s += &format!(" let {}: {} = i.read()?;\n", a.varname(), a.typename(genvar)?.0); } write_server_access(s, i, saccess, true); let argsvar = m.iargs.iter().map(|q| q.varname()).collect::<Vec<String>>().join(", "); let retargs = match m.oargs.len() { 0 => String::new(), 1 => format!("let {} = ", m.oargs[0].varname()), _ => format!("let ({}) = ", m.oargs.iter().map(|q| q.varname()).collect::<Vec<String>>().join(", ")), }; *s += &format!(" {}d.{}({})?;\n", retargs, m.fn_name, argsvar); *s += " let rm = minfo.msg.method_return();\n"; for r in &m.oargs { *s += &format!(" let rm = rm.append1({});\n", r.varname()); } *s += " Ok(vec!(rm))\n"; *s += " };\n"; *s += &format!(" let m = factory.method{}(\"{}\", Default::default(), h);\n", if hasm {"_sync"} else {""}, m.name); for a in &m.iargs { *s += &format!(" let m = m.in_arg((\"{}\", \"{}\"));\n", a.name, a.typ); } for a in &m.oargs { *s += &format!(" let m = m.out_arg((\"{}\", \"{}\"));\n", a.name, a.typ); } *s += " let i = i.add_m(m);\n"; } for p in &i.props { *s += &format!("\n let p = factory.property::<{}, _>(\"{}\", Default::default());\n", make_type(&p.typ, false, &mut None)?, p.name); *s += &format!(" let p = p.access(tree::Access::{});\n", match &*p.access { "read" => "Read", "readwrite" => "ReadWrite", "write" => "Write", _ => return Err(format!("Unexpected access value {}", p.access).into()), }); if p.can_get() { if hasf { *s += " let fclone = f.clone();\n"; } *s += " let p = p.on_get(move |a, pinfo| {\n"; *s += " let minfo = pinfo.to_method_info();\n"; write_server_access(s, i, saccess, false); *s += &format!(" a.append(d.{}()?);\n", &p.get_fn_name); *s += " Ok(())\n"; *s += " });\n"; } if p.can_set() { if hasf { *s += " let fclone = f.clone();\n"; } *s += " let p = p.on_set(move |iter, pinfo| {\n"; *s += " let minfo = pinfo.to_method_info();\n"; write_server_access(s, i, saccess, false); *s += &format!(" d.{}(iter.read()?)?;\n", &p.set_fn_name); *s += " Ok(())\n"; *s += " });\n"; } *s += " let i = i.add_p(p);\n"; } for ss in &i.signals { *s += &format!(" let s = factory.signal(\"{}\", Default::default());\n", ss.name); for a in &ss.args { *s += &format!(" let s = s.arg((\"{}\", \"{}\"));\n", a.name, a.typ); } *s += " let i = i.add_s(s);\n"; } *s += " i\n"; *s += "}\n"; Ok(()) } fn write_intf_crossroads(s: &mut String, i: &Intf, opts: &GenOpts) -> Result<(), Box<dyn error::Error>> { let crh = opts.crhandler.as_ref().unwrap(); *s += &format!("\npub fn {}_ifaceinfo<I>() -> cr::IfaceInfo<'static, cr::{}>\n", make_snake(&i.shortname, false), crh); *s += &format!("where I: {}{} {{\n", make_camel(&i.shortname), if crh == "Par" { " + Send + Sync + 'static" } else { "" }); *s += &format!(" cr::IfaceInfo::new(\"{}\", vec!(\n", i.origname); for m in &i.methods { *s += &format!(" MethodInfo::new_{}(\"{}\", |intf: &I, info| {{\n", crh.to_lowercase(), m.name); if m.iargs.len() > 0 { *s += " let mut i = info.msg().iter_init();\n"; } for a in &m.iargs { *s += &format!(" let {}: {} = i.read()?;\n", a.varname(), a.typename(opts.genericvariant)?.0); } let mut argsvar: Vec<_> = m.iargs.iter().map(|q| q.varname()).collect(); argsvar.push("info".into()); let argsvar = argsvar.join(", "); let retargs = match m.oargs.len() { 0 => String::new(), 1 => format!("let {} = ", m.oargs[0].varname()), _ => format!("let ({}) = ", m.oargs.iter().map(|q| q.varname()).collect::<Vec<String>>().join(", ")), }; *s += &format!(" {}intf.{}({})?;\n", retargs, m.fn_name, argsvar); *s += " let rm = info.msg().method_return();\n"; for r in &m.oargs { *s += &format!(" let rm = rm.append1({});\n", r.varname()); } *s += " Ok(Some(rm))\n"; *s += " }),\n"; } *s += " ), vec!(), vec!())\n"; // TODO: Props, signals *s += "}\n"; Ok(()) } fn write_module_header(s: &mut String, opts: &GenOpts) { *s += &format!("// This code was autogenerated with `dbus-codegen-rust {}`, see https://github.com/diwic/dbus-rs\n", opts.command_line); *s += &format!("use {} as dbus;\n", opts.dbuscrate); *s += "#[allow(unused_imports)]\n"; *s += &format!("use {}::arg;\n", opts.dbuscrate); if opts.futures { *s += "use dbus_futures as dbusf;\n"; } if opts.methodtype.is_some() { *s += &format!("use {}_tree as tree;\n", opts.dbuscrate) } else { *s += &format!("use {}::{};\n", opts.dbuscrate, match opts.connectiontype { ConnectionType::Ffidisp => "ffidisp", ConnectionType::Blocking => "blocking", ConnectionType::Nonblock => "nonblock", }); } if opts.crhandler.is_some() { *s += &format!("use {}::crossroads as cr;\n", opts.dbuscrate) } } /// Generates Rust structs and traits from D-Bus XML introspection data. pub fn generate(xmldata: &str, opts: &GenOpts) -> Result<String, Box<dyn error::Error>> { use xml::EventReader; use xml::reader::XmlEvent; let mut s = String::new(); write_module_header(&mut s, opts); let mut curintf = None; let mut curm = None; let mut cursig = None; let mut curprop = None; let parser = EventReader::new(io::Cursor::new(xmldata)); for e in parser { match e? { XmlEvent::StartElement { ref name, .. } if name.prefix.is_some() => (), XmlEvent::EndElement { ref name, .. } if name.prefix.is_some() => (), XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "interface" => { if curm.is_some() { Err("Start of Interface inside method")? }; if curintf.is_some() { Err("Start of Interface inside interface")? }; let n = find_attr(attributes, "name")?; let mut n2 = n; if let &Some(ref p) = &opts.skipprefix { if n.len() > p.len() && n.starts_with(p) { n2 = &n[p.len()..]; } } curintf = Some(Intf { origname: n.into(), shortname: n2.into(), methods: Vec::new(), signals: Vec::new(), props: Vec::new() }); } XmlEvent::EndElement { ref name } if &name.local_name == "interface" => { if curm.is_some() { Err("End of Interface inside method")? }; if curintf.is_none() { Err("End of Interface outside interface")? }; let intf = curintf.take().unwrap(); // If filters are set and no filter matches -> Just print a message and continue parsing if let Some(filter) = &opts.interfaces { if !filter.contains(&intf.shortname) && !filter.contains(&intf.origname) { eprintln!("Skip filtered interface '{}'", &intf.shortname); continue; } } write_intf(&mut s, &intf, opts)?; if opts.crhandler.is_some() { write_intf_crossroads(&mut s, &intf, opts)?; } else if let Some(ref mt) = opts.methodtype { write_intf_tree(&mut s, &intf, &mt, opts.serveraccess, opts.genericvariant)?; } else { write_intf_client(&mut s, &intf, opts)?; } write_signals(&mut s, &intf)?; } XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "method" => { if curm.is_some() { Err("Start of method inside method")? }; if curintf.is_none() { Err("Start of method outside interface")? }; let name = find_attr(attributes, "name")?; curm = Some(Method { name: name.into(), fn_name: make_fn_name(curintf.as_ref().unwrap(), name), iargs: Vec::new(), oargs: Vec::new() }); } XmlEvent::EndElement { ref name } if &name.local_name == "method" => { if curm.is_none() { Err("End of method outside method")? }; if curintf.is_none() { Err("End of method outside interface")? }; curintf.as_mut().unwrap().methods.push(curm.take().unwrap()); } XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "signal" => { if cursig.is_some() { Err("Start of signal inside signal")? }; if curintf.is_none() { Err("Start of signal outside interface")? }; cursig = Some(Signal { name: find_attr(attributes, "name")?.into(), args: Vec::new() }); } XmlEvent::EndElement { ref name } if &name.local_name == "signal" => { if cursig.is_none() { Err("End of signal outside signal")? }; if curintf.is_none() { Err("End of signal outside interface")? }; curintf.as_mut().unwrap().signals.push(cursig.take().unwrap()); } XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "property" => { if curprop.is_some() { Err("Start of property inside property")? }; if curintf.is_none() { Err("Start of property outside interface")? }; let name = find_attr(attributes, "name")?; let get_fn_name = make_fn_name(curintf.as_ref().unwrap(), name); let set_fn_name = make_fn_name(curintf.as_ref().unwrap(), &format!("Set{}", name)); curprop = Some(Prop { name: name.into(), typ: find_attr(attributes, "type")?.into(), access: find_attr(attributes, "access")?.into(), get_fn_name: get_fn_name, set_fn_name: set_fn_name, }); } XmlEvent::EndElement { ref name } if &name.local_name == "property" => { if curprop.is_none() { Err("End of property outside property")? }; if curintf.is_none() { Err("End of property outside interface")? }; curintf.as_mut().unwrap().props.push(curprop.take().unwrap()); } XmlEvent::StartElement { ref name, ref attributes, .. } if &name.local_name == "arg" => { if curm.is_none() && cursig.is_none() { Err("Start of arg outside method and signal")? }; if curintf.is_none() { Err("Start of arg outside interface")? }; let typ = find_attr(attributes, "type")?.into(); let is_out = if cursig.is_some() { true } else { match find_attr(attributes, "direction") { Err(_) => false, Ok("in") => false, Ok("out") => true, _ => { Err("Invalid direction")?; unreachable!() } }}; let arr = if let Some(ref mut sig) = cursig { &mut sig.args } else if is_out { &mut curm.as_mut().unwrap().oargs } else { &mut curm.as_mut().unwrap().iargs }; let arg = Arg { name: find_attr(attributes, "name").unwrap_or("").into(), typ: typ, is_out: is_out, idx: arr.len() as i32 }; arr.push(arg); } _ => (), } } if curintf.is_some() { Err("Unterminated interface")? } Ok(s) } #[cfg(test)] mod tests { use super::{generate, GenOpts}; static FROM_DBUS: &'static str = r#" <!DOCTYPE node PUBLIC "-//freedesktop//DTD D-BUS Object Introspection 1.0//EN" "http://www.freedesktop.org/standards/dbus/1.0/introspect.dtd"> <node> <interface name="org.freedesktop.DBus"> <method name="Hello"> <arg direction="out" type="s"/> </method> <method name="RequestName"> <arg direction="in" type="s"/> <arg direction="in" type="u"/> <arg direction="out" type="u"/> </method> <method name="ReleaseName"> <arg direction="in" type="s"/> <arg direction="out" type="u"/> </method> <method name="StartServiceByName"> <arg direction="in" type="s"/> <arg direction="in" type="u"/> <arg direction="out" type="u"/> </method> <method name="UpdateActivationEnvironment"> <arg direction="in" type="a{ss}"/> </method> <method name="NameHasOwner"> <arg direction="in" type="s"/> <arg direction="out" type="b"/> </method> <method name="ListNames"> <arg direction="out" type="as"/> </method> <method name="ListActivatableNames"> <arg direction="out" type="as"/> </method> <method name="AddMatch"> <arg direction="in" type="s"/> </method> <method name="RemoveMatch"> <arg direction="in" type="s"/> </method> <method name="GetNameOwner"> <arg direction="in" type="s"/> <arg direction="out" type="s"/> </method> <method name="ListQueuedOwners"> <arg direction="in" type="s"/> <arg direction="out" type="as"/> </method> <method name="GetConnectionUnixUser"> <arg direction="in" type="s"/> <arg direction="out" type="u"/> </method> <method name="GetConnectionUnixProcessID"> <arg direction="in" type="s"/> <arg direction="out" type="u"/> </method> <method name="GetAdtAuditSessionData"> <arg direction="in" type="s"/> <arg direction="out" type="ay"/> </method> <method name="GetConnectionSELinuxSecurityContext"> <arg direction="in" type="s"/> <arg direction="out" type="ay"/> </method> <method name="GetConnectionAppArmorSecurityContext"> <arg direction="in" type="s"/> <arg direction="out" type="s"/> </method> <method name="ReloadConfig"> </method> <method name="GetId"> <arg direction="out" type="s"/> </method> <method name="GetConnectionCredentials"> <arg direction="in" type="s"/> <arg direction="out" type="a{sv}"/> </method> <signal name="NameOwnerChanged"> <arg type="s"/> <arg type="s"/> <arg type="s"/> </signal> <signal name="NameLost"> <arg type="s"/> </signal> <signal name="NameAcquired"> <arg type="s"/> </signal> </interface> <interface name="org.freedesktop.DBus.Introspectable"> <method name="Introspect"> <arg direction="out" type="s"/> </method> </interface> <interface name="org.freedesktop.DBus.Monitoring"> <method name="BecomeMonitor"> <arg direction="in" type="as"/> <arg direction="in" type="u"/> </method> </interface> <interface name="org.freedesktop.DBus.Debug.Stats"> <method name="GetStats"> <arg direction="out" type="a{sv}"/> </method> <method name="GetConnectionStats"> <arg direction="in" type="s"/> <arg direction="out" type="a{sv}"/> </method> <method name="GetAllMatchRules"> <arg direction="out" type="a{sas}"/> </method> </interface> </node> "#; #[test] fn from_dbus() { let s = generate(FROM_DBUS, &GenOpts { methodtype: Some("MTSync".into()), ..Default::default() }).unwrap(); println!("{}", s); //assert_eq!(s, "fdjsf"); } }
#![cfg(target_family = "unix")] /// TODO: Would be better to use linux low level tty /// [Reference of low level api](https://linux.die.net/man/4/tty)
#[cfg(any(unix, macos))] use rscam; use crate::camera::CameraProvider; use std::vec::*; use std::fs; use std::io::Write; use std::sync::Arc; use bytes::buf::BufMut; pub struct PiCamera { width: usize, height: usize, frame_rate: usize, device : rscam::Camera, first_frame: Arc<Vec<u8>> } unsafe impl Send for PiCamera{} unsafe impl Sync for PiCamera{} impl PiCamera{ pub fn new(width: usize, height: usize, frame_rate: usize) -> Self { let w=width as u32; let h=height as u32; let mut camera = rscam::new("/dev/video0").unwrap(); camera.start(&rscam::Config { interval: (1, frame_rate as u32), // Try to run at 60 fps. resolution: (w, h), format: b"MJPG", ..Default::default() }).unwrap(); println!("PiCamera initialized."); let mut header=Vec::new(); for i in 1..10{ let frame=camera.capture().unwrap(); header.put_slice(&frame[..]); } PiCamera{width, height, frame_rate, device: camera, first_frame: Arc::new(header)} } } impl CameraProvider for PiCamera { fn capture_zerocopy(&mut self, target: &mut Vec<u8>) -> Option<()> { let frame=self.device.capture().unwrap(); target.put(&frame[..]); Some(()) } fn h264_header(&self)->Arc<Vec<u8>>{ Arc::clone(&self.first_frame) } }
use crate::{ time::{TimePoint, TimePointSec}, NumBytes, Read, Write, }; /// This class is used in the block headers to represent the block time /// It is a parameterised class that takes an Epoch in milliseconds and /// and an interval in milliseconds and computes the number of slots. #[derive( Read, Write, NumBytes, PartialEq, Eq, PartialOrd, Ord, Debug, Clone, Copy, Hash, Default, )] #[eosio(crate_path = "crate::bytes")] pub struct BlockTimestamp { pub slot: u32, } impl BlockTimestamp { /// Milliseconds between blocks. pub const INTERVAL_MS: i32 = 500; /// Epoch is 2000-01-01T00:00.000Z. pub const EPOCH: i64 = 946_684_800_000; } impl From<u32> for BlockTimestamp { #[inline] #[must_use] fn from(i: u32) -> Self { Self { slot: i } } } impl From<BlockTimestamp> for u32 { #[inline] #[must_use] fn from(t: BlockTimestamp) -> Self { t.slot } } impl From<TimePoint> for BlockTimestamp { #[inline] fn from(tp: TimePoint) -> Self { let millis = tp.as_millis() - Self::EPOCH; let slot = millis.max(0) / i64::from(Self::INTERVAL_MS); let slot = slot as u32; Self { slot } } } impl From<BlockTimestamp> for TimePoint { #[inline] fn from(bt: BlockTimestamp) -> Self { let millis = i64::from(bt.slot) * i64::from(BlockTimestamp::INTERVAL_MS) + BlockTimestamp::EPOCH; Self::from_millis(millis) } } impl From<TimePointSec> for BlockTimestamp { #[inline] fn from(tps: TimePointSec) -> Self { let millis = i64::from(tps.as_secs()) * 1_000 - Self::EPOCH; let slot = millis / i64::from(Self::INTERVAL_MS); let slot = slot as u32; Self { slot } } } // #[cfg(test)] // #[test] // fn test_from_time_point_sec() {} impl From<BlockTimestamp> for TimePointSec { #[inline] fn from(bt: BlockTimestamp) -> Self { let millis = i64::from(bt.slot) * i64::from(BlockTimestamp::INTERVAL_MS) + BlockTimestamp::EPOCH; let secs = millis * 1_000; Self::from_secs(secs as u32) } } // #[cfg(test)] // mod tests { // use super::*; // #[test] // fn from_time_point() { // let test_cases = vec![ // (0, 0), // (BlockTimestamp::EPOCH, 0), // ( // BlockTimestamp::EPOCH // + i64::from(BlockTimestamp::INTERVAL_MS) * 10, // 10, // ), // ( // BlockTimestamp::EPOCH // + i64::from(BlockTimestamp::INTERVAL_MS) * 100, // 100, // ), // ( // BlockTimestamp::EPOCH // + i64::from(BlockTimestamp::INTERVAL_MS) * 10 // + 255, // 10, // ), // ]; // for (millis, slot) in test_cases { // let tp = TimePoint::from_millis(millis); // assert_eq!(BlockTimestamp { slot }, BlockTimestamp::from(tp)); // } // } // #[test] // fn to_time_point() { // let test_cases = vec![ // (0, BlockTimestamp::EPOCH), // ( // 1, // BlockTimestamp::EPOCH + i64::from(BlockTimestamp::INTERVAL_MS), // ), // ( // 10, // BlockTimestamp::EPOCH // + i64::from(BlockTimestamp::INTERVAL_MS) * 10, // ), // ]; // for (slot, millis) in test_cases { // let bt = BlockTimestamp { slot }; // assert_eq!(TimePoint::from_millis(millis), TimePoint::from(bt)); // } // } // #[test] // fn to_time_point_sec() { // let test_cases = vec![ // (0, BlockTimestamp::EPOCH), // ( // 1, // BlockTimestamp::EPOCH + i64::from(BlockTimestamp::INTERVAL_MS), // ), // ( // 10, // BlockTimestamp::EPOCH // + i64::from(BlockTimestamp::INTERVAL_MS) * 10, // ), // ]; // for (slot, millis) in test_cases { // let bt = BlockTimestamp { slot }; // let secs = millis / 1_000; // let secs = secs as u32; // assert_eq!(TimePointSec::from_secs(secs), TimePointSec::from(bt)); // } // } // }
fn main() { let mut v1 = vec![1,2,3]; let mut v2:Vec<i32> = vec![]; let x1 = v1.pop(); let x2 = v2.pop(); println!("x1={:?}, x2={:?}", x1, x2); }
#![cfg_attr(feature = "lints", allow(unstable_features))] #![cfg_attr(feature = "lints", feature(plugin))] #![cfg_attr(feature = "lints", plugin(clippy))] extern crate chrono; extern crate term; // TODO consolidate term, ansi_term and terminal_size extern crate open; extern crate icalendar; #[cfg(feature="shell")] extern crate rustyline; #[cfg(feature="document_export")] extern crate rustc_serialize; extern crate env_logger; #[macro_use] extern crate log; #[macro_use] extern crate clap; #[macro_use] extern crate prettytable; extern crate asciii; use std::env; use log::{LogRecord, LogLevelFilter}; use env_logger::LogBuilder; pub mod cli; use cli::match_matches; pub mod manual; fn setup_log(){ let format = |record: &LogRecord| { format!("{level}: {args}", level = record.level(), args = record.args()) }; let mut builder = LogBuilder::new(); builder.format(format).filter(None, LogLevelFilter::Info); let log_var ="ASCIII_LOG"; if env::var(log_var).is_ok() { builder.parse(&env::var(log_var).unwrap()); } builder.init().unwrap(); } fn main(){ setup_log(); trace!("setting up app"); let matches = cli::build_cli().get_matches(); match_matches(&matches); }
pub mod pe_001; pub mod pe_002; pub mod pe_003; pub mod pe_004; pub mod pe_005; pub mod pe_006; pub mod pe_007; pub mod pe_008; pub mod aoc_001; pub mod aoc_002; pub mod aoc_003;
extern crate byteorder; use std::{io, fs}; use std::io::BufRead; use byteorder::{LittleEndian, ReadBytesExt}; extern crate yahtzeevalue; use yahtzeevalue::*; use yahtzeevalue::constants::*; fn read_state_value() -> io::Result<Vec<f64>> { let file = fs::File::open("state_value.bin")?; let size = file.metadata()?.len() as usize; let mut reader = io::BufReader::new(file); let mut state_value = vec![0f64; size / 8]; for x in state_value.iter_mut() { *x = reader.read_f64::<LittleEndian>()?; } Ok(state_value) } fn precompute_state(state: State) -> bool { let t = state.turn_count(); t % 2 == 0 && t != 8 && t != 10 } fn main() { let all_state_value = read_state_value().expect("Failed to read state value"); let mut state_value_map = Vec::new(); for (i, &v) in all_state_value.iter().enumerate() { if precompute_state(State::decode(i as u32)) { state_value_map.push((i, v)); } } }
extern crate rand; extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; mod pong; mod game_object; fn main() { pong::play(); }
pub mod connection { mod codec { use byteorder::{BigEndian, ByteOrder, WriteBytesExt}; use shannon::Shannon; use std::io; use tokio_core::io::{Codec, EasyBuf}; const HEADER_SIZE: usize = 3; const MAC_SIZE: usize = 4; #[derive(Debug)] enum DecodeState { Header, Payload(u8, usize), } pub struct APCodec { encode_nonce: u32, encode_cipher: Shannon, decode_nonce: u32, decode_cipher: Shannon, decode_state: DecodeState, } impl APCodec { pub fn new(send_key: &[u8], recv_key: &[u8]) -> APCodec { APCodec{encode_nonce: 0, encode_cipher: Shannon::new(send_key), decode_nonce: 0, decode_cipher: Shannon::new(recv_key), decode_state: DecodeState::Header,} } } impl Codec for APCodec { type Out = (u8, Vec<u8>); type In = (u8, EasyBuf); fn encode(&mut self, item: (u8, Vec<u8>), buf: &mut Vec<u8>) -> io::Result<()> { let (cmd, payload) = item; let offset = buf.len(); buf.write_u8(cmd).unwrap(); buf.write_u16::<BigEndian>(payload.len() as u16).unwrap(); buf.extend_from_slice(&payload); self.encode_cipher.nonce_u32(self.encode_nonce); self.encode_nonce += 1; self.encode_cipher.encrypt(&mut buf[offset..]); let mut mac = [0u8; MAC_SIZE]; self.encode_cipher.finish(&mut mac); buf.extend_from_slice(&mac); Ok(()) } fn decode(&mut self, buf: &mut EasyBuf) -> io::Result<Option<(u8, EasyBuf)>> { if let DecodeState::Header = self.decode_state { if buf.len() >= HEADER_SIZE { let mut header = [0u8; HEADER_SIZE]; header.copy_from_slice(buf.drain_to(HEADER_SIZE).as_slice()); self.decode_cipher.nonce_u32(self.decode_nonce); self.decode_nonce += 1; self.decode_cipher.decrypt(&mut header); let cmd = header[0]; let size = BigEndian::read_u16(&header[1..]) as usize; self.decode_state = DecodeState::Payload(cmd, size); } } if let DecodeState::Payload(cmd, size) = self.decode_state { if buf.len() >= size + MAC_SIZE { self.decode_state = DecodeState::Header; let mut payload = buf.drain_to(size + MAC_SIZE); self.decode_cipher.decrypt(&mut payload.get_mut()[..size]); let mac = payload.split_off(size); self.decode_cipher.check_mac(mac.as_slice())?; return Ok(Some((cmd, payload))); } } Ok(None) } } } mod handshake { use crypto::sha1::Sha1; use crypto::hmac::Hmac; use crypto::mac::Mac; use byteorder::{BigEndian, ByteOrder, WriteBytesExt}; use protobuf::{self, Message, MessageStatic}; use rand::thread_rng; use std::io::{self, Read, Write}; use std::marker::PhantomData; use tokio_core::io::{Io, Framed, write_all, WriteAll, read_exact, ReadExact, Window}; use futures::{Poll, Async, Future}; use diffie_hellman::DHLocalKeys; use protocol; use protocol::keyexchange::{ClientHello, APResponseMessage, ClientResponsePlaintext}; use util; use super::codec::APCodec; pub struct Handshake<T> { keys: DHLocalKeys, state: HandshakeState<T>, } enum HandshakeState<T> { ClientHello(WriteAll<T, Vec<u8>>), APResponse(RecvPacket<T, APResponseMessage>), ClientResponse(Option<APCodec>, WriteAll<T, Vec<u8>>), } pub fn handshake<T: Io>(connection: T) -> Handshake<T> { let local_keys = DHLocalKeys::random(&mut thread_rng()); let client_hello = client_hello(connection, local_keys.public_key()); Handshake{keys: local_keys, state: HandshakeState::ClientHello(client_hello),} } impl <T: Io> Future for Handshake<T> { type Item = Framed<T, APCodec>; type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, io::Error> { use self::HandshakeState::*; loop { self.state = match self.state { ClientHello(ref mut write) => { let (connection, accumulator) = try_ready!(write . poll ( )); let read = recv_packet(connection, accumulator); APResponse(read) } APResponse(ref mut read) => { let (connection, message, accumulator) = try_ready!(read . poll ( )); let remote_key = message.get_challenge().get_login_crypto_challenge().get_diffie_hellman().get_gs().to_owned(); let shared_secret = self.keys.shared_secret(&remote_key); let (challenge, send_key, recv_key) = compute_keys(&shared_secret, &accumulator); let codec = APCodec::new(&send_key, &recv_key); let write = client_response(connection, challenge); ClientResponse(Some(codec), write) } ClientResponse(ref mut codec, ref mut write) => { let (connection, _) = try_ready!(write . poll ( )); let codec = codec.take().unwrap(); let framed = connection.framed(codec); return Ok(Async::Ready(framed)); } } } } } fn client_hello<T: Write>(connection: T, gc: Vec<u8>) -> WriteAll<T, Vec<u8>> { let packet = { let mut msg = ClientHello::new(); { let mut msg = msg.mut_build_info(); msg.set_product(protocol::keyexchange::Product::PRODUCT_PARTNER); msg.set_platform(protocol::keyexchange::Platform::PLATFORM_LINUX_X86); msg.set_version(1133871366144); msg }; { let repeated = msg.mut_cryptosuites_supported(); repeated.push(protocol::keyexchange::Cryptosuite::CRYPTO_SUITE_SHANNON) }; { let mut msg = msg.mut_login_crypto_hello().mut_diffie_hellman(); msg.set_gc(gc); msg.set_server_keys_known(1); msg }; msg.set_client_nonce(util::rand_vec(&mut thread_rng(), 16)); msg.set_padding(vec!(0x1e)); msg }; let mut buffer = vec!(0 , 4); let size = 2 + 4 + packet.compute_size(); buffer.write_u32::<BigEndian>(size).unwrap(); packet.write_to_vec(&mut buffer).unwrap(); write_all(connection, buffer) } fn client_response<T: Write>(connection: T, challenge: Vec<u8>) -> WriteAll<T, Vec<u8>> { let packet = { let mut msg = ClientResponsePlaintext::new(); { let mut msg = msg.mut_login_crypto_response().mut_diffie_hellman(); msg.set_hmac(challenge); msg }; msg.mut_pow_response(); msg.mut_crypto_response(); msg }; let mut buffer = vec!(); let size = 4 + packet.compute_size(); buffer.write_u32::<BigEndian>(size).unwrap(); packet.write_to_vec(&mut buffer).unwrap(); write_all(connection, buffer) } enum RecvPacket<T, M: MessageStatic> { Header(ReadExact<T, Window<Vec<u8>>>, PhantomData<M>), Body(ReadExact<T, Window<Vec<u8>>>, PhantomData<M>), } fn recv_packet<T, M>(connection: T, acc: Vec<u8>) -> RecvPacket<T, M> where T: Read, M: MessageStatic { RecvPacket::Header(read_into_accumulator(connection, 4, acc), PhantomData) } impl <T, M> Future for RecvPacket<T, M> where T: Read, M: MessageStatic { type Item = (T, M, Vec<u8>); type Error = io::Error; fn poll(&mut self) -> Poll<Self::Item, io::Error> { use self::RecvPacket::*; loop { *self = match *self { Header(ref mut read, _) => { let (connection, header) = try_ready!(read . poll ( )); let size = BigEndian::read_u32(header.as_ref()) as usize; let acc = header.into_inner(); let read = read_into_accumulator(connection, size - 4, acc); RecvPacket::Body(read, PhantomData) } Body(ref mut read, _) => { let (connection, data) = try_ready!(read . poll ( )); let message = protobuf::parse_from_bytes(data.as_ref()).unwrap(); let acc = data.into_inner(); return Ok(Async::Ready((connection, message, acc))); } } } } } fn read_into_accumulator<T: Read>(connection: T, size: usize, mut acc: Vec<u8>) -> ReadExact<T, Window<Vec<u8>>> { let offset = acc.len(); acc.resize(offset + size, 0); let mut window = Window::new(acc); window.set_start(offset); read_exact(connection, window) } fn compute_keys(shared_secret: &[u8], packets: &[u8]) -> (Vec<u8>, Vec<u8>, Vec<u8>) { let mut data = Vec::with_capacity(100); let mut mac = Hmac::new(Sha1::new(), &shared_secret); for i in 1..6 { mac.input(packets); mac.input(&[i]); data.extend_from_slice(&mac.result().code()); mac.reset(); } mac = Hmac::new(Sha1::new(), &data[..20]); mac.input(packets); (mac.result().code().to_vec(), data[20..52].to_vec(), data[52..84].to_vec()) } } pub use self::codec::APCodec; pub use self::handshake::handshake; use futures::{Future, Sink, Stream, BoxFuture}; use std::io; use std::net::ToSocketAddrs; use tokio_core::net::TcpStream; use tokio_core::reactor::Handle; use tokio_core::io::Framed; use protobuf::{self, Message}; use authentication::Credentials; use version; pub type Transport = Framed<TcpStream, APCodec>; pub fn connect<A: ToSocketAddrs>(addr: A, handle: &Handle) -> BoxFuture<Transport, io::Error> { let addr = addr.to_socket_addrs().unwrap().next().unwrap(); let socket = TcpStream::connect(&addr, handle); let connection = socket.and_then(|socket| { handshake(socket) }); connection.boxed() } pub fn authenticate(transport: Transport, credentials: Credentials, device_id: String) -> BoxFuture<(Transport, Credentials), io::Error> { use protocol::authentication::{APWelcome, ClientResponseEncrypted, CpuFamily, Os}; let packet = { let mut msg = ClientResponseEncrypted::new(); { let mut msg = msg.mut_login_credentials(); msg.set_username(credentials.username); msg.set_typ(credentials.auth_type); msg.set_auth_data(credentials.auth_data); msg }; { let mut msg = msg.mut_system_info(); msg.set_cpu_family(CpuFamily::CPU_UNKNOWN); msg.set_os(Os::OS_UNKNOWN); msg.set_system_information_string("librespot".to_owned()); msg.set_device_id(device_id); msg }; msg.set_version_string(version::version_string()); msg }; let cmd = 171; let data = packet.write_to_bytes().unwrap(); transport.send((cmd, data)).and_then(|transport| { transport.into_future().map_err(|(err, _stream)| err) }).and_then(|(packet, transport)| { match packet { Some((172, data)) => { let welcome_data: APWelcome = protobuf::parse_from_bytes(data.as_ref()).unwrap(); let reusable_credentials = Credentials{username: welcome_data.get_canonical_username().to_owned(), auth_type: welcome_data.get_reusable_auth_credentials_type(), auth_data: welcome_data.get_reusable_auth_credentials().to_owned(),}; Ok((transport, reusable_credentials)) } Some((173, _)) => panic!("Authentication failed"), Some((cmd, _)) => panic!("Unexpected packet {:?}" , cmd), None => panic!("EOF"), } }).boxed() } } pub mod spirc { use futures::future; use futures::sink::BoxSink; use futures::stream::BoxStream; use futures::sync::{oneshot, mpsc}; use futures::{Future, Stream, Sink, Async, Poll, BoxFuture}; use protobuf::{self, Message}; use mercury::MercuryError; use player::Player; use mixer::Mixer; use session::Session; use util::{now_ms, SpotifyId, SeqGenerator}; use version; use protocol; use protocol::spirc::{PlayStatus, State, MessageType, Frame, DeviceState}; pub struct SpircTask { player: Player, mixer: Box<Mixer>, sequence: SeqGenerator<u32>, ident: String, device: DeviceState, state: State, subscription: BoxStream<Frame, MercuryError>, sender: BoxSink<Frame, MercuryError>, commands: mpsc::UnboundedReceiver<SpircCommand>, end_of_track: BoxFuture<(), oneshot::Canceled>, shutdown: bool, session: Session, } pub enum SpircCommand { Shutdown, } pub struct Spirc { commands: mpsc::UnboundedSender<SpircCommand>, } fn initial_state() -> State { { let mut msg = protocol::spirc::State::new(); msg.set_repeat(false); msg.set_shuffle(false); msg.set_status(PlayStatus::kPlayStatusStop); msg.set_position_ms(0); msg.set_position_measured_at(0); msg } } fn initial_device_state(name: String, volume: u16) -> DeviceState { { let mut msg = DeviceState::new(); msg.set_sw_version(version::version_string()); msg.set_is_active(false); msg.set_can_play(true); msg.set_volume(volume as u32); msg.set_name(name); { let repeated = msg.mut_capabilities(); { let mut msg = repeated.push_default(); msg.set_typ(protocol::spirc::CapabilityType::kCanBePlayer); { let repeated = msg.mut_intValue(); repeated.push(1) }; msg }; { let mut msg = repeated.push_default(); msg.set_typ(protocol::spirc::CapabilityType::kDeviceType); { let repeated = msg.mut_intValue(); repeated.push(5) }; msg }; { let mut msg = repeated.push_default(); msg.set_typ(protocol::spirc::CapabilityType::kGaiaEqConnectId); { let repeated = msg.mut_intValue(); repeated.push(1) }; msg }; { let mut msg = repeated.push_default(); msg.set_typ(protocol::spirc::CapabilityType::kSupportsLogout); { let repeated = msg.mut_intValue(); repeated.push(0) }; msg }; { let mut msg = repeated.push_default(); msg.set_typ(protocol::spirc::CapabilityType::kIsObservable); { let repeated = msg.mut_intValue(); repeated.push(1) }; msg }; { let mut msg = repeated.push_default(); msg.set_typ(protocol::spirc::CapabilityType::kVolumeSteps); { let repeated = msg.mut_intValue(); repeated.push(64) }; msg }; { let mut msg = repeated.push_default(); msg.set_typ(protocol::spirc::CapabilityType::kSupportedContexts); { let repeated = msg.mut_stringValue(); repeated.push(::std::convert::Into::into("album")); repeated.push(::std::convert::Into::into("playlist")); repeated.push(::std::convert::Into::into("search")); repeated.push(::std::convert::Into::into("inbox")); repeated.push(::std::convert::Into::into("toplist")); repeated.push(::std::convert::Into::into("starred")); repeated.push(::std::convert::Into::into("publishedstarred")); repeated.push(::std::convert::Into::into("track")) }; msg }; { let mut msg = repeated.push_default(); msg.set_typ(protocol::spirc::CapabilityType::kSupportedTypes); { let repeated = msg.mut_stringValue(); repeated.push(::std::convert::Into::into("audio/local")); repeated.push(::std::convert::Into::into("audio/track")); repeated.push(::std::convert::Into::into("local")); repeated.push(::std::convert::Into::into("track")) }; msg }; }; msg } } impl Spirc { pub fn new(session: Session, player: Player, mixer: Box<Mixer>) -> (Spirc, SpircTask) { debug!("new Spirc[{}]" , session . session_id ( )); let ident = session.device_id().to_owned(); let name = session.config().name.clone(); let uri = format!("hm://remote/user/{}" , session . username ( )); let subscription = session.mercury().subscribe(&uri as &str); let subscription = subscription.map(|stream| stream.map_err(|_| MercuryError)).flatten_stream(); let subscription = subscription.map(|response| -> Frame { let data = response.payload.first().unwrap(); protobuf::parse_from_bytes(data).unwrap() }).boxed(); let sender = Box::new(session.mercury().sender(uri).with(|frame: Frame| { Ok(frame.write_to_bytes().unwrap()) })); let (cmd_tx, cmd_rx) = mpsc::unbounded(); let volume = 65535; let device = initial_device_state(name, volume); mixer.set_volume(volume); let mut task = SpircTask{player: player, mixer: mixer, sequence: SeqGenerator::new(1), ident: ident, device: device, state: initial_state(), subscription: subscription, sender: sender, commands: cmd_rx, end_of_track: future::empty().boxed(), shutdown: false, session: session.clone(),}; let spirc = Spirc{commands: cmd_tx,}; task.hello(); (spirc, task) } pub fn shutdown(&self) { let _ = mpsc::UnboundedSender::send(&self.commands, SpircCommand::Shutdown); } } impl Future for SpircTask { type Item = (); type Error = (); fn poll(&mut self) -> Poll<(), ()> { loop { let mut progress = false; if !self.shutdown { match self.subscription.poll().unwrap() { Async::Ready(Some(frame)) => { progress = true; self.handle_frame(frame); } Async::Ready(None) => panic!("subscription terminated"), Async::NotReady => (), } match self.commands.poll().unwrap() { Async::Ready(Some(command)) => { progress = true; self.handle_command(command); } Async::Ready(None) => (), Async::NotReady => (), } match self.end_of_track.poll() { Ok(Async::Ready(())) => { progress = true; self.handle_end_of_track(); } Ok(Async::NotReady) => (), Err(oneshot::Canceled) => { self.end_of_track = future::empty().boxed() } } } let poll_sender = self.sender.poll_complete().unwrap(); if self.shutdown && poll_sender.is_ready() { return Ok(Async::Ready(())); } if !progress { return Ok(Async::NotReady); } } } } impl SpircTask { fn handle_command(&mut self, cmd: SpircCommand) { match cmd { SpircCommand::Shutdown => { CommandSender::new(self, MessageType::kMessageTypeGoodbye).send(); self.shutdown = true; self.commands.close(); } } } fn handle_frame(&mut self, frame: Frame) { debug!("{:?} {:?} {} {} {}" , frame . get_typ ( ) , frame . get_device_state ( ) . get_name ( ) , frame . get_ident ( ) , frame . get_seq_nr ( ) , frame . get_state_update_id ( )); if frame.get_ident() == self.ident || (frame.get_recipient().len() > 0 && !frame.get_recipient().contains(&self.ident)) { return; } match frame.get_typ() { MessageType::kMessageTypeHello => { self.notify(Some(frame.get_ident())); } MessageType::kMessageTypeLoad => { if !self.device.get_is_active() { self.device.set_is_active(true); self.device.set_became_active_at(now_ms()); } self.update_tracks(&frame); if self.state.get_track().len() > 0 { self.state.set_position_ms(frame.get_state().get_position_ms()); self.state.set_position_measured_at(now_ms() as u64); let play = frame.get_state().get_status() == PlayStatus::kPlayStatusPlay; self.load_track(play); } else { self.state.set_status(PlayStatus::kPlayStatusStop); } self.notify(None); } MessageType::kMessageTypePlay => { if self.state.get_status() == PlayStatus::kPlayStatusPause { self.mixer.start(); self.player.play(); self.state.set_status(PlayStatus::kPlayStatusPlay); self.state.set_position_measured_at(now_ms() as u64); } self.notify(None); } MessageType::kMessageTypePause => { if self.state.get_status() == PlayStatus::kPlayStatusPlay { self.player.pause(); self.mixer.stop(); self.state.set_status(PlayStatus::kPlayStatusPause); let now = now_ms() as u64; let position = self.state.get_position_ms(); let diff = now - self.state.get_position_measured_at(); self.state.set_position_ms(position + (diff as u32)); self.state.set_position_measured_at(now); } self.notify(None); } MessageType::kMessageTypeNext => { let current_index = self.state.get_playing_track_index(); let new_index = (current_index + 1) % (self.state.get_track().len() as u32); self.state.set_playing_track_index(new_index); self.state.set_position_ms(0); self.state.set_position_measured_at(now_ms() as u64); self.load_track(true); self.notify(None); } MessageType::kMessageTypePrev => { if self.position() < 3000 { let current_index = self.state.get_playing_track_index(); let new_index = if current_index == 0 { (self.state.get_track().len() as u32) - 1 } else { current_index - 1 }; self.state.set_playing_track_index(new_index); self.state.set_position_ms(0); self.state.set_position_measured_at(now_ms() as u64); self.load_track(true); } else { self.state.set_position_ms(0); self.state.set_position_measured_at(now_ms() as u64); self.player.seek(0); } self.notify(None); } MessageType::kMessageTypeSeek => { let position = frame.get_position(); self.state.set_position_ms(position); self.state.set_position_measured_at(now_ms() as u64); self.player.seek(position); self.notify(None); } MessageType::kMessageTypeReplace => { self.update_tracks(&frame); self.notify(None); } MessageType::kMessageTypeVolume => { let volume = frame.get_volume(); self.device.set_volume(volume); self.mixer.set_volume(frame.get_volume() as u16); self.notify(None); } MessageType::kMessageTypeNotify => { if self.device.get_is_active() && frame.get_device_state().get_is_active() { self.device.set_is_active(false); self.state.set_status(PlayStatus::kPlayStatusStop); self.player.stop(); self.mixer.stop(); } } _ => (), } } fn handle_end_of_track(&mut self) { let current_index = self.state.get_playing_track_index(); let new_index = (current_index + 1) % (self.state.get_track().len() as u32); self.state.set_playing_track_index(new_index); self.state.set_position_ms(0); self.state.set_position_measured_at(now_ms() as u64); self.load_track(true); self.notify(None); } fn position(&mut self) -> u32 { let diff = (now_ms() as u64) - self.state.get_position_measured_at(); self.state.get_position_ms() + (diff as u32) } fn update_tracks(&mut self, frame: &protocol::spirc::Frame) { let index = frame.get_state().get_playing_track_index(); let tracks = frame.get_state().get_track(); self.state.set_playing_track_index(index); self.state.set_track(tracks.into_iter().cloned().collect()); } fn load_track(&mut self, play: bool) { let index = self.state.get_playing_track_index(); let track = { let gid = self.state.get_track()[index as usize].get_gid(); SpotifyId::from_raw(gid) }; let position = self.state.get_position_ms(); let end_of_track = self.player.load(track, play, position); if play { self.state.set_status(PlayStatus::kPlayStatusPlay); } else { self.state.set_status(PlayStatus::kPlayStatusPause); } self.end_of_track = end_of_track.boxed(); } fn hello(&mut self) { CommandSender::new(self, MessageType::kMessageTypeHello).send(); } fn notify(&mut self, recipient: Option<&str>) { let mut cs = CommandSender::new(self, MessageType::kMessageTypeNotify); if let Some(s) = recipient { cs = cs.recipient(&s); } cs.send(); } } impl Drop for SpircTask { fn drop(&mut self) { debug!("drop Spirc[{}]" , self . session . session_id ( )); } } struct CommandSender<'a> { spirc: &'a mut SpircTask, frame: protocol::spirc::Frame, } impl <'a> CommandSender<'a> { fn new(spirc: &'a mut SpircTask, cmd: MessageType) -> CommandSender { let frame = { let mut msg = protocol::spirc::Frame::new(); msg.set_version(1); msg.set_protocol_version(::std::convert::Into::into("2.0.0")); msg.set_ident(spirc.ident.clone()); msg.set_seq_nr(spirc.sequence.get()); msg.set_typ(cmd); msg.set_device_state(spirc.device.clone()); msg.set_state_update_id(now_ms()); msg }; CommandSender{spirc: spirc, frame: frame,} } fn recipient(mut self, recipient: &'a str) -> CommandSender { self.frame.mut_recipient().push(recipient.to_owned()); self } #[allow(dead_code)] fn state(mut self, state: protocol::spirc::State) -> CommandSender<'a> { self.frame.set_state(state); self } fn send(mut self) { if !self.frame.has_state() && self.spirc.device.get_is_active() { self.frame.set_state(self.spirc.state.clone()); } let send = self.spirc.sender.start_send(self.frame).unwrap(); assert!(send . is_ready ( )); } } }
{{#with NewObjs~}} if {{list}}.iter().any(|&c| c {{~#if ../is_triangular}} >= {{else}} == {{/if~}} {{~#if set.var~}} ({{>set.id_getter def=set.def.arg item=set.var}}, {{>set.id_getter set item=../var~}}) {{~else~}} {{>set.id_getter set item=../var~}} {{/if~}}) { continue; } {{~/with~}} {{#with Variable~}} if {{>set.id_getter def=set item=../var~}} {{#if ../is_triangular}} <= {{else}} == {{/if~}} {{>set.id_getter def=set item=conflict_var}} { continue; } {{~/with~}}
use input_i_scanner::{scan_with, InputIScanner}; use mod_int::ModInt998244353; use std::collections::HashMap; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); let (n, m) = scan_with!(_i_i, (usize, usize)); let k = scan_with!(_i_i, i32); let a = scan_with!(_i_i, usize; m); let edges = scan_with!(_i_i, (usize, usize); n - 1); let mut g = vec![vec![]; n]; for (i, &(u, v)) in edges.iter().enumerate() { g[u - 1].push((i, v - 1)); g[v - 1].push((i, u - 1)); } let mut par = vec![(!0, !0); n]; let mut dep = vec![0; n]; dfs(0, !0, &g, &mut par, &mut dep); let mut c = vec![0; n - 1]; for w in a.windows(2) { let u = w[0] - 1; let v = w[1] - 1; let (mut u, mut v) = if dep[u] >= dep[v] { (u, v) } else { (v, u) }; while dep[u] != dep[v] { let (e_id, p) = par[u]; c[e_id] += 1; u = p; } while u != v { let (u_e_id, u_p) = par[u]; let (v_e_id, v_p) = par[v]; c[u_e_id] += 1; c[v_e_id] += 1; u = u_p; v = v_p; } } // eprintln!("{:?}", c); type Mint = ModInt998244353; let mut dp: HashMap<i32, Mint> = HashMap::new(); dp.insert(0, Mint::new(1)); for c in c { let mut nxt = HashMap::new(); for (key, val) in dp { nxt.entry(key + c) .and_modify(|e| { *e += val; }) .or_insert(val); nxt.entry(key - c) .and_modify(|e| { *e += val; }) .or_insert(val); } dp = nxt; } if let Some(ans) = dp.get(&k) { println!("{}", ans.val()); } else { println!("0"); } } fn dfs( u: usize, p: usize, g: &Vec<Vec<(usize, usize)>>, par: &mut Vec<(usize, usize)>, dep: &mut Vec<usize>, ) { for &(e_id, v) in &g[u] { if v != p { par[v] = (e_id, u); dep[v] = dep[u] + 1; dfs(v, u, g, par, dep); } } }
#[macro_use] extern crate dotenv_codegen; #[macro_use] extern crate duct; fn main() { println!("Hello, world!"); let msg = cmd!("sh", "-c", "cd /home/fish/m/gitr && ls").stderr_to_stdout().read().unwrap(); println!("{}", msg); getvar("test".to_string()); } fn getvar(var: String) { // environment variables {{{ println!("{}", var); let home = dotenv!("HOME"); println!("{}", home); // }}} }
use super::{Column, DataStore, PinModeRequirement}; use crate::error::Error; use crate::repo::{PinKind, PinMode, PinStore, References}; use async_trait::async_trait; use cid::{self, Cid}; use futures::stream::{StreamExt, TryStreamExt}; use once_cell::sync::OnceCell; use sled::{ self, transaction::{ ConflictableTransactionError, TransactionError, TransactionResult, TransactionalTree, UnabortableTransactionError, }, Config as DbConfig, Db, Mode as DbMode, }; use std::collections::BTreeSet; use std::convert::Infallible; use std::path::PathBuf; use std::str::{self, FromStr}; /// [`sled`] based pinstore implementation. Implements datastore which errors for each call. /// Currently feature-gated behind `sled_data_store` feature in the [`crate::Types`], usable /// directly in custom type configurations. /// /// Current schema is to use the the default tree for storing pins, which are serialized as /// [`get_pin_key`]. Depending on the kind of pin values are generated by [`direct_value`], /// [`recursive_value`], and [`indirect_value`]. /// /// [`sled`]: https://github.com/spacejam/sled #[derive(Debug)] pub struct KvDataStore { path: PathBuf, // it is a trick for not modifying the Data:init db: OnceCell<Db>, } impl KvDataStore { fn get_db(&self) -> &Db { self.db.get().unwrap() } } #[async_trait] impl DataStore for KvDataStore { fn new(root: PathBuf) -> KvDataStore { KvDataStore { path: root, db: Default::default(), } } async fn init(&self) -> Result<(), Error> { let config = DbConfig::new(); let db = config .mode(DbMode::HighThroughput) .path(self.path.as_path()) .open()?; match self.db.set(db) { Ok(()) => Ok(()), Err(_) => Err(anyhow::anyhow!("failed to init sled")), } } async fn open(&self) -> Result<(), Error> { Ok(()) } /// Checks if a key is present in the datastore. async fn contains(&self, _col: Column, _key: &[u8]) -> Result<bool, Error> { Err(anyhow::anyhow!("not implemented")) } /// Returns the value associated with a key from the datastore. async fn get(&self, _col: Column, _key: &[u8]) -> Result<Option<Vec<u8>>, Error> { Err(anyhow::anyhow!("not implemented")) } /// Puts the value under the key in the datastore. async fn put(&self, _col: Column, _key: &[u8], _value: &[u8]) -> Result<(), Error> { Err(anyhow::anyhow!("not implemented")) } /// Removes a key-value pair from the datastore. async fn remove(&self, _col: Column, _key: &[u8]) -> Result<(), Error> { Err(anyhow::anyhow!("not implemented")) } /// Wipes the datastore. async fn wipe(&self) { todo!() } } // in the transactional parts of the [`Infallible`] is used to signal there is no additional // custom error, not that the transaction was infallible in itself. #[async_trait] impl PinStore for KvDataStore { async fn is_pinned(&self, cid: &Cid) -> Result<bool, Error> { let cid = cid.to_owned(); let db = self.get_db().to_owned(); let span = tracing::Span::current(); tokio::task::spawn_blocking(move || { let span = tracing::trace_span!(parent: &span, "blocking"); let _g = span.enter(); Ok(db.transaction::<_, _, Infallible>(|tree| { Ok(get_pinned_mode(tree, &cid)?.is_some()) })?) }) .await? } async fn insert_direct_pin(&self, target: &Cid) -> Result<(), Error> { use ConflictableTransactionError::Abort; let target = target.to_owned(); let db = self.get_db().to_owned(); let span = tracing::Span::current(); let res = tokio::task::spawn_blocking(move || { let span = tracing::trace_span!(parent: &span, "blocking"); let _g = span.enter(); db.transaction(|tx_tree| { let already_pinned = get_pinned_mode(tx_tree, &target)?; match already_pinned { Some((PinMode::Direct, _)) => return Ok(()), Some((PinMode::Recursive, _)) => { return Err(Abort(anyhow::anyhow!("already pinned recursively"))) } Some((PinMode::Indirect, key)) => { // TODO: I think the direct should live alongside the indirect? tx_tree.remove(key.as_str())?; } None => {} } let direct_key = get_pin_key(&target, &PinMode::Direct); tx_tree.insert(direct_key.as_str(), direct_value())?; tx_tree.flush(); Ok(()) }) }) .await?; launder(res) } async fn insert_recursive_pin( &self, target: &Cid, referenced: References<'_>, ) -> Result<(), Error> { // since the transaction can be retried multiple times, we need to collect these and keep // iterating it until there is no conflict. let set = referenced.try_collect::<BTreeSet<_>>().await?; let target = target.to_owned(); let db = self.get_db().to_owned(); let span = tracing::Span::current(); // the transaction is not infallible but there is no additional error we return tokio::task::spawn_blocking(move || { let span = tracing::trace_span!(parent: &span, "blocking"); let _g = span.enter(); db.transaction::<_, _, Infallible>(move |tx_tree| { let already_pinned = get_pinned_mode(tx_tree, &target)?; match already_pinned { Some((PinMode::Recursive, _)) => return Ok(()), Some((PinMode::Direct, key)) | Some((PinMode::Indirect, key)) => { // FIXME: this is probably another lapse in tests that both direct and // indirect can be removed when inserting recursive? tx_tree.remove(key.as_str())?; } None => {} } let recursive_key = get_pin_key(&target, &PinMode::Recursive); tx_tree.insert(recursive_key.as_str(), recursive_value())?; let target_value = indirect_value(&target); // cannot use into_iter here as the transactions are retryable for cid in set.iter() { let indirect_key = get_pin_key(cid, &PinMode::Indirect); if matches!(get_pinned_mode(tx_tree, cid)?, Some(_)) { // TODO: quite costly to do the get_pinned_mode here continue; } // value is for get information like "Qmd9WDTA2Kph4MKiDDiaZdiB4HJQpKcxjnJQfQmM5rHhYK indirect through QmXr1XZBg1CQv17BPvSWRmM7916R6NLL7jt19rhCPdVhc5" // FIXME: this will not work with multiple blocks linking to the same block? also the // test is probably missing as well tx_tree.insert(indirect_key.as_str(), target_value.as_str())?; } tx_tree.flush(); Ok(()) }) }) .await??; Ok(()) } async fn remove_direct_pin(&self, target: &Cid) -> Result<(), Error> { use ConflictableTransactionError::Abort; let target = target.to_owned(); let db = self.get_db().to_owned(); let span = tracing::Span::current(); let res = tokio::task::spawn_blocking(move || { let span = tracing::trace_span!(parent: &span, "blocking"); let _g = span.enter(); db.transaction::<_, _, Error>(|tx_tree| { if is_not_pinned_or_pinned_indirectly(tx_tree, &target)? { return Err(Abort(anyhow::anyhow!("not pinned or pinned indirectly"))); } let key = get_pin_key(&target, &PinMode::Direct); tx_tree.remove(key.as_str())?; tx_tree.flush(); Ok(()) }) }) .await?; launder(res) } async fn remove_recursive_pin( &self, target: &Cid, referenced: References<'_>, ) -> Result<(), Error> { use ConflictableTransactionError::Abort; // TODO: is this "in the same transaction" as the batch which is created? let set = referenced.try_collect::<BTreeSet<_>>().await?; let target = target.to_owned(); let db = self.get_db().to_owned(); let span = tracing::Span::current(); let res = tokio::task::spawn_blocking(move || { let span = tracing::trace_span!(parent: &span, "blocking"); let _g = span.enter(); db.transaction(|tx_tree| { if is_not_pinned_or_pinned_indirectly(tx_tree, &target)? { return Err(Abort(anyhow::anyhow!("not pinned or pinned indirectly"))); } let recursive_key = get_pin_key(&target, &PinMode::Recursive); tx_tree.remove(recursive_key.as_str())?; for cid in &set { let already_pinned = get_pinned_mode(tx_tree, cid)?; match already_pinned { Some((PinMode::Recursive, _)) | Some((PinMode::Direct, _)) => continue, // this should be unreachable Some((PinMode::Indirect, key)) => { // FIXME: not really sure of this but it might be that recursive removed // the others...? tx_tree.remove(key.as_str())?; } None => {} } } tx_tree.flush(); Ok(()) }) }) .await?; launder(res) } async fn list( &self, requirement: Option<PinMode>, ) -> futures::stream::BoxStream<'static, Result<(Cid, PinMode), Error>> { use tokio_stream::wrappers::UnboundedReceiverStream; let db = self.get_db().to_owned(); // if the pins are always updated in transaction, we might get away with just tree reads. // this does however mean that it is possible to witness for example a part of a larger // recursive pin and then just not find anymore of the recursive pin near the end of the // listing. for non-gc uses this should not be an issue. // // FIXME: the unboundedness is still quite unoptimal here: we might get gazillion http // listings which all quickly fill up a lot of memory and clients never have to read any // responses. using of bounded channel would require sometimes sleeping and maybe bouncing // back and forth between an async task and continuation of the iteration. leaving this to // a later issue. let (tx, rx) = tokio::sync::mpsc::unbounded_channel(); let span = tracing::Span::current(); let _jh = tokio::task::spawn_blocking(move || { let span = tracing::trace_span!(parent: &span, "blocking"); let _g = span.enter(); // this probably doesn't need to be transactional? well, perhaps transactional reads would // be the best, not sure what is the guaratee for in-sequence key reads. let iter = db.range::<String, std::ops::RangeFull>(..); let requirement = PinModeRequirement::from(requirement); let adapted = iter.map(|res| res.map_err(Error::from)) .filter_map(move |res| match res { Ok((k, _v)) => { if !k.starts_with(b"pin.") || k.len() < 7 { return Some(Err(anyhow::anyhow!( "invalid pin: {:?}", &*String::from_utf8_lossy(&*k) ))); } let mode = match k[4] { b'd' => PinMode::Direct, b'r' => PinMode::Recursive, b'i' => PinMode::Indirect, x => { return Some(Err(anyhow::anyhow!( "invalid pinmode: {}", x as char ))) } }; if !requirement.matches(&mode) { None } else { let cid = std::str::from_utf8(&k[6..]).map_err(Error::from); let cid = cid.and_then(|x| Cid::from_str(x).map_err(Error::from)); let cid = cid.map_err(|e| { e.context(format!( "failed to read pin: {:?}", &*String::from_utf8_lossy(&*k) )) }); Some(cid.map(move |cid| (cid, mode))) } } Err(e) => Some(Err(e)), }); for res in adapted { if tx.send(res).is_err() { break; } } }); // we cannot know if the task was spawned successfully until it has completed, so we cannot // really do anything with the _jh. // // perhaps we could await for the first element OR cancellation OR perhaps something // else. StreamExt::peekable() would be good to go, but Peekable is only usable on top of // something pinned, and I cannot see how could it become a boxed stream if we pin it, peek // it and ... how would we get the peeked element since Peekable::into_inner doesn't return // the value which has already been read from the stream? // // it would be nice to make sure that the stream doesn't end before task has ended, but // perhaps the unboundedness of the channel takes care of that. UnboundedReceiverStream::new(rx).boxed() } async fn query( &self, ids: Vec<Cid>, requirement: Option<PinMode>, ) -> Result<Vec<(Cid, PinKind<Cid>)>, Error> { use ConflictableTransactionError::Abort; let requirement = PinModeRequirement::from(requirement); let db = self.get_db().to_owned(); tokio::task::spawn_blocking(move || { let res = db.transaction::<_, _, Error>(|tx_tree| { // since its an Fn closure this cannot be reserved once ... not sure why it couldn't be // FnMut? the vec could be cached in the "outer" scope in a refcell. let mut modes = Vec::with_capacity(ids.len()); // as we might loop over an over on the tx we might need this over and over, cannot // take ownership inside the transaction. TODO: perhaps the use of transaction is // questionable here; if the source of the indirect pin cannot be it is already // None, this could work outside of transaction similarly. for id in ids.iter() { let mode_and_key = get_pinned_mode(tx_tree, id)?; let matched = match mode_and_key { Some((pin_mode, key)) if requirement.matches(&pin_mode) => match pin_mode { PinMode::Direct => Some(PinKind::Direct), PinMode::Recursive => Some(PinKind::Recursive(0)), PinMode::Indirect => tx_tree .get(key.as_str())? .map(|root| { cid_from_indirect_value(&*root) .map(PinKind::IndirectFrom) .map_err(|e| { Abort(e.context(format!( "failed to read indirect pin source: {:?}", String::from_utf8_lossy(root.as_ref()).as_ref(), ))) }) }) .transpose()?, }, Some(_) | None => None, }; // this might be None, or Some(PinKind); it's important there are as many cids // as there are modes modes.push(matched); } Ok(modes) }); let modes = launder(res)?; Ok(ids .into_iter() .zip(modes.into_iter()) .filter_map(|(cid, mode)| mode.map(move |mode| (cid, mode))) .collect::<Vec<_>>()) }) .await? } } /// Name the empty value stored for direct pins; the pin key itself describes the mode and the cid. fn direct_value() -> &'static [u8] { Default::default() } /// Name the empty value stored for recursive pins at the top. fn recursive_value() -> &'static [u8] { Default::default() } /// Name the value stored for indirect pins, currently only the most recent recursive pin. fn indirect_value(recursively_pinned: &Cid) -> String { recursively_pinned.to_string() } /// Inverse of [`indirect_value`]. fn cid_from_indirect_value(bytes: &[u8]) -> Result<Cid, Error> { str::from_utf8(bytes) .map_err(Error::from) .and_then(|s| Cid::from_str(s).map_err(Error::from)) } /// Helper needed as the error cannot just `?` converted. fn launder<T>(res: TransactionResult<T, Error>) -> Result<T, Error> { use TransactionError::*; match res { Ok(t) => Ok(t), Err(Abort(e)) => Err(e), Err(Storage(e)) => Err(e.into()), } } fn pin_mode_literal(pin_mode: &PinMode) -> &'static str { match pin_mode { PinMode::Direct => "d", PinMode::Indirect => "i", PinMode::Recursive => "r", } } fn get_pin_key(cid: &Cid, pin_mode: &PinMode) -> String { // TODO: get_pinned_mode could be range query if the pin modes were suffixes, keys would need // to be cid.to_bytes().push(pin_mode_literal(pin_mode))? ... since the cid bytes // representation already contains the length we should be good to go in all cases. // // for storing multiple targets then the last could be found by doing a query as well. in the // case of multiple indirect pins they'd have to be with another suffix. // // TODO: check if such representation would really order properly format!("pin.{}.{}", pin_mode_literal(pin_mode), cid) } /// Returns a tuple of the parsed mode and the key used fn get_pinned_mode( tree: &TransactionalTree, block: &Cid, ) -> Result<Option<(PinMode, String)>, UnabortableTransactionError> { for mode in &[PinMode::Direct, PinMode::Recursive, PinMode::Indirect] { let key = get_pin_key(block, mode); if tree.get(key.as_str())?.is_some() { return Ok(Some((*mode, key))); } } Ok(None) } fn is_not_pinned_or_pinned_indirectly( tree: &TransactionalTree, block: &Cid, ) -> Result<bool, UnabortableTransactionError> { match get_pinned_mode(tree, block)? { Some((PinMode::Indirect, _)) | None => Ok(true), _ => Ok(false), } } #[cfg(test)] crate::pinstore_interface_tests!(common_tests, crate::repo::kv::KvDataStore::new);
// Copyright 2016 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 static mut DROP: bool = false; struct ConnWrap(Conn); impl ::std::ops::Deref for ConnWrap { type Target=Conn; fn deref(&self) -> &Conn { &self.0 } } struct Conn; impl Drop for Conn { fn drop(&mut self) { unsafe { DROP = true; } } } fn inner() { let conn = &*match Some(ConnWrap(Conn)) { Some(val) => val, None => return, }; return; } fn main() { inner(); unsafe { assert_eq!(DROP, true); } }
use super::chan; use futures::{Poll, Sink, StartSend, Stream}; use std::fmt; /// Send values to the associated `Receiver`. /// /// Instances are created by the [`channel`](fn.channel.html) function. pub struct Sender<T> { chan: chan::Tx<T, Semaphore>, } impl<T> Clone for Sender<T> { fn clone(&self) -> Self { Sender { chan: self.chan.clone(), } } } impl<T> fmt::Debug for Sender<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Sender") .field("chan", &self.chan) .finish() } } /// Receive values from the associated `Sender`. /// /// Instances are created by the [`channel`](fn.channel.html) function. pub struct Receiver<T> { /// The channel receiver chan: chan::Rx<T, Semaphore>, } impl<T> fmt::Debug for Receiver<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { fmt.debug_struct("Receiver") .field("chan", &self.chan) .finish() } } /// Error returned by the `Sender`. #[derive(Debug)] pub struct SendError(()); /// Error returned by `Sender::try_send`. #[derive(Debug)] pub struct TrySendError<T> { kind: ErrorKind, value: T, } #[derive(Debug)] enum ErrorKind { Closed, NoCapacity, } /// Error returned by `Receiver`. #[derive(Debug)] pub struct RecvError(()); /// Create a bounded mpsc channel for communicating between asynchronous tasks, /// returning the sender/receiver halves. /// /// All data sent on `Sender` will become available on `Receiver` in the same /// order as it was sent. /// /// The `Sender` can be cloned to `send` to the same channel from multiple code /// locations. Only one `Receiver` is supported. /// /// If the `Receiver` is disconnected while trying to `send`, the `send` method /// will return a `SendError`. Similarly, if `Sender` is disconnected while /// trying to `recv`, the `recv` method will return a `RecvError`. /// /// # Examples /// /// ```rust /// extern crate futures; /// extern crate tokio; /// /// use tokio::sync::mpsc::channel; /// use tokio::prelude::*; /// use futures::future::lazy; /// /// # fn some_computation() -> impl Future<Item = (), Error = ()> + Send { /// # futures::future::ok::<(), ()>(()) /// # } /// /// tokio::run(lazy(|| { /// let (tx, rx) = channel(100); /// /// tokio::spawn({ /// some_computation() /// .and_then(|value| { /// tx.send(value) /// .map_err(|_| ()) /// }) /// .map(|_| ()) /// .map_err(|_| ()) /// }); /// /// rx.for_each(|value| { /// println!("got value = {:?}", value); /// Ok(()) /// }) /// .map(|_| ()) /// .map_err(|_| ()) /// })); /// ``` pub fn channel<T>(buffer: usize) -> (Sender<T>, Receiver<T>) { assert!(buffer > 0, "mpsc bounded channel requires buffer > 0"); let semaphore = (::semaphore::Semaphore::new(buffer), buffer); let (tx, rx) = chan::channel(semaphore); let tx = Sender::new(tx); let rx = Receiver::new(rx); (tx, rx) } /// Channel semaphore is a tuple of the semaphore implementation and a `usize` /// representing the channel bound. type Semaphore = (::semaphore::Semaphore, usize); impl<T> Receiver<T> { pub(crate) fn new(chan: chan::Rx<T, Semaphore>) -> Receiver<T> { Receiver { chan } } /// Closes the receiving half of a channel, without dropping it. /// /// This prevents any further messages from being sent on the channel while /// still enabling the receiver to drain messages that are buffered. pub fn close(&mut self) { self.chan.close(); } } impl<T> Stream for Receiver<T> { type Item = T; type Error = RecvError; fn poll(&mut self) -> Poll<Option<T>, Self::Error> { self.chan.recv().map_err(|_| RecvError(())) } } impl<T> Sender<T> { pub(crate) fn new(chan: chan::Tx<T, Semaphore>) -> Sender<T> { Sender { chan } } /// Check if the `Sender` is ready to handle a value. /// /// Polls the channel to determine if there is guaranteed capacity to send /// at least one item without waiting. /// /// When `poll_ready` returns `Ready`, the channel reserves capacity for one /// message for this `Sender` instance. The capacity is held until a message /// is send or the `Sender` instance is dropped. Callers should ensure a /// message is sent in a timely fashion in order to not starve other /// `Sender` instances. /// /// # Return value /// /// This method returns: /// /// - `Ok(Async::Ready(_))` if capacity is reserved for a single message. /// - `Ok(Async::NotReady)` if the channel may not have capacity, in which /// case the current task is queued to be notified once /// capacity is available; /// - `Err(SendError)` if the receiver has been dropped. pub fn poll_ready(&mut self) -> Poll<(), SendError> { self.chan.poll_ready().map_err(|_| SendError(())) } /// Attempts to send a message on this `Sender`, returning the message /// if there was an error. pub fn try_send(&mut self, message: T) -> Result<(), TrySendError<T>> { self.chan.try_send(message)?; Ok(()) } } impl<T> Sink for Sender<T> { type SinkItem = T; type SinkError = SendError; fn start_send(&mut self, msg: T) -> StartSend<T, Self::SinkError> { use futures::Async::*; use futures::AsyncSink; match self.poll_ready()? { Ready(_) => { self.try_send(msg).map_err(|_| SendError(()))?; Ok(AsyncSink::Ready) } NotReady => Ok(AsyncSink::NotReady(msg)), } } fn poll_complete(&mut self) -> Poll<(), Self::SinkError> { use futures::Async::Ready; Ok(Ready(())) } fn close(&mut self) -> Poll<(), Self::SinkError> { use futures::Async::Ready; Ok(Ready(())) } } // ===== impl SendError ===== impl fmt::Display for SendError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } } impl ::std::error::Error for SendError { fn description(&self) -> &str { "channel closed" } } // ===== impl TrySendError ===== impl<T> TrySendError<T> { /// Get the inner value. pub fn into_inner(self) -> T { self.value } /// Did the send fail because the channel has been closed? pub fn is_closed(&self) -> bool { if let ErrorKind::Closed = self.kind { true } else { false } } /// Did the send fail because the channel was at capacity? pub fn is_full(&self) -> bool { if let ErrorKind::NoCapacity = self.kind { true } else { false } } } impl<T: fmt::Debug> fmt::Display for TrySendError<T> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } } impl<T: fmt::Debug> ::std::error::Error for TrySendError<T> { fn description(&self) -> &str { match self.kind { ErrorKind::Closed => "channel closed", ErrorKind::NoCapacity => "no available capacity", } } } impl<T> From<(T, chan::TrySendError)> for TrySendError<T> { fn from((value, err): (T, chan::TrySendError)) -> TrySendError<T> { TrySendError { value, kind: match err { chan::TrySendError::Closed => ErrorKind::Closed, chan::TrySendError::NoPermits => ErrorKind::NoCapacity, }, } } } // ===== impl RecvError ===== impl fmt::Display for RecvError { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { use std::error::Error; write!(fmt, "{}", self.description()) } } impl ::std::error::Error for RecvError { fn description(&self) -> &str { "channel closed" } }
// Copyright 2018 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. use core::unicode::property::Pattern_White_Space; use rustc::mir::*; use rustc::ty; use rustc_errors::{DiagnosticBuilder,Applicability}; use syntax_pos::Span; use borrow_check::MirBorrowckCtxt; use borrow_check::prefixes::PrefixSet; use dataflow::move_paths::{IllegalMoveOrigin, IllegalMoveOriginKind}; use dataflow::move_paths::{LookupResult, MoveError, MovePathIndex}; use util::borrowck_errors::{BorrowckErrors, Origin}; // Often when desugaring a pattern match we may have many individual moves in // MIR that are all part of one operation from the user's point-of-view. For // example: // // let (x, y) = foo() // // would move x from the 0 field of some temporary, and y from the 1 field. We // group such errors together for cleaner error reporting. // // Errors are kept separate if they are from places with different parent move // paths. For example, this generates two errors: // // let (&x, &y) = (&String::new(), &String::new()); #[derive(Debug)] enum GroupedMoveError<'tcx> { // Place expression can't be moved from, // e.g. match x[0] { s => (), } where x: &[String] MovesFromPlace { original_path: Place<'tcx>, span: Span, move_from: Place<'tcx>, kind: IllegalMoveOriginKind<'tcx>, binds_to: Vec<Local>, }, // Part of a value expression can't be moved from, // e.g. match &String::new() { &x => (), } MovesFromValue { original_path: Place<'tcx>, span: Span, move_from: MovePathIndex, kind: IllegalMoveOriginKind<'tcx>, binds_to: Vec<Local>, }, // Everything that isn't from pattern matching. OtherIllegalMove { original_path: Place<'tcx>, span: Span, kind: IllegalMoveOriginKind<'tcx>, }, } impl<'a, 'gcx, 'tcx> MirBorrowckCtxt<'a, 'gcx, 'tcx> { pub(crate) fn report_move_errors(&mut self, move_errors: Vec<(Place<'tcx>, MoveError<'tcx>)>) { let grouped_errors = self.group_move_errors(move_errors); for error in grouped_errors { self.report(error); } } fn group_move_errors( &self, errors: Vec<(Place<'tcx>, MoveError<'tcx>)> ) -> Vec<GroupedMoveError<'tcx>> { let mut grouped_errors = Vec::new(); for (original_path, error) in errors { self.append_to_grouped_errors(&mut grouped_errors, original_path, error); } grouped_errors } fn append_to_grouped_errors( &self, grouped_errors: &mut Vec<GroupedMoveError<'tcx>>, original_path: Place<'tcx>, error: MoveError<'tcx>, ) { match error { MoveError::UnionMove { .. } => { unimplemented!("don't know how to report union move errors yet.") } MoveError::IllegalMove { cannot_move_out_of: IllegalMoveOrigin { location, kind }, } => { let stmt_source_info = self.mir.source_info(location); // Note: that the only time we assign a place isn't a temporary // to a user variable is when initializing it. // If that ever stops being the case, then the ever initialized // flow could be used. if let Some(StatementKind::Assign( Place::Local(local), Rvalue::Use(Operand::Move(move_from)), )) = self.mir.basic_blocks()[location.block] .statements .get(location.statement_index) .map(|stmt| &stmt.kind) { let local_decl = &self.mir.local_decls[*local]; // opt_match_place is the // match_span is the span of the expression being matched on // match *x.y { ... } match_place is Some(*x.y) // ^^^^ match_span is the span of *x.y // // opt_match_place is None for let [mut] x = ... statements, // whether or not the right-hand side is a place expression if let Some(ClearCrossCrate::Set(BindingForm::Var(VarBindingForm { opt_match_place: Some((ref opt_match_place, match_span)), binding_mode: _, opt_ty_info: _, pat_span: _, }))) = local_decl.is_user_variable { self.append_binding_error( grouped_errors, kind, original_path, move_from, *local, opt_match_place, match_span, stmt_source_info.span, ); return; } } grouped_errors.push(GroupedMoveError::OtherIllegalMove { span: stmt_source_info.span, original_path, kind, }); } } } fn append_binding_error( &self, grouped_errors: &mut Vec<GroupedMoveError<'tcx>>, kind: IllegalMoveOriginKind<'tcx>, original_path: Place<'tcx>, move_from: &Place<'tcx>, bind_to: Local, match_place: &Option<Place<'tcx>>, match_span: Span, statement_span: Span, ) { debug!( "append_binding_error(match_place={:?}, match_span={:?})", match_place, match_span ); let from_simple_let = match_place.is_none(); let match_place = match_place.as_ref().unwrap_or(move_from); match self.move_data.rev_lookup.find(match_place) { // Error with the match place LookupResult::Parent(_) => { for ge in &mut *grouped_errors { if let GroupedMoveError::MovesFromPlace { span, binds_to, .. } = ge { if match_span == *span { debug!("appending local({:?}) to list", bind_to); if !binds_to.is_empty() { binds_to.push(bind_to); } return; } } } debug!("found a new move error location"); // Don't need to point to x in let x = ... . let (binds_to, span) = if from_simple_let { (vec![], statement_span) } else { (vec![bind_to], match_span) }; grouped_errors.push(GroupedMoveError::MovesFromPlace { span, move_from: match_place.clone(), original_path, kind, binds_to, }); } // Error with the pattern LookupResult::Exact(_) => { let mpi = match self.move_data.rev_lookup.find(move_from) { LookupResult::Parent(Some(mpi)) => mpi, // move_from should be a projection from match_place. _ => unreachable!("Probably not unreachable..."), }; for ge in &mut *grouped_errors { if let GroupedMoveError::MovesFromValue { span, move_from: other_mpi, binds_to, .. } = ge { if match_span == *span && mpi == *other_mpi { debug!("appending local({:?}) to list", bind_to); binds_to.push(bind_to); return; } } } debug!("found a new move error location"); grouped_errors.push(GroupedMoveError::MovesFromValue { span: match_span, move_from: mpi, original_path, kind, binds_to: vec![bind_to], }); } }; } fn report(&mut self, error: GroupedMoveError<'tcx>) { let (mut err, err_span) = { let (span, original_path, kind): (Span, &Place<'tcx>, &IllegalMoveOriginKind) = match error { GroupedMoveError::MovesFromPlace { span, ref original_path, ref kind, .. } | GroupedMoveError::MovesFromValue { span, ref original_path, ref kind, .. } | GroupedMoveError::OtherIllegalMove { span, ref original_path, ref kind } => { (span, original_path, kind) }, }; let origin = Origin::Mir; debug!("report: original_path={:?} span={:?}, kind={:?} \ original_path.is_upvar_field_projection={:?}", original_path, span, kind, original_path.is_upvar_field_projection(self.mir, &self.infcx.tcx)); ( match kind { IllegalMoveOriginKind::Static => { self.infcx.tcx.cannot_move_out_of(span, "static item", origin) } IllegalMoveOriginKind::BorrowedContent { target_place: place } => { // Inspect the type of the content behind the // borrow to provide feedback about why this // was a move rather than a copy. let ty = place.ty(self.mir, self.infcx.tcx).to_ty(self.infcx.tcx); let is_upvar_field_projection = self.prefixes(&original_path, PrefixSet::All) .any(|p| p.is_upvar_field_projection(self.mir, &self.infcx.tcx) .is_some()); match ty.sty { ty::Array(..) | ty::Slice(..) => self.infcx.tcx.cannot_move_out_of_interior_noncopy( span, ty, None, origin ), ty::Closure(def_id, closure_substs) if !self.mir.upvar_decls.is_empty() && is_upvar_field_projection => { let closure_kind_ty = closure_substs.closure_kind_ty(def_id, self.infcx.tcx); let closure_kind = closure_kind_ty.to_opt_closure_kind(); let place_description = match closure_kind { Some(ty::ClosureKind::Fn) => { "captured variable in an `Fn` closure" } Some(ty::ClosureKind::FnMut) => { "captured variable in an `FnMut` closure" } Some(ty::ClosureKind::FnOnce) => { bug!("closure kind does not match first argument type") } None => bug!("closure kind not inferred by borrowck"), }; debug!("report: closure_kind_ty={:?} closure_kind={:?} \ place_description={:?}", closure_kind_ty, closure_kind, place_description); let mut diag = self.infcx.tcx.cannot_move_out_of( span, place_description, origin); for prefix in self.prefixes(&original_path, PrefixSet::All) { if let Some(field) = prefix.is_upvar_field_projection( self.mir, &self.infcx.tcx) { let upvar_decl = &self.mir.upvar_decls[field.index()]; let upvar_hir_id = upvar_decl.var_hir_id.assert_crate_local(); let upvar_node_id = self.infcx.tcx.hir.hir_to_node_id(upvar_hir_id); let upvar_span = self.infcx.tcx.hir.span(upvar_node_id); diag.span_label(upvar_span, "captured outer variable"); break; } } diag } _ => self.infcx.tcx.cannot_move_out_of( span, "borrowed content", origin ), } } IllegalMoveOriginKind::InteriorOfTypeWithDestructor { container_ty: ty } => { self.infcx.tcx .cannot_move_out_of_interior_of_drop(span, ty, origin) } IllegalMoveOriginKind::InteriorOfSliceOrArray { ty, is_index } => self.infcx.tcx.cannot_move_out_of_interior_noncopy( span, ty, Some(*is_index), origin ), }, span, ) }; self.add_move_hints(error, &mut err, err_span); err.buffer(&mut self.errors_buffer); } fn add_move_hints( &self, error: GroupedMoveError<'tcx>, err: &mut DiagnosticBuilder<'a>, span: Span, ) { let snippet = self.infcx.tcx.sess.source_map().span_to_snippet(span).unwrap(); match error { GroupedMoveError::MovesFromPlace { mut binds_to, move_from, .. } => { let try_remove_deref = match move_from { Place::Projection(box PlaceProjection { elem: ProjectionElem::Deref, .. }) => true, _ => false, }; if try_remove_deref && snippet.starts_with('*') { // The snippet doesn't start with `*` in (e.g.) index // expressions `a[b]`, which roughly desugar to // `*Index::index(&a, b)` or // `*IndexMut::index_mut(&mut a, b)`. err.span_suggestion_with_applicability( span, "consider removing the `*`", snippet[1..].to_owned(), Applicability::Unspecified, ); } else { err.span_suggestion_with_applicability( span, "consider borrowing here", format!("&{}", snippet), Applicability::Unspecified, ); } binds_to.sort(); binds_to.dedup(); self.add_move_error_details(err, &binds_to); } GroupedMoveError::MovesFromValue { mut binds_to, .. } => { binds_to.sort(); binds_to.dedup(); self.add_move_error_suggestions(err, &binds_to); self.add_move_error_details(err, &binds_to); } // No binding. Nothing to suggest. GroupedMoveError::OtherIllegalMove { .. } => (), } } fn add_move_error_suggestions( &self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local], ) { let mut suggestions: Vec<(Span, &str, String)> = Vec::new(); for local in binds_to { let bind_to = &self.mir.local_decls[*local]; if let Some( ClearCrossCrate::Set(BindingForm::Var(VarBindingForm { pat_span, .. })) ) = bind_to.is_user_variable { let pat_snippet = self.infcx.tcx.sess.source_map() .span_to_snippet(pat_span) .unwrap(); if pat_snippet.starts_with('&') { let pat_snippet = pat_snippet[1..].trim_left(); let suggestion; let to_remove; if pat_snippet.starts_with("mut") && pat_snippet["mut".len()..].starts_with(Pattern_White_Space) { suggestion = pat_snippet["mut".len()..].trim_left(); to_remove = "&mut"; } else { suggestion = pat_snippet; to_remove = "&"; } suggestions.push(( pat_span, to_remove, suggestion.to_owned(), )); } } } suggestions.sort_unstable_by_key(|&(span, _, _)| span); suggestions.dedup_by_key(|&mut (span, _, _)| span); for (span, to_remove, suggestion) in suggestions { err.span_suggestion_with_applicability( span, &format!("consider removing the `{}`", to_remove), suggestion, Applicability::MachineApplicable, ); } } fn add_move_error_details( &self, err: &mut DiagnosticBuilder<'a>, binds_to: &[Local], ) { let mut noncopy_var_spans = Vec::new(); for (j, local) in binds_to.into_iter().enumerate() { let bind_to = &self.mir.local_decls[*local]; let binding_span = bind_to.source_info.span; if j == 0 { err.span_label(binding_span, format!("data moved here")); } else { err.span_label(binding_span, format!("...and here")); } if binds_to.len() == 1 { err.span_note( binding_span, &format!( "move occurs because `{}` has type `{}`, \ which does not implement the `Copy` trait", bind_to.name.unwrap(), bind_to.ty ), ); } else { noncopy_var_spans.push(binding_span); } } if binds_to.len() > 1 { err.span_note( noncopy_var_spans, "move occurs because these variables have types that \ don't implement the `Copy` trait", ); } } }
use futures_util::stream::{self, Stream}; use http::{Request, StatusCode}; use platform::Body; use serde::{de::DeserializeOwned, Deserialize}; use snafu::ResultExt; use url::Url; macro_rules! api_url { ($resource:ident) => { url::Url::parse(concat!( "https://www.speedrun.com/api/v1/", stringify!($resource) )) .unwrap() }; } mod platform; pub mod categories; pub mod common; pub mod games; pub mod leaderboards; pub mod platforms; pub mod regions; pub mod runs; pub use { categories::Category, games::Game, leaderboards::Leaderboard, platforms::Platform, regions::Region, runs::Run, }; #[derive(Debug, snafu::Snafu)] pub enum Error { /// Failed receiving the response from speedrun.com. Response { source: platform::Error }, #[snafu(display("HTTP Status Code: {}", status.canonical_reason().unwrap_or_else(|| status.as_str())))] Status { status: StatusCode }, #[snafu(display("{}", message))] Api { status: StatusCode, message: Box<str>, }, /// Failed parsing the response from speedrun.com. Json { source: serde_json::Error }, } #[derive(Deserialize)] struct ApiError { message: Box<str>, } #[repr(transparent)] #[derive(Debug, Deserialize)] pub struct Data<T> { pub data: T, } #[derive(Debug, Deserialize)] struct Page<T> { data: Vec<T>, pagination: Pagination, } #[derive(Debug, Deserialize)] struct Pagination { offset: u64, max: u64, size: u64, links: Vec<PaginationLink>, } #[derive(Debug, Deserialize)] #[serde(tag = "rel")] enum PaginationLink { #[serde(rename = "next")] Next { uri: Box<str> }, #[serde(rename = "prev")] Previous { uri: Box<str> }, } pub use platform::Client; async fn execute_request_without_data<T: DeserializeOwned>( client: &Client, url: Url, ) -> Result<T, Error> { let response = client .request(Request::get(url.as_str()).body(Body::empty()).unwrap()) .await .context(Response)?; let status = response.status(); if !status.is_success() { if let Ok(reader) = platform::recv_reader(response.into_body()).await { if let Ok(error) = serde_json::from_reader::<_, ApiError>(reader) { return Err(Error::Api { status, message: error.message, }); } } return Err(Error::Status { status }); } let reader = platform::recv_reader(response.into_body()) .await .context(Response)?; serde_json::from_reader(reader).context(Json) } async fn execute_request<T: DeserializeOwned>(client: &Client, url: Url) -> Result<T, Error> { let data: Data<T> = execute_request_without_data(client, url).await?; Ok(data.data) } fn execute_paginated_request<T: DeserializeOwned + 'static>( client: &Client, url: Url, ) -> impl Stream<Item = Result<T, Error>> + '_ { stream::unfold( (Vec::new().into_iter(), Some(url)), move |(mut remaining_elements, url)| { async move { Some(if let Some(element) = remaining_elements.next() { (Ok(element), (remaining_elements, url)) } else { match execute_request_without_data::<Page<T>>(client, url?).await { Ok(page) => { let mut remaining_elements = page.data.into_iter(); ( Ok(remaining_elements.next()?), ( remaining_elements, page.pagination .links .into_iter() .find_map(|l| { if let PaginationLink::Next { uri } = l { Some(uri) } else { None } }) .and_then(|uri| Url::parse(&uri).ok()), ), ) } Err(e) => (Err(e), (remaining_elements, None)), } }) } }, ) }
/*! Operation implementations This module contains implementations for operations ([crate::ops]) on OSCAR Schema specifications. !*/ mod oscar_doc; mod oscar_txt; pub(crate) use oscar_doc::OscarDoc; pub(crate) use oscar_txt::OscarTxt;
// Copyright 2020 - 2021 Alex Dukhno // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use data_manipulation::UntypedQuery; use data_repr::scalar::ScalarValue; use postgre_sql::query_ast::Query; use types::SqlTypeFamily; #[derive(Clone, Debug, PartialEq)] pub enum PreparedStatementState { Parsed(Query), Described { query: UntypedQuery, param_types: Vec<u32> }, ParsedWithParams { query: Query, param_types: Vec<u32> }, } #[derive(Clone, Debug, PartialEq)] pub struct PreparedStatement { state: PreparedStatementState, sql: String, } impl PreparedStatement { pub fn parsed(sql: String, query: Query) -> PreparedStatement { PreparedStatement { state: PreparedStatementState::Parsed(query), sql, } } pub fn param_types(&self) -> Option<&[u32]> { match &self.state { PreparedStatementState::Parsed(_) => None, PreparedStatementState::Described { param_types, .. } => Some(&param_types), PreparedStatementState::ParsedWithParams { param_types, .. } => Some(&param_types), } } pub fn query(&self) -> Option<Query> { match &self.state { PreparedStatementState::Parsed(query) => Some(query.clone()), PreparedStatementState::Described { .. } => None, PreparedStatementState::ParsedWithParams { query, .. } => Some(query.clone()), } } pub fn described(&mut self, query: UntypedQuery, param_types: Vec<u32>) { self.state = PreparedStatementState::Described { query, param_types }; } pub fn parsed_with_params(&mut self, query: Query, param_types: Vec<u32>) { self.state = PreparedStatementState::ParsedWithParams { query, param_types }; } pub fn raw_query(&self) -> &str { self.sql.as_str() } } /// A portal represents the execution state of a running or runnable query. #[derive(Clone, Debug)] pub struct Portal { /// The name of the prepared statement that is bound to this portal. statement_name: String, /// The bound SQL statement from the prepared statement. stmt: UntypedQuery, /// The desired output format for each column in the result set. result_formats: Vec<i16>, param_values: Vec<ScalarValue>, param_types: Vec<SqlTypeFamily>, } impl Portal { /// Constructs a new `Portal`. pub fn new( statement_name: String, stmt: UntypedQuery, result_formats: Vec<i16>, param_values: Vec<ScalarValue>, param_types: Vec<SqlTypeFamily>, ) -> Portal { Portal { statement_name, stmt, result_formats, param_values, param_types, } } /// Returns the bound SQL statement. pub fn stmt(&self) -> UntypedQuery { self.stmt.clone() } #[allow(dead_code)] pub fn stmt_name(&self) -> &str { self.statement_name.as_str() } pub fn param_values(&self) -> Vec<ScalarValue> { self.param_values.clone() } pub fn param_types(&self) -> &[SqlTypeFamily] { &self.param_types } }
use rule::Rule; #[test] fn between() { let code = "zzz"; let z = Rule::new(|_, _| Ok(34)); z.literal("z"); let test1: Rule<i32> = Rule::default(); test1.between(1, 3, &z); if let Ok(branches) = test1.scan(&code) { assert_eq!(branches[0], 34); assert_eq!(branches[1], 34); assert_eq!(branches[2], 34); } else { assert!(true); } let test2: Rule<i32> = Rule::default(); test2.between(0, 10, &z); if let Ok(branches) = test2.scan(&code) { assert_eq!(branches[0], 34); assert_eq!(branches[1], 34); assert_eq!(branches[2], 34); } else { assert!(false); } let test3: Rule<i32> = Rule::default(); test3.between(4, 5, &z); if let Ok(_) = test3.scan(&code) { assert!(false); } else { assert!(true); } }
// raii.rs fn create_box() { // Выделить память для целого число в куче let _box1 = Box::new(3i32); // `_box1` здесь уничтожается, а память освобождается } fn main() { // Выделить память для целого число в куче let _box2 = Box::new(5i32); // Вложенная область видимости: { // Выделить память для ещё одного целого число в куче let _box3 = Box::new(4i32); // `_box3` здесь уничтожается, а память освобождается } // Создаём большое количество упаковок. Просто потому что можем. // Здесь нет необходимости освобождать память вручную! for _ in 0u32..1_000 { create_box(); } // `_box2` здесь уничтожается, а память освобождается }
use super::Graph; use std::collections::BinaryHeap; impl Graph { pub fn dijkstra(&self, s: usize) -> Vec<Option<i64>> { let mut v = vec![None; self.node_size]; let mut pq = BinaryHeap::new(); pq.push(Node{node:s, cost:0}); while let Some(tp) = pq.pop() { if v[tp.node] != None { continue; } v[tp.node] = Some(tp.cost); let from = tp.cost; for e in self.edge[tp.node].iter() { if let Some(to) = v[e.0] { if from + e.1 < to { pq.push(Node{node:e.0, cost:from + e.1}) } }else{ pq.push(Node{node:e.0, cost:from + e.1}) } } } v } } #[derive(Copy, Clone, Eq, PartialEq)] struct Node { node: usize, cost: i64 } use std::cmp::Ordering; impl Ord for Node { fn cmp(&self, other: &Self) -> Ordering { other.cost.cmp(&self.cost) } } impl PartialOrd for Node { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } #[test] fn test() { let mut g = Graph::new(6); g.add_edge(0,1,3); g.add_edge(0,2,1); g.add_edge(2,1,1); g.add_edge(2,4,3); g.add_edge(3,0,3); assert_eq!(g.dijkstra(0), vec![Some(0), Some(2), Some(1), None, Some(4), None]); }
//! Error types use num_derive::FromPrimitive; use solana_program::program_error::ProgramError; use num_traits::FromPrimitive; use thiserror::Error; /// Errors that may be returned by the program. #[derive(Clone, Debug, Eq, Error, FromPrimitive, PartialEq)] pub enum Error { /// Owner mismatch #[error("Owner mismatch")] // 0 OwnerMismatch, #[error("Unknown error")] UnknownError, } impl From<Error> for ProgramError { fn from(e: Error) -> Self { ProgramError::Custom(e as u32) } } impl From<ProgramError> for Error { fn from(err: ProgramError) -> Self { match err { ProgramError::Custom(code) => Error::from_u32(code).unwrap_or(Error::UnknownError), _ => Error::UnknownError, } } }
///! This module defines a trait which represents the idea of equality without ///! the possibility of coercion. Its usage in Firefly is to extend the behavior ///! of `Eq` for terms to respect the semantics of the `=:=` and `=/=` operators. /// This trait extends the notion of equality provided by `Eq` to cover the distinction /// between the non-strict (`==` and `/=`), and strict (`=:=` and `=/=`) equality operators. /// /// ExactEq has a default implemention for all `Eq` implementors. However, for types which distinguish /// between strict/non-strict equality, this trait should be specialized on those types. pub trait ExactEq: Eq { fn exact_eq(&self, other: &Self) -> bool; fn exact_ne(&self, other: &Self) -> bool; } impl<T: ?Sized + Eq> ExactEq for T { default fn exact_eq(&self, other: &Self) -> bool { self.eq(other) } default fn exact_ne(&self, other: &Self) -> bool { self.ne(other) } }
/* Copyright 2020 Timo Saarinen Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ //! AIS VDM/VDO data structures pub(crate) mod vdm_t1t2t3; pub(crate) mod vdm_t4; pub(crate) mod vdm_t5; pub(crate) mod vdm_t6; pub(crate) mod vdm_t9; pub(crate) mod vdm_t10; pub(crate) mod vdm_t11; pub(crate) mod vdm_t12; pub(crate) mod vdm_t13; pub(crate) mod vdm_t14; pub(crate) mod vdm_t15; pub(crate) mod vdm_t16; pub(crate) mod vdm_t17; pub(crate) mod vdm_t18; pub(crate) mod vdm_t19; pub(crate) mod vdm_t20; pub(crate) mod vdm_t21; pub(crate) mod vdm_t22; pub(crate) mod vdm_t23; pub(crate) mod vdm_t24; pub(crate) mod vdm_t25; pub(crate) mod vdm_t26; pub(crate) mod vdm_t27; use super::*; pub use vdm_t4::BaseStationReport; pub use vdm_t6::BinaryAddressedMessage; pub use vdm_t9::StandardSarAircraftPositionReport; pub use vdm_t10::UtcDateInquiry; pub use vdm_t12::AddressedSafetyRelatedMessage; pub use vdm_t13::SafetyRelatedAcknowledgement; pub use vdm_t14::SafetyRelatedBroadcastMessage; pub use vdm_t15::{Interrogation, InterrogationCase}; pub use vdm_t16::AssignmentModeCommand; pub use vdm_t17::DgnssBroadcastBinaryMessage; pub use vdm_t20::{DataLinkManagementMessage}; pub use vdm_t21::{AidToNavigationReport, NavAidType}; pub use vdm_t22::{ChannelManagement}; pub use vdm_t23::{GroupAssignmentCommand}; pub use vdm_t25::{SingleSlotBinaryMessage}; pub use vdm_t26::{MultipleSlotBinaryMessage}; // ------------------------------------------------------------------------------------------------- /// AIS station based on talker id #[derive(Clone, Copy, Debug, PartialEq)] pub enum Station { BaseStation, // !AB DependentAisBaseStation, // !AD MobileStation, // !AI (the most common one) AidToNavigationStation, // !AN AisReceivingStation, // !AR LimitedBaseStation, // !AS AisTransmittingStation, // !AT RepeaterStation, // !AX Other, // !BS, !SA, etc. } impl Default for Station { fn default() -> Station { Station::Other } } impl std::fmt::Display for Station { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { Station::BaseStation => write!(f, "base station"), Station::DependentAisBaseStation => write!(f, "dependent AIS base station"), Station::MobileStation => write!(f, "mobile station"), Station::AidToNavigationStation => write!(f, "aid to navigation station"), Station::AisReceivingStation => write!(f, "ais receiving station"), Station::LimitedBaseStation => write!(f, "limited base station"), Station::AisTransmittingStation => write!(f, "AIS transmitting station"), Station::RepeaterStation => write!(f, "repeater station"), Station::Other => write!(f, "other"), } } } // ------------------------------------------------------------------------------------------------- /// Types 1, 2, 3 and 18: Position Report Class A, and Long Range AIS Broadcast message #[derive(Default, Clone, Debug, PartialEq)] pub struct VesselDynamicData { /// True if the data is about own vessel, false if about other. pub own_vessel: bool, /// AIS station type. pub station: Station, /// Class A or Class B pub ais_type: AisClass, /// User ID (30 bits) pub mmsi: u32, // TODO: timestamp /// Navigation status pub nav_status: NavigationStatus, /// Accurate ROT_sensor (±0..708°/min) if available. pub rot: Option<f64>, /// ROT direction when turn is more than 5°/30s. pub rot_direction: Option<RotDirection>, /// Speed over ground in knots pub sog_knots: Option<f64>, /// Position accuracy: true = high (<= 10 m), false = low (> 10 m) pub high_position_accuracy: bool, /// Latitude pub latitude: Option<f64>, /// Longitude pub longitude: Option<f64>, /// Course over ground pub cog: Option<f64>, /// True heading (0-359) pub heading_true: Option<f64>, /// Derived from UTC second (6 bits) pub timestamp_seconds: u8, /// Positioning system metadata (included in seconds in UTC timestamp) pub positioning_system_meta: Option<PositioningSystemMeta>, /// GNSS position status (Type 27): /// true = current GNSS position /// false = not GNSS position pub current_gnss_position: Option<bool>, /// Special manoeuvre indicator. false = not engaged in special manoeuvre, /// true = engaged in special manouvre. pub special_manoeuvre: Option<bool>, /// Riverine And Inland Navigation systems blue sign: /// RAIM (Receiver autonomous integrity monitoring) flag of electronic position /// fixing device; false = RAIM not in use = default; true = RAIM in use pub raim_flag: bool, /// Class B unit flag: false = Class B SOTDMA unit, true = Class B "CS" unit. pub class_b_unit_flag: Option<bool>, /// Class B display: /// false = No display available; not capable of displaying Message 12 and 14 /// true = Equipped with integrated display displaying Message 12 and 14 pub class_b_display: Option<bool>, /// Class B DSC: /// false = Not equipped with DSC function /// true = Equipped with DSC function (dedicated or time-shared pub class_b_dsc: Option<bool>, /// Class B band flag: /// false = Capable of operating over the upper 525 kHz band of the marine band /// true = Capable of operating over the whole marine band (irrelevant if /// “Class B Message 22 flag” is 0) pub class_b_band_flag: Option<bool>, /// Class B Message 22 flag: /// false = No frequency management via Message 22 , operating on AIS1, AIS2 only /// true = Frequency management via Message 22 pub class_b_msg22_flag: Option<bool>, /// Mode flag: /// false = Station operating in autonomous and continuous mode = default /// true = Station operating in assigned mode pub class_b_mode_flag: Option<bool>, /// Communication state selector flag /// false = SOTDMA communication state follows /// true = ITDMA communication state follows (always “1” for Class-B “CS”) pub class_b_css_flag: Option<bool>, /// Communication state /// Diagnostic information for the radio system. /// https://www.itu.int/dms_pubrec/itu-r/rec/m/R-REC-M.1371-1-200108-S!!PDF-E.pdf pub radio_status: Option<u32>, } /// AIS class which is either Class A or Class B #[derive(Clone, Copy, Debug, PartialEq)] pub enum AisClass { /// AIS class not known. Unknown, /// AIS class A. ClassA, // Message types 1, 2, 3, 5 /// AIS class B. ClassB, // Message types 14, 18, 19, 24 } impl Default for AisClass { fn default() -> AisClass { AisClass::Unknown } } impl std::fmt::Display for AisClass { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { AisClass::Unknown => write!(f, "unknown"), AisClass::ClassA => write!(f, "Class A"), AisClass::ClassB => write!(f, "Class B"), } } } impl LatLon for VesselDynamicData { fn latitude(&self) -> Option<f64> { self.latitude } fn longitude(&self) -> Option<f64> { self.longitude } } /// Navigation status for VesselDynamicData #[derive(Clone, Copy, Debug, PartialEq)] pub enum NavigationStatus { UnderWayUsingEngine = 0, // 0 AtAnchor = 1, // 1 NotUnderCommand = 2, // 2 RestrictedManoeuverability = 3, // 3 ConstrainedByDraught = 4, // 4 Moored = 5, // 5 Aground = 6, // 6 EngagedInFishing = 7, // 7 UnderWaySailing = 8, // 8 Reserved9 = 9, // 9, may be renamed in the future Reserved10 = 10, // 10, may be renamed in the future Reserved11 = 11, // 11, may be renamed in the future Reserved12 = 12, // 12, may be renamed in the future Reserved13 = 13, // 13, may be renamed in the future AisSartIsActive = 14, // 14 NotDefined = 15, // 15 } impl NavigationStatus { pub fn new(nav_status: u8) -> NavigationStatus { match nav_status { 0 => NavigationStatus::UnderWayUsingEngine, 1 => NavigationStatus::AtAnchor, 2 => NavigationStatus::NotUnderCommand, 3 => NavigationStatus::RestrictedManoeuverability, 4 => NavigationStatus::ConstrainedByDraught, 5 => NavigationStatus::Moored, 6 => NavigationStatus::Aground, 7 => NavigationStatus::EngagedInFishing, 8 => NavigationStatus::UnderWaySailing, 9 => NavigationStatus::Reserved9, 10 => NavigationStatus::Reserved10, 11 => NavigationStatus::Reserved11, 12 => NavigationStatus::Reserved12, 13 => NavigationStatus::Reserved13, 14 => NavigationStatus::AisSartIsActive, 15 => NavigationStatus::NotDefined, _ => NavigationStatus::NotDefined, } } pub fn to_value(&self) -> u8 { *self as u8 } } impl std::fmt::Display for NavigationStatus { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { NavigationStatus::UnderWayUsingEngine => write!(f, "under way using engine"), NavigationStatus::AtAnchor => write!(f, "at anchor"), NavigationStatus::NotUnderCommand => write!(f, "not under command"), NavigationStatus::RestrictedManoeuverability => { write!(f, "restricted manoeuverability") } NavigationStatus::ConstrainedByDraught => write!(f, "constrained by draught"), NavigationStatus::Moored => write!(f, "moored"), NavigationStatus::Aground => write!(f, "aground"), NavigationStatus::EngagedInFishing => write!(f, "engaged in fishing"), NavigationStatus::UnderWaySailing => write!(f, "under way sailing"), NavigationStatus::Reserved9 => write!(f, "(reserved9)"), NavigationStatus::Reserved10 => write!(f, "(reserved10)"), NavigationStatus::Reserved11 => write!(f, "(reserved11)"), NavigationStatus::Reserved12 => write!(f, "(reserved12)"), NavigationStatus::Reserved13 => write!(f, "(reserved13)"), NavigationStatus::AisSartIsActive => write!(f, "ais sart is active"), NavigationStatus::NotDefined => write!(f, "(notDefined)"), } } } impl Default for NavigationStatus { fn default() -> NavigationStatus { NavigationStatus::NotDefined } } // ------------------------------------------------------------------------------------------------- /// Location metadata about positioning system #[derive(Clone, Copy, Debug, PartialEq)] pub enum PositioningSystemMeta { Operative, // When timestamp second is 0-59 ManualInputMode, DeadReckoningMode, Inoperative, } impl std::fmt::Display for PositioningSystemMeta { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { PositioningSystemMeta::Operative => write!(f, "operative"), PositioningSystemMeta::ManualInputMode => write!(f, "manual input mode"), PositioningSystemMeta::DeadReckoningMode => write!(f, "dead reckoning mode"), PositioningSystemMeta::Inoperative => write!(f, "inoperative"), } } } // ------------------------------------------------------------------------------------------------- /// Vessel rotation direction #[derive(Clone, Copy, Debug, PartialEq)] pub enum RotDirection { /// Turning port (left, when seen by an observer aboard the vessel looking forward) Port, /// Not turning Center, /// Turning starboard (right, when seen by an observer aboard the vessel looking forward) Starboard, } impl Default for RotDirection { fn default() -> RotDirection { RotDirection::Center } } impl std::fmt::Display for RotDirection { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { RotDirection::Port => write!(f, "port"), RotDirection::Center => write!(f, "center"), RotDirection::Starboard => write!(f, "starboard"), } } } // ------------------------------------------------------------------------------------------------- /// Types 5 and 24: Ship static voyage related data, and boat static data report. #[derive(Default, Clone, Debug, PartialEq)] pub struct VesselStaticData { /// True if the data is about own vessel, false if about other vessel. pub own_vessel: bool, /// Class A or Class B pub ais_type: AisClass, /// User ID (30 bits) pub mmsi: u32, /// AIS version indicator (2 bits) pub ais_version_indicator: u8, /// IMO number (1-999999999; 30 bits). pub imo_number: Option<u32>, /// Call sign (7 ASCII characters) pub call_sign: Option<String>, /// Name (20 ASCII characters) pub name: Option<String>, /// Type of ship (first 4 of 8 bits) pub ship_type: ShipType, /// Type of ship and cargo (last 4 of 8 bits) pub cargo_type: CargoType, /// Class B Vendor ID pub equipment_vendor_id: Option<String>, /// Class B unite model code pub equipment_model: Option<u8>, /// Class B serial number pub equipment_serial_number: Option<u32>, /// Overall dimension / reference for position A (9 bits) pub dimension_to_bow: Option<u16>, /// Overall dimension / reference for position B (9 bits) pub dimension_to_stern: Option<u16>, /// Overall dimension / reference for position C (6 bits) pub dimension_to_port: Option<u16>, /// Overall dimension / reference for position C (6 bits) pub dimension_to_starboard: Option<u16>, // Type of electronic position fixing device. pub position_fix_type: Option<PositionFixType>, /// ETA (20 bits) pub eta: Option<DateTime<Utc>>, /// Maximum present static draught in decimetres (1-255; 8 bits) pub draught10: Option<u8>, /// Destination (120 ASCII characters) pub destination: Option<String>, /// Class B mothership MMSI pub mothership_mmsi: Option<u32>, } // ------------------------------------------------------------------------------------------------- /// Ship type derived from combined ship and cargo type field #[derive(Clone, Copy, Debug, PartialEq)] pub enum ShipType { NotAvailable = 0, // 0 Reserved1 = 10, // 1x WingInGround = 20, // 2x Fishing = 30, // 30 Towing = 31, // 31 TowingLong = 32, // 32; Towing: length exceeds 200m or breadth exceeds 25m DredgingOrUnderwaterOps = 33, // 33 DivingOps = 34, // 34 MilitaryOps = 35, // 35 Sailing = 36, // 36 PleasureCraft = 37, // 37 Reserved38 = 38, // 38 Reserved39 = 39, // 39 HighSpeedCraft = 40, // 4x Pilot = 50, // 50 SearchAndRescue = 51, // 51 Tug = 52, // 52 PortTender = 53, // 53 AntiPollutionEquipment = 54, // 54 LawEnforcement = 55, // 55 SpareLocal56 = 56, // 56 SpareLocal57 = 57, // 57 MedicalTransport = 58, // 58 Noncombatant = 59, // 59; Noncombatant ship according to RR Resolution No. 18 Passenger = 60, // 6x Cargo = 70, // 7x Tanker = 80, // 8x Other = 90, // 9x } impl ShipType { /// Construct a new `ShipType` using the higher bits of the ship and cargo type field of NMEA. pub fn new(raw: u8) -> ShipType { match raw { 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 => ShipType::NotAvailable, 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 => ShipType::Reserved1, 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 => ShipType::WingInGround, 30 => ShipType::Fishing, 31 => ShipType::Towing, 32 => ShipType::TowingLong, 33 => ShipType::DredgingOrUnderwaterOps, 34 => ShipType::DivingOps, 35 => ShipType::MilitaryOps, 36 => ShipType::Sailing, 37 => ShipType::PleasureCraft, 38 => ShipType::Reserved38, 39 => ShipType::Reserved39, 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 => ShipType::HighSpeedCraft, 50 => ShipType::Pilot, 51 => ShipType::SearchAndRescue, 52 => ShipType::Tug, 53 => ShipType::PortTender, 54 => ShipType::AntiPollutionEquipment, 55 => ShipType::LawEnforcement, 56 => ShipType::SpareLocal56, 57 => ShipType::SpareLocal57, 58 => ShipType::MedicalTransport, 59 => ShipType::Noncombatant, 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 => ShipType::Passenger, 70 | 71 | 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 => ShipType::Cargo, 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 => ShipType::Cargo, 90 | 91 | 92 | 93 | 94 | 95 | 96 | 97 | 98 | 99 => ShipType::Cargo, _ => { warn!("Unexpected ship and cargo type: {}", raw); ShipType::NotAvailable } } } pub fn to_value(&self) -> u8 { *self as u8 } } impl Default for ShipType { fn default() -> ShipType { ShipType::NotAvailable } } impl std::fmt::Display for ShipType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { ShipType::NotAvailable => write!(f, "(not available)"), ShipType::Reserved1 => write!(f, "(reserved)"), ShipType::WingInGround => write!(f, "wing in ground"), ShipType::Fishing => write!(f, "fishing"), ShipType::Towing => write!(f, "towing"), ShipType::TowingLong => write!(f, "towing, long"), ShipType::DredgingOrUnderwaterOps => write!(f, "dredging or underwater ops"), ShipType::DivingOps => write!(f, "diving ops"), ShipType::MilitaryOps => write!(f, "military ops"), ShipType::Sailing => write!(f, "sailing"), ShipType::PleasureCraft => write!(f, "pleasure craft"), ShipType::Reserved38 => write!(f, "(reserved)"), ShipType::Reserved39 => write!(f, "(reserved)"), ShipType::HighSpeedCraft => write!(f, "high-speed craft"), ShipType::Pilot => write!(f, "pilot"), ShipType::SearchAndRescue => write!(f, "search and rescue"), ShipType::Tug => write!(f, "tug"), ShipType::PortTender => write!(f, "port tender"), ShipType::AntiPollutionEquipment => write!(f, "anti-pollution equipment"), ShipType::LawEnforcement => write!(f, "law enforcement"), ShipType::SpareLocal56 => write!(f, "(local)"), ShipType::SpareLocal57 => write!(f, "(local)"), ShipType::MedicalTransport => write!(f, "medical transport"), ShipType::Noncombatant => write!(f, "noncombatant"), ShipType::Passenger => write!(f, "passenger"), ShipType::Cargo => write!(f, "cargo"), ShipType::Tanker => write!(f, "tanker"), ShipType::Other => write!(f, "other"), } } } // ------------------------------------------------------------------------------------------------- /// Cargo type derived from combined ship and cargo type field #[derive(Clone, Copy, Debug, PartialEq)] pub enum CargoType { Undefined = 10, // x0 HazardousCategoryA = 11, // x1 HazardousCategoryB = 12, // x2 HazardousCategoryC = 13, // x3 HazardousCategoryD = 14, // x4 Reserved5 = 15, // x5 Reserved6 = 16, // x6 Reserved7 = 17, // x7 Reserved8 = 18, // x8 Reserved9 = 19, // x9 } impl CargoType { /// Construct a new `CargoType` using the higher bits of the ship and cargo type field of NMEA. pub fn new(raw: u8) -> CargoType { match raw { 10 | 20 | 40 | 60 | 70 | 80 | 90 => CargoType::Undefined, 11 | 21 | 41 | 61 | 71 | 81 | 91 => CargoType::HazardousCategoryA, 12 | 22 | 42 | 62 | 72 | 82 | 92 => CargoType::HazardousCategoryB, 13 | 23 | 43 | 63 | 73 | 83 | 93 => CargoType::HazardousCategoryC, 14 | 24 | 44 | 64 | 74 | 84 | 94 => CargoType::HazardousCategoryD, 15 | 25 | 45 | 65 | 75 | 85 | 95 => CargoType::Reserved5, 16 | 26 | 46 | 66 | 76 | 86 | 96 => CargoType::Reserved6, 17 | 27 | 47 | 67 | 77 | 87 | 97 => CargoType::Reserved7, 18 | 28 | 48 | 68 | 78 | 88 | 98 => CargoType::Reserved8, 19 | 29 | 49 | 69 | 79 | 89 | 99 => CargoType::Reserved9, _ => { warn!("Unexpected ship and cargo type: {}", raw); CargoType::Undefined } } } pub fn to_value(&self) -> u8 { *self as u8 } } impl std::fmt::Display for CargoType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { CargoType::Undefined => write!(f, "undefined"), CargoType::HazardousCategoryA => write!(f, "hazardous category A"), CargoType::HazardousCategoryB => write!(f, "hazardous category B"), CargoType::HazardousCategoryC => write!(f, "hazardous category C"), CargoType::HazardousCategoryD => write!(f, "hazardous category D"), CargoType::Reserved5 => write!(f, "(reserved)"), CargoType::Reserved6 => write!(f, "(reserved)"), CargoType::Reserved7 => write!(f, "(reserved)"), CargoType::Reserved8 => write!(f, "(reserved)"), CargoType::Reserved9 => write!(f, "(reserved)"), } } } impl Default for CargoType { fn default() -> CargoType { CargoType::Undefined } } // ------------------------------------------------------------------------------------------------- /// EPFD position fix types #[derive(Clone, Copy, Debug, PartialEq)] pub enum PositionFixType { Undefined = 0, // 0 GPS = 1, // 1 GLONASS = 2, // 2 GPSGLONASS = 3, // 3 LoranC = 4, // 4 Chayka = 5, // 5 IntegratedNavigationSystem = 6, // 6 Surveyed = 7, // 7 Galileo = 8, // 8 } impl PositionFixType { pub fn new(raw: u8) -> PositionFixType { match raw { 0 => PositionFixType::Undefined, 1 => PositionFixType::GPS, 2 => PositionFixType::GLONASS, 3 => PositionFixType::GPSGLONASS, 4 => PositionFixType::LoranC, 5 => PositionFixType::Chayka, 6 => PositionFixType::IntegratedNavigationSystem, 7 => PositionFixType::Surveyed, 8 => PositionFixType::Galileo, _ => { warn!("Unrecognized position fix type: {}", raw); PositionFixType::Undefined } } } pub fn to_value(&self) -> u8 { *self as u8 } } impl std::fmt::Display for PositionFixType { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match self { PositionFixType::Undefined => write!(f, "undefined"), PositionFixType::GPS => write!(f, "GPS"), PositionFixType::GLONASS => write!(f, "GLONASS"), PositionFixType::GPSGLONASS => write!(f, "GPS/GLONASS"), PositionFixType::LoranC => write!(f, "Loran-C"), PositionFixType::Chayka => write!(f, "Chayka"), PositionFixType::IntegratedNavigationSystem => { write!(f, "integrated navigation system") } PositionFixType::Surveyed => write!(f, "surveyed"), PositionFixType::Galileo => write!(f, "Galileo"), } } } impl VesselStaticData { /// Decode ISO 3166 country code from MID part of MMSI. pub fn country(&self) -> Option<&'static str> { match self.mmsi / 1000000 { // Mapping generated with mid-to-iso3166.py 201 => Some("AL"), // Albania 202 => Some("AD"), // Andorra 203 => Some("AT"), // Austria 204 => Some("PT"), // Portugal 205 => Some("BE"), // Belgium 206 => Some("BY"), // Belarus 207 => Some("BG"), // Bulgaria 208 => Some("VA"), // Vatican City State 209 => Some("CY"), // Cyprus 210 => Some("CY"), // Cyprus 211 => Some("DE"), // Germany 212 => Some("CY"), // Cyprus 213 => Some("GE"), // Georgia 214 => Some("MD"), // Moldova 215 => Some("MT"), // Malta 216 => Some("AM"), // Armenia 218 => Some("DE"), // Germany 219 => Some("DK"), // Denmark 220 => Some("DK"), // Denmark 224 => Some("ES"), // Spain 225 => Some("ES"), // Spain 226 => Some("FR"), // France 227 => Some("FR"), // France 228 => Some("FR"), // France 229 => Some("MT"), // Malta 230 => Some("FI"), // Finland 231 => Some("FO"), // Faroe Islands 232 => Some("GB"), // United Kingdom of Great Britain and Northern Ireland 233 => Some("GB"), // United Kingdom of Great Britain and Northern Ireland 234 => Some("GB"), // United Kingdom of Great Britain and Northern Ireland 235 => Some("GB"), // United Kingdom of Great Britain and Northern Ireland 236 => Some("GI"), // Gibraltar 237 => Some("GR"), // Greece 238 => Some("HR"), // Croatia 239 => Some("GR"), // Greece 240 => Some("GR"), // Greece 241 => Some("GR"), // Greece 242 => Some("MA"), // Morocco 243 => Some("HU"), // Hungary 244 => Some("NL"), // Netherlands 245 => Some("NL"), // Netherlands 246 => Some("NL"), // Netherlands 247 => Some("IT"), // Italy 248 => Some("MT"), // Malta 249 => Some("MT"), // Malta 250 => Some("IE"), // Ireland 251 => Some("IS"), // Iceland 252 => Some("LI"), // Liechtenstein 253 => Some("LU"), // Luxembourg 254 => Some("MC"), // Monaco 255 => Some("PT"), // Portugal 256 => Some("MT"), // Malta 257 => Some("NO"), // Norway 258 => Some("NO"), // Norway 259 => Some("NO"), // Norway 261 => Some("PL"), // Poland 262 => Some("ME"), // Montenegro 263 => Some("PT"), // Portugal 264 => Some("RO"), // Romania 265 => Some("SE"), // Sweden 266 => Some("SE"), // Sweden 267 => Some("SK"), // Slovakia 268 => Some("SM"), // San Marino 269 => Some("CH"), // Switzerland 270 => Some("CZ"), // Czechia 271 => Some("TR"), // Turkey 272 => Some("UA"), // Ukraine 273 => Some("RU"), // Russian Federation 274 => Some("MK"), // Republic of North Macedonia 275 => Some("LV"), // Latvia 276 => Some("EE"), // Estonia 277 => Some("LT"), // Lithuania 278 => Some("SI"), // Slovenia 279 => Some("RS"), // Serbia 301 => Some("AI"), // Anguilla 303 => Some("US"), // United States of America 304 => Some("AG"), // Antigua and Barbuda 305 => Some("AG"), // Antigua and Barbuda 306 => Some("BQ"), // Bonaire, Sint Eustatius and Saba // 306 => Some("CW"), // Curaçao // 306 => Some("SX"), // Sint Maarten 307 => Some("AW"), // Aruba 308 => Some("BS"), // Bahamas 309 => Some("BS"), // Bahamas 310 => Some("BM"), // Bermuda 311 => Some("BS"), // Bahamas 312 => Some("BZ"), // Belize 314 => Some("BB"), // Barbados 316 => Some("CA"), // Canada 319 => Some("KY"), // Cayman Islands 321 => Some("CR"), // Costa Rica 323 => Some("CU"), // Cuba 325 => Some("DM"), // Dominica 327 => Some("DO"), // Dominican Republic 329 => Some("GP"), // Guadeloupe 330 => Some("GD"), // Grenada 331 => Some("GL"), // Greenland 332 => Some("GT"), // Guatemala 334 => Some("HN"), // Honduras 336 => Some("HT"), // Haiti 338 => Some("US"), // United States of America 339 => Some("JM"), // Jamaica 341 => Some("KN"), // Saint Kitts and Nevis 343 => Some("LC"), // Saint Lucia 345 => Some("MX"), // Mexico 347 => Some("MQ"), // Martinique 348 => Some("MS"), // Montserrat 350 => Some("NI"), // Nicaragua 351 => Some("PA"), // Panama 352 => Some("PA"), // Panama 353 => Some("PA"), // Panama 354 => Some("PA"), // Panama 355 => Some("PA"), // Panama 356 => Some("PA"), // Panama 357 => Some("PA"), // Panama 358 => Some("PR"), // Puerto Rico 359 => Some("SV"), // El Salvador 361 => Some("PM"), // Saint Pierre and Miquelon 362 => Some("TT"), // Trinidad and Tobago 364 => Some("TC"), // Turks and Caicos Islands 366 => Some("US"), // United States of America 367 => Some("US"), // United States of America 368 => Some("US"), // United States of America 369 => Some("US"), // United States of America 370 => Some("PA"), // Panama 371 => Some("PA"), // Panama 372 => Some("PA"), // Panama 373 => Some("PA"), // Panama 374 => Some("PA"), // Panama 375 => Some("VC"), // Saint Vincent and the Grenadines 376 => Some("VC"), // Saint Vincent and the Grenadines 377 => Some("VC"), // Saint Vincent and the Grenadines 378 => Some("VG"), // British Virgin Islands 379 => Some("VI"), // United States Virgin Islands 401 => Some("AF"), // Afghanistan 403 => Some("SA"), // Saudi Arabia 405 => Some("BD"), // Bangladesh 408 => Some("BH"), // Bahrain 410 => Some("BT"), // Bhutan 412 => Some("CN"), // China 413 => Some("CN"), // China 414 => Some("CN"), // China 416 => Some("TW"), // Taiwan 417 => Some("LK"), // Sri Lanka 419 => Some("IN"), // India 422 => Some("IR"), // Iran 423 => Some("AZ"), // Azerbaijan 425 => Some("IQ"), // Iraq 428 => Some("IL"), // Israel 431 => Some("JP"), // Japan 432 => Some("JP"), // Japan 434 => Some("TM"), // Turkmenistan 436 => Some("KZ"), // Kazakhstan 437 => Some("UZ"), // Uzbekistan 438 => Some("JO"), // Jordan 440 => Some("KR"), // Korea 441 => Some("KR"), // Korea 443 => Some("PS"), // Palestine, State of 445 => Some("KR"), // Korea 447 => Some("KW"), // Kuwait 450 => Some("LB"), // Lebanon 451 => Some("KG"), // Kyrgyzstan 453 => Some("MO"), // Macao 455 => Some("MV"), // Maldives 457 => Some("MN"), // Mongolia 459 => Some("NP"), // Nepal 461 => Some("OM"), // Oman 463 => Some("PK"), // Pakistan 466 => Some("QA"), // Qatar 468 => Some("SY"), // Syrian Arab Republic 470 => Some("AE"), // United Arab Emirates 471 => Some("AE"), // United Arab Emirates 472 => Some("TJ"), // Tajikistan 473 => Some("YE"), // Yemen 475 => Some("YE"), // Yemen 477 => Some("HK"), // Hong Kong 478 => Some("BA"), // Bosnia and Herzegovina 501 => Some("TF"), // French Southern Territories 503 => Some("AU"), // Australia 506 => Some("MM"), // Myanmar 508 => Some("BN"), // Brunei Darussalam 510 => Some("FM"), // Micronesia 511 => Some("PW"), // Palau 512 => Some("NZ"), // New Zealand 514 => Some("KH"), // Cambodia 515 => Some("KH"), // Cambodia 516 => Some("CX"), // Christmas Island 518 => Some("CK"), // Cook Islands 520 => Some("FJ"), // Fiji 523 => Some("CC"), // Cocos Islands 525 => Some("ID"), // Indonesia 529 => Some("KI"), // Kiribati 531 => Some("LA"), // Lao People's Democratic Republic 533 => Some("MY"), // Malaysia 536 => Some("MP"), // Northern Mariana Islands 538 => Some("MH"), // Marshall Islands 540 => Some("NC"), // New Caledonia 542 => Some("NU"), // Niue 544 => Some("NR"), // Nauru 546 => Some("PF"), // French Polynesia 548 => Some("PH"), // Philippines 550 => Some("TL"), // Timor-Leste 553 => Some("PG"), // Papua New Guinea 555 => Some("PN"), // Pitcairn 557 => Some("SB"), // Solomon Islands 559 => Some("AS"), // American Samoa 561 => Some("WS"), // Samoa 563 => Some("SG"), // Singapore 564 => Some("SG"), // Singapore 565 => Some("SG"), // Singapore 566 => Some("SG"), // Singapore 567 => Some("TH"), // Thailand 570 => Some("TO"), // Tonga 572 => Some("TV"), // Tuvalu 574 => Some("VN"), // Viet Nam 576 => Some("VU"), // Vanuatu 577 => Some("VU"), // Vanuatu 578 => Some("WF"), // Wallis and Futuna 601 => Some("ZA"), // South Africa 603 => Some("AO"), // Angola 605 => Some("DZ"), // Algeria 607 => Some("TF"), // French Southern Territories 608 => Some("SH"), // Saint Helena, Ascension and Tristan da Cunha 609 => Some("BI"), // Burundi 610 => Some("BJ"), // Benin 611 => Some("BW"), // Botswana 612 => Some("CF"), // Central African Republic 613 => Some("CM"), // Cameroon 615 => Some("CG"), // Congo 616 => Some("KM"), // Comoros 617 => Some("CV"), // Cabo Verde 618 => Some("TF"), // French Southern Territories 619 => Some("CI"), // Côte d'Ivoire 620 => Some("KM"), // Comoros 621 => Some("DJ"), // Djibouti 622 => Some("EG"), // Egypt 624 => Some("ET"), // Ethiopia 625 => Some("ER"), // Eritrea 626 => Some("GA"), // Gabon 627 => Some("GH"), // Ghana 629 => Some("GM"), // Gambia 630 => Some("GW"), // Guinea-Bissau 631 => Some("GQ"), // Equatorial Guinea 632 => Some("GN"), // Guinea 633 => Some("BF"), // Burkina Faso 634 => Some("KE"), // Kenya 635 => Some("TF"), // French Southern Territories 636 => Some("LR"), // Liberia 637 => Some("LR"), // Liberia 638 => Some("SS"), // South Sudan 642 => Some("LY"), // Libya 644 => Some("LS"), // Lesotho 645 => Some("MU"), // Mauritius 647 => Some("MG"), // Madagascar 649 => Some("ML"), // Mali 650 => Some("MZ"), // Mozambique 654 => Some("MR"), // Mauritania 655 => Some("MW"), // Malawi 656 => Some("NE"), // Niger 657 => Some("NG"), // Nigeria 659 => Some("NA"), // Namibia 660 => Some("TF"), // French Southern Territories 661 => Some("RW"), // Rwanda 662 => Some("SD"), // Sudan 663 => Some("SN"), // Senegal 664 => Some("SC"), // Seychelles 665 => Some("SH"), // Saint Helena, Ascension and Tristan da Cunha 666 => Some("SO"), // Somalia 667 => Some("SL"), // Sierra Leone 668 => Some("ST"), // Sao Tome and Principe 669 => Some("SZ"), // Eswatini 670 => Some("TD"), // Chad 671 => Some("TG"), // Togo 672 => Some("TN"), // Tunisia 674 => Some("TZ"), // Tanzania, United Republic of 675 => Some("UG"), // Uganda 676 => Some("CG"), // Congo 677 => Some("TZ"), // Tanzania, United Republic of 678 => Some("ZM"), // Zambia 679 => Some("ZW"), // Zimbabwe 701 => Some("AR"), // Argentina 710 => Some("BR"), // Brazil 720 => Some("BO"), // Bolivia 725 => Some("CL"), // Chile 730 => Some("CO"), // Colombia 735 => Some("EC"), // Ecuador 740 => Some("FK"), // Falkland Islands [Malvinas] 745 => Some("GF"), // French Guiana 750 => Some("GY"), // Guyana 755 => Some("PY"), // Paraguay 760 => Some("PE"), // Peru 765 => Some("SR"), // Suriname 770 => Some("UY"), // Uruguay 775 => Some("VE"), // Venezuela _ => None, } } }