text
stringlengths
8
4.13M
use itertools::Itertools; fn main() { let input = include_str!("../../../input/12.txt") .split('\n') .collect_vec(); let mut ship = Ship::new(&input); let part_one_result = ship.journey(); println!("Manhattan distance: {}", part_one_result) } enum Direction { North, East, South, West, } impl Direction { fn change(&self, left: bool, units: i32) -> Direction { match self { Direction::North => match units { 90 if left => return Direction::West, 90 if !left => return Direction::East, 180 => return Direction::South, 270 if left => return Direction::East, 270 if !left => return Direction::West, _ => {} }, Direction::East => match units { 90 if left => return Direction::North, 90 if !left => return Direction::South, 180 => return Direction::West, 270 if left => return Direction::South, 270 if !left => return Direction::North, _ => {} }, Direction::South => match units { 90 if left => return Direction::East, 90 if !left => return Direction::West, 180 => return Direction::North, 270 if left => return Direction::West, 270 if !left => return Direction::East, _ => {} }, Direction::West => match units { 90 if left => return Direction::South, 90 if !left => return Direction::North, 180 => return Direction::East, 270 if left => return Direction::North, 270 if !left => return Direction::South, _ => {} }, } Direction::East } } struct Ship<'a> { route: &'a [&'a str], direction: Direction, units_north: i32, units_east: i32, units_south: i32, units_west: i32, } impl<'a> Ship<'a> { fn new(input: &'a [&str]) -> Self { Self { route: input, direction: Direction::East, units_north: 0, units_east: 0, units_south: 0, units_west: 0, } } fn journey(&mut self) -> usize { for &instruction in self.route { let instr = instruction.chars().next().unwrap(); let units = &instruction[1..].parse::<i32>().unwrap(); match instr { 'N' => self.units_north += units, 'S' => self.units_south += units, 'E' => self.units_east += units, 'W' => self.units_west += units, 'L' => self.direction = self.direction.change(true, *units), 'R' => self.direction = self.direction.change(false, *units), 'F' => match self.direction { Direction::North => self.units_north += units, Direction::East => self.units_east += units, Direction::South => self.units_south += units, Direction::West => self.units_west += units, }, _ => {} } } self.manhattan_distance() } /// Calculates the manhattan distance between the two provided grid cells pub fn manhattan_distance(&self) -> usize { let x_diff = if self.units_west < self.units_east { self.units_east - self.units_west } else { self.units_west - self.units_east }; let y_diff = if self.units_north < self.units_south { self.units_south - self.units_north } else { self.units_north - self.units_south }; (x_diff + y_diff) as usize } }
use core::sync::atomic; use core::{ptr}; use super::super::linux_def::IoVec; use super::super::common::*; use super::register::execute; use super::register::Probe; use super::squeue::SubmissionQueue; use super::sys; use super::util::{cast_ptr, unsync_load, Fd}; use super::porting::*; #[cfg(feature = "unstable")] use super::register::Restriction; /// Submitter pub struct Submitter<'a> { pub fd: &'a Fd, pub flags: u32, pub sq_head: *const atomic::AtomicU32, pub sq_tail: *const atomic::AtomicU32, pub sq_flags: *const atomic::AtomicU32, } impl<'a> Submitter<'a> { #[inline] pub(crate) const fn new(fd: &'a Fd, flags: u32, sq: &SubmissionQueue) -> Submitter<'a> { Submitter { fd, flags, sq_head: sq.head, sq_tail: sq.tail, sq_flags: sq.flags, } } pub fn sq_len(&self) -> usize { unsafe { let head = (*self.sq_head).load(atomic::Ordering::Acquire); let tail = unsync_load(self.sq_tail); tail.wrapping_sub(head) as usize } } pub fn sq_need_wakeup(&self) -> bool { unsafe { (*self.sq_flags).load(atomic::Ordering::Acquire) & sys::IORING_SQ_NEED_WAKEUP != 0 } } #[cfg(feature = "unstable")] pub fn squeue_wait(&self) -> Result<usize> { let result = unsafe { sys::io_uring_enter( self.fd.as_raw_fd(), 0, 0, sys::IORING_ENTER_SQ_WAIT, ptr::null(), ) }; if result >= 0 { Ok(result as _) } else { Err(io::Error::last_os_error()) } } /// Register buffers. pub fn register_buffers(&self, bufs: &[IoVec]) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_BUFFERS, bufs.as_ptr() as *const _, bufs.len() as _, ) .map(drop) } /// Register files for I/O. pub fn register_files(&self, fds: &[RawFd]) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_FILES, fds.as_ptr() as *const _, fds.len() as _, ) .map(drop) } /// It’s possible to use `eventfd(2)` to get notified of completion events on an io_uring instance. pub fn register_eventfd(&self, eventfd: RawFd) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_EVENTFD, cast_ptr::<RawFd>(&eventfd) as *const _, 1, ) .map(drop) } /// This operation replaces existing files in the registered file set with new ones, /// either turning a sparse entry (one where fd is equal to -1) into a real one, removing an existing entry (new one is set to -1), /// or replacing an existing entry with a new existing entry. pub fn register_files_update(&self, offset: u32, fds: &[RawFd]) -> Result<usize> { let fu = sys::io_uring_files_update { offset, resv: 0, fds: fds.as_ptr() as _, }; let fu = cast_ptr::<sys::io_uring_files_update>(&fu); let ret = execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_FILES_UPDATE, fu as *const _, fds.len() as _, )?; Ok(ret as _) } /// This works just like [Submitter::register_eventfd], /// except notifications are only posted for events that complete in an async manner. pub fn register_eventfd_async(&self, eventfd: RawFd) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_EVENTFD_ASYNC, cast_ptr::<RawFd>(&eventfd) as *const _, 1, ) .map(drop) } /// This operation returns a structure `Probe`, /// which contains information about the opcodes supported by io_uring on the running kernel. pub fn register_probe(&self, probe: &mut Probe) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_PROBE, probe.as_mut_ptr() as *const _, Probe::COUNT as _, ) .map(drop) } /// This operation registers credentials of the running application with io_uring, /// and returns an id associated with these credentials. pub fn register_personality(&self) -> Result<i32> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_PERSONALITY, ptr::null(), 0, ) } /// Unregister buffers. pub fn unregister_buffers(&self) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_UNREGISTER_BUFFERS, ptr::null(), 0, ) .map(drop) } /// Unregister files. pub fn unregister_files(&self) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_UNREGISTER_FILES, ptr::null(), 0, ) .map(drop) } /// Unregister an eventfd file descriptor to stop notifications. pub fn unregister_eventfd(&self) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_UNREGISTER_EVENTFD, ptr::null(), 0, ) .map(drop) } /// This operation unregisters a previously registered personality with io_uring. pub fn unregister_personality(&self, id: i32) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_UNREGISTER_PERSONALITY, ptr::null(), id as _, ) .map(drop) } #[cfg(feature = "unstable")] pub fn register_restrictions(&self, res: &mut [Restriction]) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_RESTRICTIONS, res.as_mut_ptr().cast(), res.len() as _, ) .map(drop) } #[cfg(feature = "unstable")] pub fn register_enable_rings(&self) -> Result<()> { execute( self.fd.as_raw_fd(), sys::IORING_REGISTER_ENABLE_RINGS, ptr::null(), 0, ) .map(drop) } }
use types::MalVal; use types::MalVal::{Nil,Bool,Int,Str,Sym,List,Vector,Hash,Func,MalFunc,Atom}; fn escape_str(s: &str) -> String { s.chars().map(|c| { match c { '"' => "\\\"".to_string(), '\n' => "\\n".to_string(), '\\' => "\\\\".to_string(), _ => c.to_string(), } }).collect::<Vec<String>>().join("") } impl MalVal { pub fn pr_str(&self, print_readably: bool) -> String { match self { Nil => String::from("nil"), Bool(true) => String::from("true"), Bool(false) => String::from("false"), Int(i) => format!("{}", i), //Float(f) => format!("{}", f), Str(s) => { if s.starts_with("\u{29e}") { format!(":{}", &s[2..]) } else if print_readably { format!("\"{}\"", escape_str(s)) } else { s.clone() } } Sym(s) => s.clone(), List(l,_) => pr_seq(&**l, print_readably, "(", ")", " "), Vector(l,_) => pr_seq(&**l, print_readably, "[", "]", " "), Hash(hm,_) => { let l: Vec<MalVal> = hm .iter() .flat_map(|(k, v)| { vec![Str(k.to_string()), v.clone()] }) .collect(); pr_seq(&l, print_readably, "{", "}", " ") }, Func(f,_) => format!("#<fn {:?}>", f), MalFunc{ast: a, params: p, ..} => { format!("(fn* {} {})", p.pr_str(true), a.pr_str(true)) }, Atom(a) => format!("(atom {})", a.borrow().pr_str(true)), } } } pub fn pr_seq(seq: &Vec<MalVal>, print_readably: bool, start: &str, end: &str, join: &str) -> String { let strs: Vec<String> = seq .iter() .map(|x| x.pr_str(print_readably)) .collect(); format!("{}{}{}", start, strs.join(join), end) } // vim: ts=2:sw=2:expandtab
//! this module manages reading and translating //! the arguments passed on launch of the application. pub mod clap_args; mod app_launch_args; mod install_launch_args; pub use { app_launch_args::*, install_launch_args::*, }; use { crate::{ app::{App, AppContext}, conf::Conf, display, errors::{ProgramError, TreeBuildError}, launchable::Launchable, shell_install::ShellInstall, tree::TreeOptions, verb::VerbStore, }, clap::{self, ArgMatches}, crossterm::{ self, cursor, event::{DisableMouseCapture, EnableMouseCapture}, terminal::{EnterAlternateScreen, LeaveAlternateScreen}, QueueableCommand, }, std::{ env, io::{self, Write}, path::{Path, PathBuf}, }, }; #[cfg(not(windows))] fn canonicalize_root(root: &Path) -> io::Result<PathBuf> { root.canonicalize() } #[cfg(windows)] fn canonicalize_root(root: &Path) -> io::Result<PathBuf> { Ok(if root.is_relative() { env::current_dir()?.join(root) } else { root.to_path_buf() }) } fn get_root_path(cli_args: &ArgMatches<'_>) -> Result<PathBuf, ProgramError> { let mut root = cli_args .value_of("ROOT") .map_or(env::current_dir()?, PathBuf::from); if !root.exists() { return Err(TreeBuildError::FileNotFound { path: format!("{:?}", &root), }.into()); } if !root.is_dir() { // we try to open the parent directory if the passed file isn't one if let Some(parent) = root.parent() { info!("Passed path isn't a directory => opening parent instead"); root = parent.to_path_buf(); } else { // let's give up return Err(TreeBuildError::NotADirectory { path: format!("{:?}", &root), }.into()); } } Ok(canonicalize_root(&root)?) } /// run the application, and maybe return a launchable /// which must be run after broot pub fn run() -> Result<Option<Launchable>, ProgramError> { let clap_app = clap_args::clap_app(); // parse the launch arguments we got from cli let cli_matches = clap_app.get_matches(); // read the install related arguments let install_args = InstallLaunchArgs::from(&cli_matches)?; // execute installation things required by launch args let mut must_quit = false; if let Some(state) = install_args.set_install_state { state.write_file()?; must_quit = true; } if let Some(shell) = &install_args.print_shell_function { ShellInstall::print(shell)?; must_quit = true; } if must_quit { return Ok(None); } // read the list of specific config files let specific_conf: Option<Vec<PathBuf>> = cli_matches .value_of("conf") .map(|s| s.split(';').map(PathBuf::from).collect()); // if we don't run on a specific config file, we check the // configuration if specific_conf.is_none() && install_args.install != Some(false) { let mut shell_install = ShellInstall::new(install_args.install == Some(true)); shell_install.check()?; if shell_install.should_quit { return Ok(None); } } // read the configuration file(s): either the standard one // or the ones required by the launch args let mut config = match &specific_conf { Some(conf_paths) => { let mut conf = Conf::default(); for path in conf_paths { conf.read_file(path.to_path_buf())?; } conf } _ => time!(Conf::from_default_location())?, }; debug!("config: {:#?}", &config); // tree options are built from the default_flags // found in the config file(s) (if any) then overriden // by the cli args let mut tree_options = TreeOptions::default(); tree_options.apply_config(&config)?; tree_options.apply_launch_args(&cli_matches); // verb store is completed from the config file(s) let verb_store = VerbStore::new(&mut config)?; // reading the other arguments let file_export_path = cli_matches.value_of("file-export-path").map(str::to_string); let cmd_export_path = cli_matches.value_of("cmd-export-path").map(str::to_string); let commands = cli_matches.value_of("commands").map(str::to_string); let height = cli_matches.value_of("height").and_then(|s| s.parse().ok()); let color = match cli_matches.value_of("color") { Some("yes") => Some(true), Some("no") => Some(false), _ => None, }; let root = get_root_path(&cli_matches)?; #[cfg(unix)] if let Some(server_name) = cli_matches.value_of("send") { use crate::{ command::Sequence, net::{Client, Message}, }; let client = Client::new(server_name); if let Some(seq) = &commands { let message = Message::Sequence(Sequence::new_local(seq.to_string())); client.send(&message)?; } else if !cli_matches.is_present("get-root") { let message = Message::Command(format!(":focus {}", root.to_string_lossy())); client.send(&message)?; }; if cli_matches.is_present("get-root") { client.send(&Message::GetRoot)?; } return Ok(None); } let mut launch_args = AppLaunchArgs { root, file_export_path, cmd_export_path, tree_options, commands, height, color, listen: cli_matches.value_of("listen").map(str::to_string), }; if color == Some(false) { launch_args.tree_options.show_selection_mark = true; } let context = AppContext::from(launch_args, verb_store, &config)?; let mut w = display::writer(); let app = App::new(&context)?; w.queue(EnterAlternateScreen)?; w.queue(cursor::Hide)?; let capture_mouse = config.disable_mouse_capture != Some(true); if capture_mouse { w.queue(EnableMouseCapture)?; } let r = app.run(&mut w, &context, &config); if capture_mouse { w.queue(DisableMouseCapture)?; } w.queue(cursor::Show)?; w.queue(LeaveAlternateScreen)?; w.flush()?; r } /// wait for user input, return `true` if they didn't answer 'n' pub fn ask_authorization() -> Result<bool, ProgramError> { let mut answer = String::new(); io::stdin().read_line(&mut answer)?; let answer = answer.trim(); Ok(!matches!(answer, "n" | "N")) }
use input_i_scanner::InputIScanner; fn main() { let stdin = std::io::stdin(); let mut _i_i = InputIScanner::from(stdin.lock()); macro_rules! scan { (($($t: ty),+)) => { ($(scan!($t)),+) }; ($t: ty) => { _i_i.scan::<$t>() as $t }; (($($t: ty),+); $n: expr) => { std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>() }; ($t: ty; $n: expr) => { std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>() }; } let n = scan!(usize); let ss = scan!(u64; n); let mut ans = 0; for s in ss { let mut ok = false; for a in 1..=s { for b in 1..=s { if 4 * a * b + 3 * a + 3 * b == s { ok = true; } } } if !ok { ans += 1; } } println!("{}", ans); }
//! An API wrapper for startuppong.com //! //! The wrapper is implemented as a few module level functions for accessing the endpoints. All of //! the JSON responses are represented with structs. The rustc_serialize crate is heavily relied on //! to handle decoding of JSON responses. //! //! Sign up for an account at [startuppong.com](http://www.startuppong.com). //! //! # Examples //! ```no_run //! use startuppong::Account; //! use startuppong::get_players; //! //! // Get the current leaderboard //! let account = Account::new("account_id".to_owned(), "account_key".to_owned()); //! //! // Make request to startuppong.com //! let players_response = get_players(&account).unwrap(); //! //! // Consume the response and get the list of players //! let players = players_response.players(); //! //! // Print out the leaderboard //! for player in &players { //! println!("{} ({}) - {}", player.rank, player.rating, player.name); //! } //! ``` extern crate rustc_serialize; extern crate hyper; extern crate mime; use std::env; use std::io::Read; use hyper::header::ContentType; use rustc_serialize::json; /// Error types, From impls, etc pub mod error; use error::ApiError; /// An account is necessary to make requests against the API. /// /// This struct holds your account ID and access key. It is a required argument to all of the API /// methods. #[derive(Debug, RustcEncodable, Clone)] pub struct Account { api_account_id: String, api_access_key: String } impl Account { /// Create a new Account pub fn new(id: String, key: String) -> Account { Account { api_account_id: id, api_access_key: key } } /// Try and create an account from environment variables /// /// The environment variables needed are **STARTUPPONG_ACCOUNT_ID** and /// **STARTUPPONG_ACCESS_KEY**. pub fn from_env() -> Result<Account, std::env::VarError> { Ok(Account::new(try!(env::var("STARTUPPONG_ACCOUNT_ID")), try!(env::var("STARTUPPONG_ACCESS_KEY")))) } /// Return a ref to the api_account_id pub fn id(&self) -> &str { &self.api_account_id[..] } /// Return a ref to the api_access_key pub fn key(&self) -> &str { &self.api_access_key[..] } } /// A person on the ladder #[derive(Debug, RustcDecodable, Clone)] pub struct Player { pub id: u32, pub rating: f32, pub rank: u32, pub name: String } /// The stats before and after a set #[derive(Debug, RustcDecodable, Clone)] pub struct Match { pub loser_rating_after: f32, pub winner_rating_after: f32, pub played_time: u64, pub loser_rank_after: u32, pub winner_name: String, pub winner_rank_before: u32, pub winner_rating_before: f32, pub loser_name: String, pub winner_id: u32, pub loser_rank_before: u32, pub loser_rating_before: f32, pub id: u64, pub winner_rank_after: u32, pub loser_id: u32 } /// Wrapper for APIs returning a player list. /// /// Use [`players()`](struct.GetPlayersResponse.html#method.players) to consume the response and /// get the underlying `Vec<Player>` #[derive(Debug, RustcDecodable)] pub struct GetPlayersResponse { players: Vec<Player> } impl GetPlayersResponse { /// Consume the response and get underlying Vec pub fn players(self) -> Vec<Player> { self.players } } /// Wrapper for APIs returning a match list. /// /// Use [`matches()`](struct.GetMatchesResponse.html#method.matches) to consume the response and /// get the underlying `Vec<Match>`. #[derive(Debug, RustcDecodable)] pub struct GetMatchesResponse { matches: Vec<Match> } impl GetMatchesResponse { /// Consume the response and get underlying Vec pub fn matches(self) -> Vec<Match> { self.matches } } /// Get ids for players /// /// Since the API doesn't provide any way to do the matching for us, we query the get_players /// endpoint and do a linear search for each name in names. The returned ids can be used as /// arguments to the add_match and other APIs requiring player IDs pub fn get_players_ids(account: &Account, names: Vec<&str>) -> Result<Vec<u32>, ApiError> { let players = try!(get_players(account)).players(); let mut ids = Vec::with_capacity(names.len()); for name in &names { let len_before = ids.len(); for player in &players { if player.name.contains(name) { ids.push(player.id); break; } } // If the length hasn't changed, no player names matched if ids.len() == len_before { return Err(ApiError::PlayerNotFound(name.to_string())); } } Ok(ids) } /// Return all players associated with the given account /// /// Wraps `/api/v1/get_players` pub fn get_players(account: &Account) -> Result<GetPlayersResponse, ApiError> { let url = format!("http://www.startuppong.com/api/v1/get_players\ ?api_account_id={}&api_access_key={}", account.id(), account.key()); get::<GetPlayersResponse>(&url) } /// Return most recent matches on the given account /// /// Wraps `/api/v1/get_recent_matches_for_company` pub fn get_recent_matches_for_company(account: &Account) -> Result<GetMatchesResponse, ApiError> { let url = format!("http://www.startuppong.com/api/v1/get_recent_matches_for_company\ ?api_account_id={}&api_access_key={}", account.id(), account.key()); get::<GetMatchesResponse>(&url) } /// Helper for retrieving a resource /// /// `get` assumes that the http response is JSON formatted, and the parameterized type T /// implements rustc_serialize::Decodable. fn get<T>(url: &str) -> Result<T, ApiError> where T: rustc_serialize::Decodable { let client = hyper::Client::new(); let mut res = try!(client.get(&url[..]).send()); let mut body = String::new(); try!(res.read_to_string(&mut body)); Ok(try!(json::decode::<T>(&body))) } /// Add a match /// /// Using the given `winner_id` and `loser_id`, create a new match. See /// [add_match_with_names](fn.add_match_with_names.html) for a potentially easier to consume API. /// This method wraps the `/api/v1/add_match` endpoint. pub fn add_match(account: &Account, winner_id: u32, loser_id: u32) -> Result<(), ApiError> { let client = hyper::Client::new(); let data = format!("api_account_id={}&api_access_key={}&winner_id={}&loser_id={}", account.id(), account.key(), winner_id, loser_id); let url = "http://www.startuppong.com/api/v1/add_match"; try!(client.post(&url[..]) .header(ContentType("application/x-www-form-urlencoded".parse().unwrap())) .body(&data).send()); Ok(()) } /// Add a match using the given names. /// /// It is possible for name lookup to fail. If that happens, the Result will unwrap to a /// `startuppong::ApiError::PlayerNotFound(String)` where the String is the first name not /// resolved. Names are matched in a case-sensitive fashion. The first result with a valid sub /// string match is accepted. pub fn add_match_with_names(account: &Account, winner: &str, loser: &str) -> Result<(), ApiError> { let names = vec![winner, loser]; let ids = try!(get_players_ids(account, names)); add_match(account, ids[0], ids[1]) } #[cfg(feature = "api_test")] #[cfg(test)] mod api_tests { use super::Account; use super::get_players as get_players_; use super::get_players_ids as get_players_ids_; #[test] fn get_players() { let account = Account::from_env().unwrap(); let player_res = get_players_(&account).unwrap(); let players = player_res.players(); // The account has been preconfigured with at least two players assert!(players.len() >= 2); } #[test] fn get_players_ids() { let account = Account::from_env().unwrap(); let ids = get_players_ids_(&account, vec!["arst", "oien"]).unwrap(); println!("{:?}", ids); } } #[cfg(test)] mod tests { use rustc_serialize::json; use super::GetPlayersResponse; use super::GetMatchesResponse; #[test] fn parse_get_players_response() { let raw = r#"{ "players": [ { "name": "Eshaan Bhalla", "rank": 1, "rating": 561.844467876031, "id": 89 }, { "name": "Collin Green", "rank": 2, "rating": 635.422989640755, "id": 55 }, { "name": "Joe Wilm", "rank": 3, "rating": 484.820167747424, "id": 60 } ] }"#; let res = json::decode::<GetPlayersResponse>(raw).unwrap(); let players = res.players(); assert_eq!(players[0].name, "Eshaan Bhalla"); assert_eq!(players[1].name, "Collin Green"); assert_eq!(players[2].name, "Joe Wilm"); assert_eq!(players[0].rank, 1); assert_eq!(players[0].id, 89); } #[test] fn parse_get_matches_response() { let raw = r#"{ "matches": [ { "loser_rating_after": 513.938174130505, "winner_rating_after": 635.422989640755, "played_time": 1432949959, "loser_rank_after": 5, "winner_name": "Collin Green", "winner_rank_before": 2, "winner_rating_before": 632.015809629857, "loser_name": "Michael Carter", "winner_id": 55, "loser_rank_before": 5, "loser_rating_before": 517.345354141403, "id": 1093, "winner_rank_after": 2, "loser_id": 58 }, { "loser_rating_after": 484.820167747424, "winner_rating_after": 632.015809629857, "played_time": 1432945408, "loser_rank_after": 3, "winner_name": "Collin Green", "winner_rank_before": 3, "winner_rating_before": 628.94100790458, "loser_name": "Joe Wilm", "winner_id": 55, "loser_rank_before": 2, "loser_rating_before": 487.894969472701, "id": 1092, "winner_rank_after": 2, "loser_id": 60 }, { "loser_rating_after": 628.94100790458, "winner_rating_after": 487.894969472701, "played_time": 1432945400, "loser_rank_after": 3, "winner_name": "Joe Wilm", "winner_rank_before": 4, "winner_rating_before": 480.798589900423, "loser_name": "Collin Green", "winner_id": 60, "loser_rank_before": 2, "loser_rating_before": 636.037387476858, "id": 1091, "winner_rank_after": 2, "loser_id": 55 } ] }"#; let res = json::decode::<GetMatchesResponse>(raw).unwrap(); let matches = res.matches(); assert_eq!(matches.len(), 3); assert_eq!(matches[0].winner_name, "Collin Green"); assert_eq!(matches[0].played_time, 1432949959); assert_eq!(matches[0].loser_rank_after, 5); assert_eq!(matches[0].loser_rank_before, 5); assert_eq!(matches[0].winner_id, 55); assert_eq!(matches[0].loser_id, 58); assert_eq!(matches[0].id, 1093); } }
use std::collections::HashMap; use std::collections::HashSet; use instruction::*; use error::*; use std::fmt; const ROM_START_ADDR: usize = 0x200; #[derive(Copy, Clone, Hash, Eq, PartialEq, Debug, PartialOrd, Ord)] struct Pc(usize); impl Pc { fn advance(self, n: usize) -> Pc { Pc(self.0 + n * 2) } } impl From<Addr> for Pc { fn from(addr: Addr) -> Pc { Pc(addr.0 as usize - ROM_START_ADDR) } } struct Rom<'a> { bytes: &'a [u8], } impl<'a> Rom<'a> { fn new(bytes: &[u8]) -> Rom { Rom { bytes } } fn decode_instruction(&self, pc: Pc) -> Result<Instruction> { use byteorder::{BigEndian, ByteOrder}; if pc.0 >= self.bytes.len() { bail!("Unexpected EOF"); } let Pc(actual_pc) = pc; let instruction_word = InstructionWord(BigEndian::read_u16(&self.bytes[actual_pc..])); Instruction::decode(instruction_word) } } #[derive(Copy, Clone, Debug)] struct BBRange { start: Pc, end: Pc, } impl BBRange { fn new(start: Pc, end: Pc) -> BBRange { assert!(start <= end); BBRange { start, end } } fn intersects(&self, other: &BBRange) -> bool { self.start <= other.end && other.start <= self.end } } struct SubroutineBuilder<'a> { rom: Rom<'a>, addr: Pc, has_ret: bool, bbs: BasicBlocksBuilder, bb_ranges: HashMap<BasicBlockId, BBRange>, } impl<'a> SubroutineBuilder<'a> { fn new(rom: Rom<'a>, addr: Pc) -> SubroutineBuilder<'a> { SubroutineBuilder { rom, addr, has_ret: false, bbs: BasicBlocksBuilder::new(), bb_ranges: HashMap::new(), } } fn into_routine(self) -> Routine { println!("result = {:#?}", self.bbs); Routine { entry: BasicBlockId::entry(), bbs: self.bbs.into_map(), } } fn seal_bb( &mut self, id: BasicBlockId, range: BBRange, insts: Vec<Instruction>, terminator: Terminator, ) { println!("sealing {:?}, bb={:?}", range, id); let intersecting_ranges: Vec<_> = self.bb_ranges .values() .filter(|r| r.intersects(&range)) .cloned() .collect(); if !intersecting_ranges.is_empty() { panic!("there are intersecting ranges: {:#?}", intersecting_ranges); } let bb = BasicBlock::new(insts, terminator); self.bbs.insert(id, bb); self.bb_ranges.insert(id, range); } fn build_bb( &mut self, pc: &mut Pc, instructions: &mut Vec<Instruction>, leaders: &HashMap<Pc, BasicBlockId>, ) -> Result<Terminator> { let terminator = loop { let instruction = self.rom.decode_instruction(*pc)?; println!("pc={:?}, {:?}", pc, instruction); // Check, if current instruction is a terminator. match instruction { Instruction::Ret => { break Terminator::Ret; } Instruction::Jump(addr) => { let target_pc = Pc::from(addr); let target_id = leaders[&target_pc]; break Terminator::Jump { target: target_id }; } Instruction::Skip(predicate) => { let next_pc = pc.advance(1); let skip_pc = pc.advance(2); let next_id = leaders[&next_pc]; let skip_id = leaders[&skip_pc]; break Terminator::Skip { predicate, next: next_id, skip: skip_id, }; } _ => {} } // Otherwise, put current instructions into result vector. instructions.push(instruction); // If next instruction is a leader, then this instruction is last in current // basic block. if let Some(next_block_id) = leaders.get(&pc.advance(1)) { break Terminator::Jump { target: *next_block_id, }; } *pc = pc.advance(1); }; Ok(terminator) } fn identify_leaders( &mut self, seen_calls: &mut HashSet<Addr>, ) -> Result<HashMap<Pc, BasicBlockId>> { let mut leaders: HashMap<Pc, BasicBlockId> = HashMap::new(); let mut stack: Vec<Pc> = Vec::new(); stack.push(self.addr); leaders.insert(self.addr, BasicBlockId::entry()); while let Some(mut pc) = stack.pop() { loop { let instruction = self.rom.decode_instruction(pc)?; match instruction { Instruction::Ret => { self.has_ret = true; break; } Instruction::JumpPlusV0(_) => { bail!("Indirect jumps not supported!"); } Instruction::Jump(addr) => { let target_pc = Pc::from(addr); leaders.entry(target_pc).or_insert_with(|| { stack.push(target_pc); self.bbs.gen_id() }); break; } Instruction::Skip(_) => { let next_pc = pc.advance(1); let skip_pc = pc.advance(2); leaders.entry(next_pc).or_insert_with(|| { stack.push(next_pc); self.bbs.gen_id() }); leaders.entry(skip_pc).or_insert_with(|| { stack.push(skip_pc); self.bbs.gen_id() }); break; } Instruction::Call(addr) => { seen_calls.insert(addr); } _ => {} } pc = pc.advance(1); } } Ok(leaders) } fn build_cfg(&mut self, seen_calls: &mut HashSet<Addr>) -> Result<()> { let leaders = self.identify_leaders(seen_calls)?; println!("leaders = {:?}", leaders); for leader_pc in leaders.keys().cloned() { let mut pc = leader_pc; let mut instructions = Vec::new(); let terminator = self.build_bb(&mut pc, &mut instructions, &leaders)?; let bb_id = leaders[&leader_pc]; self.seal_bb(bb_id, BBRange::new(leader_pc, pc), instructions, terminator); } Ok(()) } } pub fn build_cfg(rom: &[u8]) -> Result<CFG> { let mut seen_calls = HashSet::new(); let mut subs = HashMap::new(); let mut subroutine_stack: Vec<Addr> = Vec::new(); let start_subroutine_id = RoutineId::start().0; subroutine_stack.push(start_subroutine_id); while let Some(subroutine_addr) = subroutine_stack.pop() { let mut sub_builder = SubroutineBuilder::new(Rom::new(rom), Pc::from(subroutine_addr)); let mut seen_calls_from_sr = HashSet::new(); sub_builder.build_cfg(&mut seen_calls_from_sr)?; if RoutineId(subroutine_addr) == RoutineId::start() && sub_builder.has_ret { bail!("ret in top-level code found") } subs.insert(subroutine_addr.into(), sub_builder); for seen in seen_calls_from_sr.difference(&seen_calls).cloned() { println!("queueing {:#?}", seen); subroutine_stack.push(seen); } seen_calls = seen_calls .intersection(&seen_calls_from_sr) .cloned() .collect(); } let subroutines = subs.into_iter() .map(|(k, v)| (k, v.into_routine())) .collect(); Ok(CFG { start: RoutineId(start_subroutine_id), subroutines, }) } #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Terminator { Ret, Jump { target: BasicBlockId }, Skip { predicate: Predicate, next: BasicBlockId, skip: BasicBlockId, }, } impl Terminator { pub fn successors(&self) -> Vec<BasicBlockId> { match *self { Terminator::Ret => vec![], Terminator::Jump { target } => vec![target], Terminator::Skip { next, skip, .. } => vec![next, skip], } } } #[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)] pub struct BasicBlockId(usize); impl BasicBlockId { fn entry() -> BasicBlockId { BasicBlockId(0) } } impl fmt::Display for BasicBlockId { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "bb{}", self.0) } } #[derive(Hash, PartialEq, Eq, Debug, Clone, Copy)] pub struct RoutineId(pub Addr); impl RoutineId { pub fn start() -> RoutineId { RoutineId(Addr(ROM_START_ADDR as u16)) } } impl From<Addr> for RoutineId { fn from(addr: Addr) -> RoutineId { RoutineId(addr) } } #[derive(Debug)] pub struct BasicBlock { insts: Vec<Instruction>, terminator: Terminator, } impl BasicBlock { fn new(insts: Vec<Instruction>, terminator: Terminator) -> BasicBlock { assert!(!insts.iter().any(|x| x.is_terminating())); BasicBlock { insts, terminator } } pub fn instructions(&self) -> &[Instruction] { &self.insts } pub fn terminator(&self) -> Terminator { self.terminator } } impl Instruction { pub fn is_terminating(&self) -> bool { use self::Instruction::*; match *self { Ret | Jump(..) | Skip(..) | JumpPlusV0(..) => true, _ => false, } } } #[derive(Debug)] struct BasicBlocksBuilder { id_counter: usize, bbs: HashMap<BasicBlockId, BasicBlock>, } impl BasicBlocksBuilder { fn new() -> BasicBlocksBuilder { BasicBlocksBuilder { id_counter: 1, // 0 reserved for BasicBlockId::entry() bbs: HashMap::new(), } } fn gen_id(&mut self) -> BasicBlockId { let id = self.id_counter; self.id_counter += 1; BasicBlockId(id) } fn insert(&mut self, id: BasicBlockId, basic_block: BasicBlock) { let existing_value = self.bbs.insert(id, basic_block); assert!(existing_value.is_none()); } fn into_map(self) -> HashMap<BasicBlockId, BasicBlock> { if self.bbs.is_empty() { return self.bbs; } self.bbs } } impl From<HashMap<BasicBlockId, BasicBlock>> for BasicBlocksBuilder { fn from(map: HashMap<BasicBlockId, BasicBlock>) -> BasicBlocksBuilder { let max_id = map.keys().map(|b| b.0).max().unwrap_or(0); BasicBlocksBuilder { id_counter: max_id + 1, bbs: map, } } } #[derive(Debug)] pub struct Routine { pub entry: BasicBlockId, pub bbs: HashMap<BasicBlockId, BasicBlock>, } #[derive(Debug)] pub struct CFG { start: RoutineId, subroutines: HashMap<RoutineId, Routine>, } impl CFG { pub fn start(&self) -> RoutineId { self.start } pub fn subroutines(&self) -> &HashMap<RoutineId, Routine> { &self.subroutines } fn print_bb( &self, routine: &Routine, bb_id: BasicBlockId, seen_bbs: &mut HashSet<BasicBlockId>, ) { println!("{}:", bb_id); let bb = &routine.bbs[&bb_id]; for inst in &bb.insts { println!(" {:?}", inst); } println!(" terminator: {:?}", bb.terminator); seen_bbs.insert(bb_id); for successor_bb in bb.terminator.successors() { if !seen_bbs.contains(&successor_bb) { self.print_bb(routine, successor_bb, seen_bbs); } } } fn print_routine(&self, routine: &Routine) { let mut seen_bbs = HashSet::new(); self.print_bb(routine, routine.entry, &mut seen_bbs); } pub fn print(&self) { for subroutine in self.subroutines.values() { self.print_routine(subroutine); } } } #[test] fn test_bbrange_intersects() { fn intersects(a: (usize, usize), b: (usize, usize)) -> bool { BBRange::new(Pc(a.0), Pc(a.1)).intersects(&BBRange::new(Pc(b.0), Pc(b.1))) } assert!(intersects((0, 3), (1, 4))); // intersection 1-3 assert!(intersects((0, 3), (0, 1))); // intersection 0-1 assert!(intersects((0, 0), (0, 0))); // intersection 0-0 assert!(intersects((5, 10), (6, 7))); // intersection 6-7 assert!(!intersects((0, 5), (6, 10))); // intersection 6-7 } #[test] fn test_jump_self() { #[cfg_attr(rustfmt, rustfmt_skip)] let rom = vec![ 0x00, 0xE0, // CLS 0x12, 0x02, // 0x202: JMP 0x202 ]; let cfg = build_cfg(&rom).unwrap(); let start = cfg.start; let start_routine = cfg.subroutines.get(&start).unwrap(); println!("{:#?}", start_routine); let entry = start_routine.entry; let entry_bb = &start_routine.bbs[&entry]; assert_eq!(entry_bb.insts, vec![Instruction::ClearScreen]); } #[test] fn test_jump_self2() { #[cfg_attr(rustfmt, rustfmt_skip)] let rom = vec![ 0x12, 0x02, // JMP 0x202 0x12, 0x02, // 0x202: JMP 0x202 ]; let cfg = build_cfg(&rom).unwrap(); let start = cfg.start; let start_routine = cfg.subroutines.get(&start).unwrap(); println!("{:#?}", start_routine); let entry = start_routine.entry; let entry_bb = &start_routine.bbs[&entry]; assert_eq!(entry_bb.insts, vec![]); assert_eq!( entry_bb.terminator, Terminator::Jump { target: BasicBlockId(1), } ); } #[test] fn test_cfg() { #[cfg_attr(rustfmt, rustfmt_skip)] let rom = vec![ 0x30, 0x02, // 0x200: SE V0, 0 0x12, 0x08, // JMP 0x208 0x12, 0x06, // JMP 0x206 0x00, 0x01, // 0x206: SYS 0x001 0x00, 0x02, // 0x208: SYS 0x002, 0x12, 0x00, // JMP 0x200 ]; let cfg = build_cfg(&rom).unwrap(); let start = cfg.start; let start_routine = cfg.subroutines.get(&start).unwrap(); let entry_id = start_routine.entry; let entry_bb = &start_routine.bbs[&entry_id]; assert_eq!(entry_bb.insts, vec![]); let (next_id, skip_id) = match entry_bb.terminator { Terminator::Skip { next, skip, .. } => (next, skip), unexpected => panic!("expected Skip, but found {:?}", unexpected), }; let next_jmp_id = match start_routine.bbs[&next_id].terminator { Terminator::Jump { target } => target, unexpected => panic!("expected Jump, but found {:?}", unexpected), }; let skip_jmp_id = match start_routine.bbs[&skip_id].terminator { Terminator::Jump { target } => target, unexpected => panic!("expected Jump, but found {:?}", unexpected), }; assert_eq!( start_routine.bbs[&next_jmp_id].insts, vec![Instruction::Sys(Addr(0x002))] ); assert_eq!( start_routine.bbs[&next_jmp_id].terminator, Terminator::Jump { target: entry_id } ); assert_eq!( start_routine.bbs[&skip_jmp_id].insts, vec![Instruction::Sys(Addr(0x001))] ); assert_eq!( start_routine.bbs[&skip_jmp_id].terminator, Terminator::Jump { target: next_jmp_id, } ); }
#[doc = "Reader of register UR10"] pub type R = crate::R<u32, super::UR10>; #[doc = "Reader of field `PA_END_2`"] pub type PA_END_2_R = crate::R<u16, u16>; #[doc = "Reader of field `SA_BEG_2`"] pub type SA_BEG_2_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:11 - Protected area end address for bank 2"] #[inline(always)] pub fn pa_end_2(&self) -> PA_END_2_R { PA_END_2_R::new((self.bits & 0x0fff) as u16) } #[doc = "Bits 16:27 - Secured area start address for bank 2"] #[inline(always)] pub fn sa_beg_2(&self) -> SA_BEG_2_R { SA_BEG_2_R::new(((self.bits >> 16) & 0x0fff) as u16) } }
use bevy::prelude::*; use crate::construction::ConstructionSite; #[derive(Debug, Clone)] pub enum ResourceType { Wasmium, } #[derive(Debug, Clone)] pub struct Mine { resource_type: ResourceType, /// The total amount of this resource that exists in the "resource deposit" underlying this mine deposit_qty: u32, /// Maximum amount of this resource this mine can hold at any time max_qty: u32, /// Amount of this resource available for pickup from the mine current_qty: u32, /// Units yielded per second yield_rate_ups: u32, } impl Mine { pub fn new( resource_type: ResourceType, max_qty: u32, deposit_qty: u32, yield_rate_ups: u32, ) -> Mine { Mine { deposit_qty, resource_type, max_qty, current_qty: 0, yield_rate_ups, } } } /// A mine is a component that will gradually store a resource that has been extracted from /// an underlying resource deposit. During construction of a mine, the deposit goes away // and is converted into a mine, hence the tracking of the original deposit quantity pub fn mines(mut query: Query<(&mut Mine, &ConstructionSite)>) { for (mut mine, site) in query.iter_mut() { if site.progress < 100 { continue; } if mine.current_qty < mine.max_qty { mine.current_qty = mine .current_qty .saturating_add(mine.yield_rate_ups) .clamp(0, mine.max_qty); mine.deposit_qty = mine.deposit_qty.saturating_sub(mine.yield_rate_ups); if mine.deposit_qty == 0 { info!("Mine has been depleted"); } if mine.current_qty == mine.max_qty { info!("Mine has reached capacity."); } } } }
//! ```elixir //! @doc """ //! Returns `true` if the `function/arity` is exported from `module`. //! """ //! @spec function_exported(module :: atom(), function :: atom(), arity :: 0..255) //! ``` use std::convert::TryInto; use anyhow::*; use liblumen_alloc::erts::apply::find_symbol; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::term::prelude::{Atom, Term}; use liblumen_alloc::{Arity, ModuleFunctionArity}; #[native_implemented::function(erlang:function_exported/3)] pub fn result(module: Term, function: Term, arity: Term) -> exception::Result<Term> { let module_atom: Atom = module.try_into().context("module must be an atom")?; let function_atom: Atom = function.try_into().context("function must be an atom")?; let arity_arity: Arity = arity.try_into().context("arity must be in 0-255")?; let module_function_arity = ModuleFunctionArity { module: module_atom, function: function_atom, arity: arity_arity, }; Ok(find_symbol(&module_function_arity).is_some().into()) }
#[inline(always)] fn compare_elements(x: char, y: char) -> bool { // My version // x != y && x.to_ascii_lowercase() == y.to_ascii_lowercase() // Optimization taken from Reddit: // https://www.reddit.com/r/adventofcode/comments/a3912m/2018_day_5_solutions/eb4ilyz/ x as u8 ^ 32 == y as u8 } pub fn part1(input: &str) -> usize { input .chars() .fold(Vec::new(), |mut acc, x| { match acc.last() { Some(prev) if compare_elements(x, *prev) => { acc.pop(); } _ => { acc.push(x); } } acc }) .len() } const LETTERS: &str = "abcdefghijklmnopqrstuvwxyz"; pub fn part2(input: &str) -> usize { LETTERS .chars() .map(|l| { part1( &input .chars() .filter(|c| c.to_ascii_lowercase() != l) .collect::<String>(), ) }) .min() .unwrap() } #[cfg(test)] mod tests { use super::{part1, part2}; use env_logger; #[test] fn test_part1() { env_logger::init(); assert_eq!(part1("dabAcCaCBAcCcaDA"), 10); assert_eq!(part1("aabAAB"), 6); assert_eq!(part1("aA"), 0); assert_eq!(part1("abBA"), 0); assert_eq!(part1("abAB"), 4); assert_eq!( part1("iITJoOyRrYiIXxjgLlGrRnSsShHsNqQdNngGDwNHhDgGWwaAjSsJdnLlOogG"), 2 ); } #[test] fn test_part2() { assert_eq!(part2("dabAcCaCBAcCcaDA"), 4); } }
use crate::cluster_api; use crate::cluster_management; use crate::deployment_management; use crate::runtime_plugin_manager; use clap::{App, Arg}; use common::config::*; use daemonize::Daemonize; // use std::sync::mpsc::{Receiver, Sender}; use std::env; use std::path::Path; use std::sync::mpsc; use std::thread; use chrono::{DateTime, Utc}; use std::collections::HashMap; use std::sync::{Arc, Mutex}; pub fn cli() { let matches = App::new("Gary") .version("0.1.0") .author("Marek C. <countsmarek@gmail.com>") .about("Does awesome things! very awesome.") .arg( Arg::with_name("config") .short("c") .long("config") .value_name("FILE") .help("Sets a custom config file") .multiple(false) .takes_value(true), ) .arg( Arg::with_name("v") .short("v") .multiple(true) .help("Sets the level of verbosity"), ) .arg( Arg::with_name("daemon") .short("d") .long("daemon") .multiple(false) .help("Setting this flag will enable running as a daemon"), ) .arg( Arg::with_name("target") .short("t") .long("target") .takes_value(true) .multiple(true) .help("The initial node to try and reach to join the cluster"), ) .get_matches(); let mut runtime_plugin_manager = runtime_plugin_manager::RuntimePluginManager::new(); let docker_box = Box::from(gary_docker::ContainerdRuntimePlugin::new()); runtime_plugin_manager.load_in_memory_plugin(docker_box); let cur_dir = env::current_dir(); if let Ok(mut cur_dir) = cur_dir { cur_dir.push("plugins/runtime/"); if Path::new(cur_dir.to_str().unwrap()).exists() { println!("{}", cur_dir.to_str().unwrap()); let _ = runtime_plugin_manager.load_plugins_in_dir(String::from(cur_dir.to_str().unwrap())); } } let config = common::config::ClusterConfig::get_config_or_default(matches.value_of("config")); let mut node_hash: HashMap<String, DateTime<Utc>> = HashMap::new(); if matches.is_present("target") { let t = matches.values_of("target").unwrap(); for f in t { node_hash.insert(String::from(f), Utc::now()); } } let mutex = Mutex::new(node_hash); let cluster_nodes: Arc<Mutex<HashMap<String, DateTime<Utc>>>> = Arc::new(mutex); //TODO: use config file if exists for vars if matches.is_present("daemon") { println!("Running as daemon"); let daemonize = Daemonize::new() .pid_file("/var/run/gary.pid") .chown_pid_file(true) .working_directory("/tmp") .user("root") .group("daemon"); match daemonize.start() { Ok(_) => run(cluster_nodes, config), Err(e) => println!("Should log failure to become daemon. error: {}", e), }; } else { run(cluster_nodes, config); } } fn run(targets: Arc<Mutex<HashMap<String, DateTime<Utc>>>>, init_config: ClusterConfig) { println!("Starting server"); // cluster consts - need to be CLI args const NODEHOSTNAME: &str = "nodehostname8675309"; // const NODELISTENERPORT: u16 = 5555; //create thread channels let (_tx_cm, rx_cm): (mpsc::Sender<&str>, mpsc::Receiver<&str>) = mpsc::channel(); let (tx_dm, rx_dm): (mpsc::Sender<&str>, mpsc::Receiver<&str>) = mpsc::channel(); // Channel to main thread for debug let (tx_mt, rx_mt): (mpsc::Sender<&str>, mpsc::Receiver<&str>) = mpsc::channel(); let cm_targets = targets.clone(); //spawn a new thread for cluster management thread::spawn(move || { println!("starting first node in the cluster"); // cluster_management::start_node(tx_cm, rx_dm); // Communicates with Deployment Manager cluster_management::start_node(tx_mt, rx_dm, NODEHOSTNAME, cm_targets); // Communicates with Main Thread }); let api_nodes = targets.clone(); thread::spawn(move || { cluster_api::start(api_nodes); }); // run deployment management on this thread println!("starting deployment management"); deployment_management::manage_deployments(tx_dm, rx_cm); loop { // Consider using mpsc::Receiver::poll() match rx_mt.recv() { Ok(i) => println!("got this from cluster mgmt: {}", i), Err(_) => { // println!("channel closed"); // break; } } } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICompositionCapabilitiesInteropFactory(pub ::windows::core::IUnknown); impl ICompositionCapabilitiesInteropFactory { #[cfg(all(feature = "UI_Composition", feature = "Win32_Foundation"))] pub unsafe fn GetForWindow<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>>(&self, hwnd: Param0) -> ::windows::core::Result<super::super::super::super::UI::Composition::CompositionCapabilities> { let mut result__: <super::super::super::super::UI::Composition::CompositionCapabilities as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), hwnd.into_param().abi(), &mut result__).from_abi::<super::super::super::super::UI::Composition::CompositionCapabilities>(result__) } } unsafe impl ::windows::core::Interface for ICompositionCapabilitiesInteropFactory { type Vtable = ICompositionCapabilitiesInteropFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2c9db356_e70d_4642_8298_bc4aa5b4865c); } impl ::core::convert::From<ICompositionCapabilitiesInteropFactory> for ::windows::core::IUnknown { fn from(value: ICompositionCapabilitiesInteropFactory) -> Self { value.0 } } impl ::core::convert::From<&ICompositionCapabilitiesInteropFactory> for ::windows::core::IUnknown { fn from(value: &ICompositionCapabilitiesInteropFactory) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICompositionCapabilitiesInteropFactory { 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 ICompositionCapabilitiesInteropFactory { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICompositionCapabilitiesInteropFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "UI_Composition", feature = "Win32_Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hwnd: super::super::super::Foundation::HWND, result: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "UI_Composition", feature = "Win32_Foundation")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICompositionDrawingSurfaceInterop(pub ::windows::core::IUnknown); impl ICompositionDrawingSurfaceInterop { #[cfg(feature = "Win32_Foundation")] pub unsafe fn BeginDraw(&self, updaterect: *const super::super::super::Foundation::RECT, iid: *const ::windows::core::GUID, updateobject: *mut *mut ::core::ffi::c_void, updateoffset: *mut super::super::super::Foundation::POINT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(updaterect), ::core::mem::transmute(iid), ::core::mem::transmute(updateobject), ::core::mem::transmute(updateoffset)).ok() } pub unsafe fn EndDraw(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Resize<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::SIZE>>(&self, sizepixels: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), sizepixels.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Scroll(&self, scrollrect: *const super::super::super::Foundation::RECT, cliprect: *const super::super::super::Foundation::RECT, offsetx: i32, offsety: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(scrollrect), ::core::mem::transmute(cliprect), ::core::mem::transmute(offsetx), ::core::mem::transmute(offsety)).ok() } pub unsafe fn ResumeDraw(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn SuspendDraw(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self)).ok() } } unsafe impl ::windows::core::Interface for ICompositionDrawingSurfaceInterop { type Vtable = ICompositionDrawingSurfaceInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfd04e6e3_fe0c_4c3c_ab19_a07601a576ee); } impl ::core::convert::From<ICompositionDrawingSurfaceInterop> for ::windows::core::IUnknown { fn from(value: ICompositionDrawingSurfaceInterop) -> Self { value.0 } } impl ::core::convert::From<&ICompositionDrawingSurfaceInterop> for ::windows::core::IUnknown { fn from(value: &ICompositionDrawingSurfaceInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICompositionDrawingSurfaceInterop { 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 ICompositionDrawingSurfaceInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICompositionDrawingSurfaceInterop_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, updaterect: *const super::super::super::Foundation::RECT, iid: *const ::windows::core::GUID, updateobject: *mut *mut ::core::ffi::c_void, updateoffset: *mut super::super::super::Foundation::POINT) -> ::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, sizepixels: super::super::super::Foundation::SIZE) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, scrollrect: *const super::super::super::Foundation::RECT, cliprect: *const super::super::super::Foundation::RECT, offsetx: i32, offsety: i32) -> ::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) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICompositionDrawingSurfaceInterop2(pub ::windows::core::IUnknown); impl ICompositionDrawingSurfaceInterop2 { #[cfg(feature = "Win32_Foundation")] pub unsafe fn BeginDraw(&self, updaterect: *const super::super::super::Foundation::RECT, iid: *const ::windows::core::GUID, updateobject: *mut *mut ::core::ffi::c_void, updateoffset: *mut super::super::super::Foundation::POINT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(updaterect), ::core::mem::transmute(iid), ::core::mem::transmute(updateobject), ::core::mem::transmute(updateoffset)).ok() } pub unsafe fn EndDraw(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Resize<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::SIZE>>(&self, sizepixels: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), sizepixels.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Scroll(&self, scrollrect: *const super::super::super::Foundation::RECT, cliprect: *const super::super::super::Foundation::RECT, offsetx: i32, offsety: i32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(scrollrect), ::core::mem::transmute(cliprect), ::core::mem::transmute(offsetx), ::core::mem::transmute(offsety)).ok() } pub unsafe fn ResumeDraw(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self)).ok() } pub unsafe fn SuspendDraw(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn CopySurface<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, destinationresource: Param0, destinationoffsetx: i32, destinationoffsety: i32, sourcerectangle: *const super::super::super::Foundation::RECT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self), destinationresource.into_param().abi(), ::core::mem::transmute(destinationoffsetx), ::core::mem::transmute(destinationoffsety), ::core::mem::transmute(sourcerectangle)).ok() } } unsafe impl ::windows::core::Interface for ICompositionDrawingSurfaceInterop2 { type Vtable = ICompositionDrawingSurfaceInterop2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x41e64aae_98c0_4239_8e95_a330dd6aa18b); } impl ::core::convert::From<ICompositionDrawingSurfaceInterop2> for ::windows::core::IUnknown { fn from(value: ICompositionDrawingSurfaceInterop2) -> Self { value.0 } } impl ::core::convert::From<&ICompositionDrawingSurfaceInterop2> for ::windows::core::IUnknown { fn from(value: &ICompositionDrawingSurfaceInterop2) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICompositionDrawingSurfaceInterop2 { 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 ICompositionDrawingSurfaceInterop2 { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<ICompositionDrawingSurfaceInterop2> for ICompositionDrawingSurfaceInterop { fn from(value: ICompositionDrawingSurfaceInterop2) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&ICompositionDrawingSurfaceInterop2> for ICompositionDrawingSurfaceInterop { fn from(value: &ICompositionDrawingSurfaceInterop2) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, ICompositionDrawingSurfaceInterop> for ICompositionDrawingSurfaceInterop2 { fn into_param(self) -> ::windows::core::Param<'a, ICompositionDrawingSurfaceInterop> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, ICompositionDrawingSurfaceInterop> for &ICompositionDrawingSurfaceInterop2 { fn into_param(self) -> ::windows::core::Param<'a, ICompositionDrawingSurfaceInterop> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct ICompositionDrawingSurfaceInterop2_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, updaterect: *const super::super::super::Foundation::RECT, iid: *const ::windows::core::GUID, updateobject: *mut *mut ::core::ffi::c_void, updateoffset: *mut super::super::super::Foundation::POINT) -> ::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, sizepixels: super::super::super::Foundation::SIZE) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, scrollrect: *const super::super::super::Foundation::RECT, cliprect: *const super::super::super::Foundation::RECT, offsetx: i32, offsety: i32) -> ::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) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, destinationresource: ::windows::core::RawPtr, destinationoffsetx: i32, destinationoffsety: i32, sourcerectangle: *const super::super::super::Foundation::RECT) -> ::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 ICompositionGraphicsDeviceInterop(pub ::windows::core::IUnknown); impl ICompositionGraphicsDeviceInterop { pub unsafe fn GetRenderingDevice(&self) -> ::windows::core::Result<::windows::core::IUnknown> { let mut result__: <::windows::core::IUnknown 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::IUnknown>(result__) } pub unsafe fn SetRenderingDevice<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, value: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), value.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for ICompositionGraphicsDeviceInterop { type Vtable = ICompositionGraphicsDeviceInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa116ff71_f8bf_4c8a_9c98_70779a32a9c8); } impl ::core::convert::From<ICompositionGraphicsDeviceInterop> for ::windows::core::IUnknown { fn from(value: ICompositionGraphicsDeviceInterop) -> Self { value.0 } } impl ::core::convert::From<&ICompositionGraphicsDeviceInterop> for ::windows::core::IUnknown { fn from(value: &ICompositionGraphicsDeviceInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICompositionGraphicsDeviceInterop { 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 ICompositionGraphicsDeviceInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICompositionGraphicsDeviceInterop_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, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICompositorDesktopInterop(pub ::windows::core::IUnknown); impl ICompositorDesktopInterop { #[cfg(all(feature = "UI_Composition_Desktop", feature = "Win32_Foundation"))] pub unsafe fn CreateDesktopWindowTarget<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HWND>, Param1: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, hwndtarget: Param0, istopmost: Param1) -> ::windows::core::Result<super::super::super::super::UI::Composition::Desktop::DesktopWindowTarget> { let mut result__: <super::super::super::super::UI::Composition::Desktop::DesktopWindowTarget as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), hwndtarget.into_param().abi(), istopmost.into_param().abi(), &mut result__).from_abi::<super::super::super::super::UI::Composition::Desktop::DesktopWindowTarget>(result__) } pub unsafe fn EnsureOnThread(&self, threadid: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(threadid)).ok() } } unsafe impl ::windows::core::Interface for ICompositorDesktopInterop { type Vtable = ICompositorDesktopInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x29e691fa_4567_4dca_b319_d0f207eb6807); } impl ::core::convert::From<ICompositorDesktopInterop> for ::windows::core::IUnknown { fn from(value: ICompositorDesktopInterop) -> Self { value.0 } } impl ::core::convert::From<&ICompositorDesktopInterop> for ::windows::core::IUnknown { fn from(value: &ICompositorDesktopInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICompositorDesktopInterop { 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 ICompositorDesktopInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICompositorDesktopInterop_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(all(feature = "UI_Composition_Desktop", feature = "Win32_Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hwndtarget: super::super::super::Foundation::HWND, istopmost: super::super::super::Foundation::BOOL, result: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "UI_Composition_Desktop", feature = "Win32_Foundation")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, threadid: u32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICompositorInterop(pub ::windows::core::IUnknown); impl ICompositorInterop { #[cfg(all(feature = "UI_Composition", feature = "Win32_Foundation"))] pub unsafe fn CreateCompositionSurfaceForHandle<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::HANDLE>>(&self, swapchain: Param0) -> ::windows::core::Result<super::super::super::super::UI::Composition::ICompositionSurface> { let mut result__: <super::super::super::super::UI::Composition::ICompositionSurface as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), swapchain.into_param().abi(), &mut result__).from_abi::<super::super::super::super::UI::Composition::ICompositionSurface>(result__) } #[cfg(feature = "UI_Composition")] pub unsafe fn CreateCompositionSurfaceForSwapChain<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, swapchain: Param0) -> ::windows::core::Result<super::super::super::super::UI::Composition::ICompositionSurface> { let mut result__: <super::super::super::super::UI::Composition::ICompositionSurface as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), swapchain.into_param().abi(), &mut result__).from_abi::<super::super::super::super::UI::Composition::ICompositionSurface>(result__) } #[cfg(feature = "UI_Composition")] pub unsafe fn CreateGraphicsDevice<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, renderingdevice: Param0) -> ::windows::core::Result<super::super::super::super::UI::Composition::CompositionGraphicsDevice> { let mut result__: <super::super::super::super::UI::Composition::CompositionGraphicsDevice as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), renderingdevice.into_param().abi(), &mut result__).from_abi::<super::super::super::super::UI::Composition::CompositionGraphicsDevice>(result__) } } unsafe impl ::windows::core::Interface for ICompositorInterop { type Vtable = ICompositorInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x25297d5c_3ad4_4c9c_b5cf_e36a38512330); } impl ::core::convert::From<ICompositorInterop> for ::windows::core::IUnknown { fn from(value: ICompositorInterop) -> Self { value.0 } } impl ::core::convert::From<&ICompositorInterop> for ::windows::core::IUnknown { fn from(value: &ICompositorInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICompositorInterop { 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 ICompositorInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICompositorInterop_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(all(feature = "UI_Composition", feature = "Win32_Foundation"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, swapchain: super::super::super::Foundation::HANDLE, result: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "UI_Composition", feature = "Win32_Foundation")))] usize, #[cfg(feature = "UI_Composition")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, swapchain: ::windows::core::RawPtr, result: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Composition"))] usize, #[cfg(feature = "UI_Composition")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, renderingdevice: ::windows::core::RawPtr, result: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Composition"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IDesktopWindowTargetInterop(pub ::windows::core::IUnknown); impl IDesktopWindowTargetInterop { #[cfg(feature = "Win32_Foundation")] pub unsafe fn Hwnd(&self) -> ::windows::core::Result<super::super::super::Foundation::HWND> { let mut result__: <super::super::super::Foundation::HWND as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<super::super::super::Foundation::HWND>(result__) } } unsafe impl ::windows::core::Interface for IDesktopWindowTargetInterop { type Vtable = IDesktopWindowTargetInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x35dbf59e_e3f9_45b0_81e7_fe75f4145dc9); } impl ::core::convert::From<IDesktopWindowTargetInterop> for ::windows::core::IUnknown { fn from(value: IDesktopWindowTargetInterop) -> Self { value.0 } } impl ::core::convert::From<&IDesktopWindowTargetInterop> for ::windows::core::IUnknown { fn from(value: &IDesktopWindowTargetInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IDesktopWindowTargetInterop { 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 IDesktopWindowTargetInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IDesktopWindowTargetInterop_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, value: *mut super::super::super::Foundation::HWND) -> ::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 ISwapChainInterop(pub ::windows::core::IUnknown); impl ISwapChainInterop { pub unsafe fn SetSwapChain<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, swapchain: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), swapchain.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for ISwapChainInterop { type Vtable = ISwapChainInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x26f496a0_7f38_45fb_88f7_faaabe67dd59); } impl ::core::convert::From<ISwapChainInterop> for ::windows::core::IUnknown { fn from(value: ISwapChainInterop) -> Self { value.0 } } impl ::core::convert::From<&ISwapChainInterop> for ::windows::core::IUnknown { fn from(value: &ISwapChainInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISwapChainInterop { 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 ISwapChainInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ISwapChainInterop_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, swapchain: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IVisualInteractionSourceInterop(pub ::windows::core::IUnknown); impl IVisualInteractionSourceInterop { #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Input_Pointer", feature = "Win32_UI_WindowsAndMessaging"))] pub unsafe fn TryRedirectForManipulation(&self, pointerinfo: *const super::super::super::UI::Input::Pointer::POINTER_INFO) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(pointerinfo)).ok() } } unsafe impl ::windows::core::Interface for IVisualInteractionSourceInterop { type Vtable = IVisualInteractionSourceInterop_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x11f62cd1_2f9d_42d3_b05f_d6790d9e9f8e); } impl ::core::convert::From<IVisualInteractionSourceInterop> for ::windows::core::IUnknown { fn from(value: IVisualInteractionSourceInterop) -> Self { value.0 } } impl ::core::convert::From<&IVisualInteractionSourceInterop> for ::windows::core::IUnknown { fn from(value: &IVisualInteractionSourceInterop) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IVisualInteractionSourceInterop { 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 IVisualInteractionSourceInterop { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IVisualInteractionSourceInterop_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_UI_Input_Pointer", feature = "Win32_UI_WindowsAndMessaging"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pointerinfo: *const super::super::super::UI::Input::Pointer::POINTER_INFO) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_UI_Input_Pointer", feature = "Win32_UI_WindowsAndMessaging")))] usize, );
use super::*; use ffi_support::{FfiStr, ExternError}; #[no_mangle] pub extern fn indy_res_context_create(pool_handle: Handle, submitter_did: FfiStr<'_>, submitter_did_private_key: &ByteArray, context_json: FfiStr<'_>, context_did: &mut OutString, err: &mut ExternError) -> i32 { let submitter_did = submitter_did.as_str(); let submitter_did_buffer = submitter_did_private_key.to_vec(); let context_json = context_json.as_str(); *err = ExternError::success(); //TODO: do some work let s = r#"{"id":"did:sov1qazxsw2wsdxcde34erfgvbg"}"#; assign_out_string!(context_did, s); if err.get_code().code() > 0 { 0 } else { 1 } } #[cfg(test)] mod tests { use ffi_support::{FfiStr, ExternError}; use std::os::raw::c_char; use crate::ffi::pool_context::indy_res_context_create; use std::ffi::CString; #[test] fn vanilla_test() { let pool_handle = 0; let did = std::ffi::CString::new("did:sov:aksjdhgkasjhtkhrg").unwrap(); let submitter_did = unsafe { FfiStr::from_raw(did.as_ptr()) }; let submitter_private_key = vec![1u8; 32]; let context = std::ffi::CString::new("test").unwrap(); let context_json = unsafe { FfiStr::from_raw(context.as_ptr()) }; let mut context_did: *const c_char = std::ptr::null(); let mut err = ExternError::success(); let res = indy_res_context_create(pool_handle, submitter_did, submitter_private_key.as_slice().as_ptr() as *const u8, submitter_private_key.len(), context_json, &mut context_did, &mut err); let s = unsafe { std::ffi::CStr::from_ptr(context_did) }; let ctx_did = s.to_str().unwrap(); dbg!(ctx_did); } }
use winapi::um::winuser::{WS_OVERLAPPEDWINDOW, WS_VISIBLE, WS_DISABLED, WS_MAXIMIZE, WS_MINIMIZE, WS_CAPTION, WS_MINIMIZEBOX, WS_MAXIMIZEBOX, WS_SYSMENU, WS_THICKFRAME, WS_CLIPCHILDREN, WS_CLIPSIBLINGS }; use crate::win32::base_helper::check_hwnd; use crate::win32::window_helper as wh; use crate::{NwgError, Icon}; use super::{ControlBase, ControlHandle}; const NOT_BOUND: &'static str = "ExternCanvas is not yet bound to a winapi object"; const BAD_HANDLE: &'static str = "INTERNAL ERROR: ExternCanvas handle is not HWND!"; bitflags! { /** The extern canvas flags. Note that the window flags only applies if the the extern canvas is a top level window (it has no parents). Window flags: * MAIN_WINDOW: Combine all the top level system window decoration: A title, a system menu, a resizable frame, and the close, minimize, maximize buttons * WINDOW: A window with a title, a system menu, a close button, and a non resizable border. * MINIMIZE_BOX: Includes a minimize button * MAXIMIZE_BOX: Includes a maximize button * SYS_MENU: Includes a system menu when the user right click the window header * MAXIMIZED: Create the window as maximized * MINIMIZED: Create the window as minimized * RESIZABLE: Add a resizable border General flags: * VISIBLE: Show the window right away */ pub struct ExternCanvasFlags: u32 { const NONE = 0; const MAIN_WINDOW = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_THICKFRAME | WS_MAXIMIZEBOX; const WINDOW = WS_CAPTION | WS_SYSMENU; const MINIMIZE_BOX = WS_MINIMIZEBOX; const MAXIMIZE_BOX = WS_MAXIMIZEBOX; const SYS_MENU = WS_SYSMENU; const VISIBLE = WS_VISIBLE; const DISABLED = WS_DISABLED; const MAXIMIZED = WS_MAXIMIZE; const MINIMIZED = WS_MINIMIZE; const RESIZABLE = WS_THICKFRAME | WS_MAXIMIZEBOX; } } /** An `ExternCanvas` is a window/children control that is painted to by an external API (such as OpenGL, Vulkan or DirectX). When building a `ExternCanvas`, leaving the parent field empty will create a window-like canvas. If a parent is set, the canvas will be a children control (like a button). When used as a child, `ExternCanvas` can be used as a way to add highly dynamic controls to a NWG application (ex: a video player). Requires the `extern-canvas` feature. As a top level window, the extern canvas has the same features as the window control. As a children control, resize and move events cannot be triggered and window parameters are not visible. **Builder parameters:** * `flags`: The window flags. See `ExternCanvasFlags` * `ex_flags`: A combination of win32 window extended flags. Unlike `flags`, ex_flags must be used straight from winapi * `title`: The text in the window title bar * `size`: The default size of the window * `position`: The default position of the window in the desktop * `icon`: The window icon * `parent`: Logical parent of the window, unlike children controls, this is NOT required. **Control events:** * `OnInit`: The window was created * `MousePress(_)`: Generic mouse press events on the button * `OnMouseMove`: Generic mouse mouse event * `OnMouseWheel`: Generic mouse wheel event * `OnPaint`: Generic on paint event * `OnKeyPress`: Generic key press * `OnKeyRelease`: Generic ket release * `OnResize`: When the window is resized * `OnResizeBegin`: Just before the window begins being resized by the user * `OnResizeEnd`: Just after the user stops resizing the window * `OnWindowMaximize`: When the window is maximized * `OnWindowMinimize`: When the window is minimized * `OnMove`: When the window is moved by the user * `OnMinMaxInfo`: When the size or position of the window is about to change and the size of the windows must be restricted */ #[derive(Default)] pub struct ExternCanvas { pub handle: ControlHandle } impl ExternCanvas { pub fn builder<'a>() -> ExternCanvasBuilder<'a> { ExternCanvasBuilder { title: "New Canvas", size: (500, 500), position: (300, 300), flags: None, ex_flags: 0, icon: None, parent: None } } /// Invalidate the whole drawing region. For canvas that are children control, this should be called in the paint event. pub fn invalidate(&self) { use winapi::um::winuser::InvalidateRect; use std::ptr; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { InvalidateRect(handle, ptr::null(), 1); } } /// Return the icon of the window pub fn icon(&self) -> Option<Icon> { use winapi::um::winuser::WM_GETICON; use winapi::um::winnt::HANDLE; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let icon_handle = wh::send_message(handle, WM_GETICON, 0, 0); if icon_handle == 0 { None } else { Some(Icon { handle: icon_handle as HANDLE, owned: false }) } } /// Set the icon in the window /// - icon: The new icon. If None, the icon is removed pub fn set_icon(&self, icon: Option<&Icon>) { use winapi::um::winuser::WM_SETICON; use std::{mem, ptr}; let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); let image_handle = icon.map(|i| i.handle).unwrap_or(ptr::null_mut()); unsafe { wh::send_message(handle, WM_SETICON, 0, mem::transmute(image_handle)); } } /// Return true if the control currently has the keyboard focus pub fn focus(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_focus(handle) } } /// Set the keyboard focus on the button pub fn set_focus(&self) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_focus(handle); } } /// Return true if the control user can interact with the control, return false otherwise pub fn enabled(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_enabled(handle) } } /// Enable or disable the control pub fn set_enabled(&self, v: bool) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_enabled(handle, v) } } /// Return true if the control is visible to the user. Will return true even if the /// control is outside of the parent client view (ex: at the position (10000, 10000)) pub fn visible(&self) -> bool { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_visibility(handle) } } /// Show or hide the control to the user pub fn set_visible(&self, v: bool) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_visibility(handle, v) } } /// Return the size of the button in the parent window pub fn size(&self) -> (u32, u32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_size(handle) } } /// Return the physical size of canvas in pixels considering the dpi scale pub fn physical_size(&self) -> (u32, u32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_physical_size(handle) } } /// Set the size of the button in the parent window pub fn set_size(&self, x: u32, y: u32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_size(handle, x, y, true) } } /// Return the position of the button in the parent window pub fn position(&self) -> (i32, i32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_position(handle) } } /// Set the position of the button in the parent window pub fn set_position(&self, x: i32, y: i32) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_position(handle, x, y) } } /// Return window title pub fn text(&self) -> String { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::get_window_text(handle) } } /// Set the window title pub fn set_text<'a>(&self, v: &'a str) { let handle = check_hwnd(&self.handle, NOT_BOUND, BAD_HANDLE); unsafe { wh::set_window_text(handle, v) } } /// Winapi class name used during control creation pub fn class_name(&self) -> &'static str { "NWG_EXTERN_CANVAS" } // Winapi base flags used during window creation pub fn flags(&self) -> u32 { WS_OVERLAPPEDWINDOW | WS_VISIBLE } /// Winapi flags required by the control pub fn forced_flags(&self) -> u32 { WS_CLIPCHILDREN | WS_CLIPSIBLINGS } } impl Drop for ExternCanvas { fn drop(&mut self) { self.handle.destroy(); } } #[cfg(feature = "raw-win-handle")] use raw_window_handle::{HasRawWindowHandle, RawWindowHandle, windows::WindowsHandle}; #[cfg(feature = "raw-win-handle")] unsafe impl HasRawWindowHandle for ExternCanvas { fn raw_window_handle(&self) -> RawWindowHandle { use winapi::um::winuser::GWL_HINSTANCE; match self.handle { ControlHandle::Hwnd(hwnd) => { let hinstance = wh::get_window_long(hwnd, GWL_HINSTANCE); RawWindowHandle::Windows(WindowsHandle { hwnd: hwnd as _, hinstance: hinstance as _, ..WindowsHandle::empty() }) } // Not a valid window handle, so return an empty handle _ => RawWindowHandle::Windows(WindowsHandle::empty()) } } } pub struct ExternCanvasBuilder<'a> { title: &'a str, size: (i32, i32), position: (i32, i32), flags: Option<ExternCanvasFlags>, ex_flags: u32, icon: Option<&'a Icon>, parent: Option<ControlHandle> } impl<'a> ExternCanvasBuilder<'a> { pub fn flags(mut self, flags: ExternCanvasFlags) -> ExternCanvasBuilder<'a> { self.flags = Some(flags); self } pub fn ex_flags(mut self, flags: u32) -> ExternCanvasBuilder<'a> { self.ex_flags = flags; self } pub fn title(mut self, text: &'a str) -> ExternCanvasBuilder<'a> { self.title = text; self } pub fn size(mut self, size: (i32, i32)) -> ExternCanvasBuilder<'a> { self.size = size; self } pub fn position(mut self, pos: (i32, i32)) -> ExternCanvasBuilder<'a> { self.position = pos; self } pub fn icon(mut self, ico: Option<&'a Icon>) -> ExternCanvasBuilder<'a> { self.icon = ico; self } pub fn parent<C: Into<ControlHandle>>(mut self, p: Option<C>) -> ExternCanvasBuilder<'a> { self.parent = p.map(|p2| p2.into()); self } pub fn build(self, out: &mut ExternCanvas) -> Result<(), NwgError> { use winapi::um::winuser::{WS_CHILD}; let mut flags = self.flags.map(|f| f.bits()).unwrap_or(out.flags()); // Remove window flags if a parent is set if self.parent.is_some() { flags &= !(WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX | WS_THICKFRAME | WS_MAXIMIZEBOX); flags |= WS_CHILD; } *out = Default::default(); out.handle = ControlBase::build_hwnd() .class_name(out.class_name()) .forced_flags(out.forced_flags()) .flags(flags) .ex_flags(self.ex_flags) .size(self.size) .position(self.position) .text(self.title) .parent(self.parent) .build()?; if self.icon.is_some() { out.set_icon(self.icon); } Ok(()) } }
mod draw; use cogs_gamedev::controls::InputHandler; use crate::{ assets::Assets, boilerplates::{FrameInfo, Gamemode, GamemodeDrawer, Transition}, controls::{Control, InputSubscriber}, modes::ModeEnding, simulator::{ board::Board, floodfill::{FloodFillError, FloodFiller}, solutions::{Metrics, Solution}, transport::Cable, }, utils::profile::Profile, }; use super::ModePlaying; /// Standard time to do one step in frames. pub(super) const STEP_TIME: u64 = 30; /// Time to do steps when zooming via tab const STEP_TIME_ON_DEMAND: u64 = 10; /// Amount the win box goes in by per frame const WIN_BOX_ENTER_SPEED: f32 = 2.0 / 30.0; #[derive(Clone)] pub(super) struct ModeSimulating { /// We do need to clone into this, which is kind of bad, /// but it makes things simpler and i really doubt there's /// going to be bad perf issues from cloning like 1kb board: Board, flooder: FloodFiller, advance_method: AdvanceMethod, level_key: String, level_idx: usize, level_name: String, step_start: u64, } impl ModeSimulating { pub fn new(mode: &ModePlaying, advance_method: AdvanceMethod, current_frame: u64) -> Self { Self { board: mode.board.clone(), flooder: FloodFiller::new(&mode.board), advance_method, level_key: mode.level_key.clone(), level_idx: mode.level_idx, level_name: mode.level_name.clone(), step_start: current_frame, } } /// Update my advancing method. /// Return if we should step. fn handle_advance(&mut self, controls: &InputSubscriber, frame_info: FrameInfo) -> bool { match self.advance_method { AdvanceMethod::Errors(..) | AdvanceMethod::WinScreen { .. } => false, _ if controls.clicked_down(Control::StepOnce) => { self.advance_method = AdvanceMethod::OnDemand; true } AdvanceMethod::ByFrames { start_frame, interval, } => { if controls.clicked_down(Control::Start) { // pause self.advance_method = AdvanceMethod::OnDemand; false } else { // Check if we're on a hot frame let dframe = frame_info.frames_ran - start_frame; dframe % interval == 0 } } AdvanceMethod::OnDemand => { if controls.clicked_down(Control::Start) { // back to automatic play self.advance_method = AdvanceMethod::ByFrames { start_frame: frame_info.frames_ran, interval: STEP_TIME, }; true } else { // just waiting false } } } } fn step(&mut self) { if !self.advance_method.is_special() { let errors = self.flooder.step(&self.board); if !errors.is_empty() { self.advance_method = AdvanceMethod::Errors(errors); } else if let Some(metrics) = self.flooder.did_win(&self.board) { // pog self.advance_method = AdvanceMethod::WinScreen { text: self.get_win_text(&metrics), appear_progress: 0.0, }; let mut profile = Profile::get(); let soln = profile .solutions .entry(self.level_key.clone()) .or_insert_with(|| Solution { cables: self.board.cables.clone(), left: self.board.left.clone(), right: self.board.right.clone(), level_key: self.level_key.clone(), metrics: None, }); soln.metrics = Some(metrics); } } } fn get_win_text(&self, metrics: &Metrics) -> String { let chars_across = 25usize; // subtract length of "TOTAL CYCLES:" let cycles_metric = format!( "TOTAL CYCLES:{:.>width$}", metrics.total_cycles, width = chars_across - 13 ); let min_cycles_metric = format!( "MIN CYCLES:{:.>width$}", metrics.min_cycles, width = chars_across - 11 ); // length of "CROSSOVERS:" let crossover_metric = format!( "CROSSOVERS:{:.>width$}", metrics.crossovers, width = chars_across - 11 ); format!( "{}\n{}\n{}\n\n\r\r{:^width$}", cycles_metric, min_cycles_metric, crossover_metric, "CLICK TO CONTINUE", width = chars_across ) } } impl Gamemode for ModeSimulating { fn update( &mut self, controls: &InputSubscriber, frame_info: FrameInfo, assets: &Assets, ) -> Transition { if controls.clicked_down(Control::Escape) { return Transition::Pop; } if let AdvanceMethod::WinScreen { appear_progress, .. } = &mut self.advance_method { *appear_progress += WIN_BOX_ENTER_SPEED; if *appear_progress > 0.999 && controls.clicked_down(Control::Select) { // TODO: overflows let new_idx = self.level_idx + 1; let trans = if assets.levels.get(new_idx).is_some() { Box::new(ModePlaying::new(&assets.levels[new_idx], new_idx)) as _ } else { Box::new(ModeEnding::new()) as _ }; // Pop this state, and the level select below it return Transition::PopNAndPush(2, vec![trans]); } } else { let advance = self.handle_advance(controls, frame_info); if advance { self.step_start = frame_info.frames_ran; self.step(); } } Transition::None } fn get_draw_info(&mut self) -> Box<dyn GamemodeDrawer> { Box::new(self.clone()) } } #[derive(Clone)] pub(super) enum AdvanceMethod { /// Advance the flood fill once every this many frames ByFrames { start_frame: u64, interval: u64 }, /// Advance it on demand when tab is pressed OnDemand, /// Wait there were errors! Errors(Vec<FloodFillError>), /// Haha (johnathon) we are not actually stepping, instead here's our win screen WinScreen { /// Progress from 0-1 how in-view our textbox is appear_progress: f32, /// Text appearing on the win screen text: String, }, } impl AdvanceMethod { /// Returns `true` if the method is special and won't actually advance fn is_special(&self) -> bool { matches!( self, AdvanceMethod::Errors(..) | AdvanceMethod::WinScreen { .. } ) } }
fn main() { loop { //emulator.updateCpu() //emulator.updatePpu() } }
#[doc = "Reader of register CLIDR"] pub type R = crate::R<u32, super::CLIDR>; #[doc = "Reader of field `CL1`"] pub type CL1_R = crate::R<u8, u8>; #[doc = "Reader of field `CL2`"] pub type CL2_R = crate::R<u8, u8>; #[doc = "Reader of field `CL3`"] pub type CL3_R = crate::R<u8, u8>; #[doc = "Reader of field `CL4`"] pub type CL4_R = crate::R<u8, u8>; #[doc = "Reader of field `CL5`"] pub type CL5_R = crate::R<u8, u8>; #[doc = "Reader of field `CL6`"] pub type CL6_R = crate::R<u8, u8>; #[doc = "Reader of field `CL7`"] pub type CL7_R = crate::R<u8, u8>; #[doc = "Reader of field `LoUIS`"] pub type LOUIS_R = crate::R<u8, u8>; #[doc = "Reader of field `LoC`"] pub type LOC_R = crate::R<u8, u8>; #[doc = "Reader of field `LoU`"] pub type LOU_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:2 - CL1"] #[inline(always)] pub fn cl1(&self) -> CL1_R { CL1_R::new((self.bits & 0x07) as u8) } #[doc = "Bits 3:5 - CL2"] #[inline(always)] pub fn cl2(&self) -> CL2_R { CL2_R::new(((self.bits >> 3) & 0x07) as u8) } #[doc = "Bits 6:8 - CL3"] #[inline(always)] pub fn cl3(&self) -> CL3_R { CL3_R::new(((self.bits >> 6) & 0x07) as u8) } #[doc = "Bits 9:11 - CL4"] #[inline(always)] pub fn cl4(&self) -> CL4_R { CL4_R::new(((self.bits >> 9) & 0x07) as u8) } #[doc = "Bits 12:14 - CL5"] #[inline(always)] pub fn cl5(&self) -> CL5_R { CL5_R::new(((self.bits >> 12) & 0x07) as u8) } #[doc = "Bits 15:17 - CL6"] #[inline(always)] pub fn cl6(&self) -> CL6_R { CL6_R::new(((self.bits >> 15) & 0x07) as u8) } #[doc = "Bits 18:20 - CL7"] #[inline(always)] pub fn cl7(&self) -> CL7_R { CL7_R::new(((self.bits >> 18) & 0x07) as u8) } #[doc = "Bits 21:23 - LoUIS"] #[inline(always)] pub fn lo_uis(&self) -> LOUIS_R { LOUIS_R::new(((self.bits >> 21) & 0x07) as u8) } #[doc = "Bits 24:26 - LoC"] #[inline(always)] pub fn lo_c(&self) -> LOC_R { LOC_R::new(((self.bits >> 24) & 0x07) as u8) } #[doc = "Bits 27:29 - LoU"] #[inline(always)] pub fn lo_u(&self) -> LOU_R { LOU_R::new(((self.bits >> 27) & 0x07) as u8) } }
use std::mem; use Error; /// Encode a natural number according to section 7.2.1 /// of the Simplicity tech report pub fn encode(n: usize) -> Vec<bool> { assert_ne!(n, 0); // Cannot encode zero let len = 8 * mem::size_of::<usize>() - n.leading_zeros() as usize - 1; if len == 0 { vec![false] } else { let mut ret = vec![true]; ret.extend(encode(len)); let idx = ret.len(); let mut n = n - (1 << len as u32); for _ in 0..len { ret.push(n % 2 == 1); n /= 2; } ret[idx..].reverse(); ret } } /// Decode a natural number according to section 7.2.1 /// of the Simplicity whitepaper. pub fn decode<BitStream: Iterator<Item = bool>>( mut iter: BitStream, ) -> Result<usize, Error> { let mut recurse_depth = 0; loop { match iter.next() { Some(true) => recurse_depth += 1, Some(false) => break, None => return Err(Error::EndOfStream), } } let mut len = 0; loop { let mut n = 1; for _ in 0..len { let bit = match iter.next() { Some(false) => 0, Some(true) => 1, None => return Err(Error::EndOfStream), }; n = 2 * n + bit; } if recurse_depth == 0 { return Ok(n) } else { len = n; if len > 31 { return Err(Error::NaturalOverflow); } recurse_depth -= 1; } } } #[cfg(test)] mod tests { use super::*; #[test] fn decode_fixed() { let tries = vec![ (1, vec![false]), (2, vec![true, false, false]), (3, vec![true, false, true]), (4, vec![true, true, false, false, false, false]), (5, vec![true, true, false, false, false, true]), (6, vec![true, true, false, false, true, false]), (7, vec![true, true, false, false, true, true]), (8, vec![true, true, false, true, false, false, false]), (15, vec![true, true, false, true, true, true, true]), (16, vec![ true, true, true, false, // len: 1 false, // len: 2 false, false, // len: 4 false, false, false, false, ]), // 31 (31, vec![ true, true, true, false, // len: 1 false, // len: 2 false, false, // len: 4 true, true, true, true, ]), // 32 (32, vec![ true, true, true, false, // len: 1 false, // len: 2 false, true, // len: 5 false, false, false, false, false ]), // 2^15 (32768, vec![ true, true, true, false, // len: 1 true, // len: 3 true, true, true, // len: 15 false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, ]), (65535, vec![ true, true, true, false, // len: 1 true, // len: 3 true, true, true, // len: 15 true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, ]), (65536, vec![ true, true, true, true, false, // len: 1 false, // len: 2 false, false, // len: 4 false, false, false, false, // len: 16 false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, false, ]), ]; for (target, vec) in tries { let truncated = vec[0..vec.len() - 1].to_vec(); assert_eq!( decode(truncated.into_iter()), Err(Error::EndOfStream), ); let encode = encode(target); assert_eq!(encode, vec); let decode = decode(vec.into_iter()).unwrap(); assert_eq!(target, decode); } } }
extern crate alloc; use alloc::collections::BTreeMap; use std::{mem, slice}; use uefi::guid::Guid; use uefi::status::{Error, Result}; unsafe fn smm_cmd(cmd: u8, subcmd: u8, arg: u32) -> u32 { let res; asm!( "out 0xB2, $0" : "={eax}"(res) : "{eax}"(((subcmd as u32) << 8) | (cmd as u32)), "{ebx}"(arg) : "memory" : "intel", "volatile" ); res } const CMD_SMMSTORE: u8 = 0xED; unsafe fn smmstore_cmd(subcmd: u8, arg: u32) -> Result<()> { match smm_cmd(CMD_SMMSTORE, subcmd, arg) { 0 => Ok(()), 1 => Err(Error::DeviceError), 2 => Err(Error::Unsupported), _ => Err(Error::Unknown), } } const SMMSTORE_CLEAR: u8 = 1; const SMMSTORE_READ: u8 = 2; const SMMSTORE_APPEND: u8 = 3; unsafe fn smmstore_clear() -> Result<()> { smmstore_cmd(SMMSTORE_CLEAR, 0) } unsafe fn smmstore_read(buf: &mut [u8]) -> Result<()> { #[repr(C)] struct Params { buf: u32, bufsize: u32, } let params = Params { buf: buf.as_mut_ptr() as u32, bufsize: buf.len() as u32 }; smmstore_cmd(SMMSTORE_READ, &params as *const Params as u32) } unsafe fn smmstore_append(key: &[u8], val: &[u8]) -> Result<()> { #[repr(C)] struct Params { key: u32, keysize: u32, val: u32, valsize: u32 } let params = Params { key: key.as_ptr() as u32, keysize: key.len() as u32, val: val.as_ptr() as u32, valsize: val.len() as u32 }; smmstore_cmd(SMMSTORE_APPEND, &params as *const Params as u32) } pub fn smmstore() -> Result<()> { let mut data = [0; 0x40000]; let res = unsafe { smmstore_read(&mut data) }; // println!("Read {:?}", res); res?; let mut compact = BTreeMap::<&[u8], &[u8]>::new(); let mut i = 0; let mut duplicates = 0; while i + 8 <= data.len() { let (keysz, valsz) = unsafe { let ptr = data.as_ptr().add(i) as *const u32; i += 8; (*ptr as usize, *ptr.add(1) as usize) }; // No more entries if keysz == 0 || keysz == 0xffff_ffff { break; } // Data too short if i + keysz + valsz >= data.len() { break; } unsafe { let ptr = data.as_ptr().add(i); let key = slice::from_raw_parts( ptr, keysz ); let value = slice::from_raw_parts( ptr.add(keysz), valsz ); if compact.insert(key, value).is_some() { duplicates += 1; } } i += keysz + valsz + 1; i = (i + 3) & !3; } let rewrite = { i >= data.len() / 2 || duplicates >= 16 }; if rewrite { let res = unsafe { smmstore_clear() }; // println!("Clear {:?}", res); res?; for (key, value) in compact.iter() { if key.len() > mem::size_of::<Guid>() && value.len() > 0 { let res = unsafe { smmstore_append(&key, &value) }; // println!("Append {:?}", res); res?; } } } Ok(()) }
use smithay::{ delegate_presentation, delegate_xdg_decoration, delegate_xdg_shell, desktop::{PopupKind, Space, Window}, input::{ pointer::{Focus, GrabStartData as PointerGrabStartData}, Seat, }, reexports::{ wayland_protocols::xdg::shell::server::xdg_toplevel::{self}, wayland_server::{ protocol::{wl_seat, wl_surface::WlSurface}, Resource, }, }, utils::{Rectangle, Serial}, wayland::{ compositor::with_states, shell::xdg::{ decoration::XdgDecorationHandler, PopupSurface, PositionerState, ToplevelSurface, XdgShellHandler, XdgShellState, XdgToplevelSurfaceData, }, }, }; use smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1::Mode; use crate::{ grabs::{MoveSurfaceGrab, ResizeSurfaceGrab}, state::Backend, Corrosion, }; impl<BackendData: Backend> XdgShellHandler for Corrosion<BackendData> { fn xdg_shell_state(&mut self) -> &mut XdgShellState { &mut self.xdg_shell_state } fn new_toplevel(&mut self, surface: ToplevelSurface) { let window = Window::new(surface); window.toplevel().with_pending_state(|state| { state.states.set(xdg_toplevel::State::TiledLeft); state.states.set(xdg_toplevel::State::TiledBottom); state.states.set(xdg_toplevel::State::TiledRight); state.states.set(xdg_toplevel::State::TiledTop); }); window.toplevel().send_configure(); self.space.map_element(window, (0, 0), false); } fn new_popup(&mut self, surface: PopupSurface, _positioner: PositionerState) { if let Err(err) = self.popup_manager.track_popup(PopupKind::from(surface)) { tracing::error!("Failed to track popup: {}", err); } } fn move_request(&mut self, surface: ToplevelSurface, seat: wl_seat::WlSeat, serial: Serial) { let seat = Seat::from_resource(&seat).unwrap(); let wl_surface = surface.wl_surface(); if let Some(start_data) = check_grab(&seat, wl_surface, serial) { let pointer = seat.get_pointer().unwrap(); let window = self .space .elements() .find(|w| w.toplevel().wl_surface() == wl_surface) .unwrap() .clone(); let initial_window_location = self.space.element_location(&window).unwrap(); let grab = MoveSurfaceGrab { start_data, window, initial_window_location, }; pointer.set_grab(self, grab, serial, Focus::Clear); tracing::debug!("move_request: {:?}", serial); } } fn resize_request( &mut self, surface: ToplevelSurface, seat: wl_seat::WlSeat, serial: Serial, edges: xdg_toplevel::ResizeEdge, ) { let seat = Seat::from_resource(&seat).unwrap(); let wl_surface = surface.wl_surface(); if let Some(start_data) = check_grab(&seat, wl_surface, serial) { let pointer = seat.get_pointer().unwrap(); let window = self .space .elements() .find(|w| w.toplevel().wl_surface() == wl_surface) .unwrap() .clone(); let initial_window_location = self.space.element_location(&window).unwrap(); let initial_window_size = window.geometry().size; surface.with_pending_state(|state| { state.states.set(xdg_toplevel::State::Resizing); }); surface.send_configure(); let grab = ResizeSurfaceGrab::start( start_data, window, edges.into(), Rectangle::from_loc_and_size(initial_window_location, initial_window_size), ); pointer.set_grab(self, grab, serial, Focus::Clear); tracing::debug!("resize_request: {:?}", serial); } } fn grab(&mut self, _surface: PopupSurface, _seat: wl_seat::WlSeat, _serial: Serial) { // TODO popup grabs } } // xdg decoration impl<BackendData: Backend> XdgDecorationHandler for Corrosion<BackendData> { fn new_decoration(&mut self, toplevel: ToplevelSurface) { toplevel.with_pending_state(|state| { // Advertise server side decoration state.decoration_mode = Some(Mode::ServerSide); }); toplevel.send_configure(); } fn request_mode(&mut self, _toplevel: ToplevelSurface, _mode: Mode) { /* ... */ } fn unset_mode(&mut self, _toplevel: ToplevelSurface) { /* ... */ } } // Xdg Shell delegate_xdg_shell!(@<BackendData: Backend + 'static> Corrosion<BackendData>); // Xdg Decoration delegate_xdg_decoration!(@<BackendData: Backend + 'static> Corrosion<BackendData>); // Presentation delegate_presentation!(@<BackendData: Backend + 'static> Corrosion<BackendData>); fn check_grab<BackendData: Backend + 'static>( seat: &Seat<Corrosion<BackendData>>, surface: &WlSurface, serial: Serial, ) -> Option<PointerGrabStartData<Corrosion<BackendData>>> { let pointer = seat.get_pointer()?; // Check that this surface has a click grab. if !pointer.has_grab(serial) { return None; } let start_data = pointer.grab_start_data()?; let (focus, _) = start_data.focus.as_ref()?; // If the focus was for a different surface, ignore the request. if !focus.id().same_client_as(&surface.id()) { return None; } // if you see this thank you for reading our shitty code // also i am sorry for the shitty code Some(start_data) } /// Should be called on `WlSurface::commit` pub fn handle_commit(space: &Space<Window>, surface: &WlSurface) -> Option<()> { let window = space .elements() .find(|w| w.toplevel().wl_surface() == surface) .cloned()?; let initial_configure_sent = with_states(surface, |states| { states .data_map .get::<XdgToplevelSurfaceData>() .unwrap() .lock() .unwrap() .initial_configure_sent }); if !initial_configure_sent { window.toplevel().send_configure(); } Some(()) }
use crate::{DocBase, VarType}; pub fn gen_doc() -> Vec<DocBase> { vec![DocBase { var_type: VarType::Variable, name: "open", signatures: vec![], description: "Current open price.", example: "", returns: "", arguments: "", remarks: "Previous values may be accessed with square brackets operator [], e.g. `open[1]`, `open[2]`.", links: "", }] }
use crate::r#macro; use super::{parser, semantics, LispErr, Pos}; use alloc::{ boxed::Box, collections::{btree_map::BTreeMap, linked_list::LinkedList, vec_deque::VecDeque}, format, string::{String, ToString}, vec, vec::Vec, }; use core::{ cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, ops::{Shl, Shr}, pin::Pin, ptr::{read_volatile, write_volatile}, }; use num_bigint::BigInt; use num_traits::{ToPrimitive, Zero}; type Expr = semantics::LangExpr; type Pattern = semantics::Pattern; struct RuntimeErr { msg: String, pos: Pos, } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct Variables { vars: VecDeque<BTreeMap<String, RTData>>, } impl Variables { fn new() -> Variables { let mut list = VecDeque::new(); list.push_back(BTreeMap::new()); Variables { vars: list } } fn push(&mut self) { self.vars.push_back(BTreeMap::new()); } fn pop(&mut self) { self.vars.pop_back(); } fn insert(&mut self, id: String, data: RTData) { let m = self.vars.back_mut().unwrap(); m.insert(id, data); } fn get(&mut self, id: &str) -> Option<&RTData> { for m in self.vars.iter().rev() { if let Some(val) = m.get(id) { return Some(val); } } None } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum TCall { Defun(String), Lambda(u64), } #[derive(Eq, Debug, Clone)] pub struct IntType(*mut (BigInt, bool)); impl IntType { fn get_int(&self) -> &BigInt { unsafe { &(*self.0).0 } } fn get_ref(&mut self) -> &mut bool { unsafe { &mut (*self.0).1 } } } impl Ord for IntType { fn cmp(&self, other: &Self) -> Ordering { let s1 = self.get_int(); let s2 = other.get_int(); s1.cmp(s2) } } impl PartialOrd for IntType { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let s1 = self.get_int(); let s2 = other.get_int(); Some(s1.cmp(s2)) } } impl PartialEq for IntType { fn eq(&self, other: &Self) -> bool { let s1 = self.get_int(); let s2 = other.get_int(); s1 == s2 } } #[derive(Eq, Debug, Clone)] pub struct StrType(*mut (String, bool)); impl StrType { fn get_string(&self) -> &String { unsafe { &(*self.0).0 } } fn get_ref(&mut self) -> &mut bool { unsafe { &mut (*self.0).1 } } } impl Ord for StrType { fn cmp(&self, other: &Self) -> Ordering { let s1 = self.get_string(); let s2 = other.get_string(); s1.cmp(s2) } } impl PartialOrd for StrType { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let s1 = self.get_string(); let s2 = other.get_string(); Some(s1.cmp(s2)) } } impl PartialEq for StrType { fn eq(&self, other: &Self) -> bool { let s1 = self.get_string(); let s2 = other.get_string(); s1 == s2 } } #[derive(Eq, Debug, Clone)] pub struct ClojureType(*mut (Clojure, bool)); impl ClojureType { fn get_clojure(&self) -> &Clojure { unsafe { &(*self.0).0 } } fn get_clojure_mut(&mut self) -> &mut Clojure { unsafe { &mut (*self.0).0 } } fn get_ref(&mut self) -> &mut bool { unsafe { &mut (*self.0).1 } } } impl Ord for ClojureType { fn cmp(&self, other: &Self) -> Ordering { let s1 = self.get_clojure(); let s2 = other.get_clojure(); s1.cmp(s2) } } impl PartialOrd for ClojureType { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let s1 = self.get_clojure(); let s2 = other.get_clojure(); Some(s1.cmp(s2)) } } impl PartialEq for ClojureType { fn eq(&self, other: &Self) -> bool { let s1 = self.get_clojure(); let s2 = other.get_clojure(); s1 == s2 } } #[derive(Eq, Debug, Clone)] pub struct LDataType(*mut (LabeledData, bool)); impl LDataType { fn get_ldata(&self) -> &LabeledData { unsafe { &(*self.0).0 } } fn get_ldata_mut(&mut self) -> &mut LabeledData { unsafe { &mut (*self.0).0 } } fn get_ref(&mut self) -> &mut bool { unsafe { &mut (*self.0).1 } } } impl Ord for LDataType { fn cmp(&self, other: &Self) -> Ordering { let s1 = self.get_ldata(); let s2 = other.get_ldata(); s1.cmp(s2) } } impl PartialOrd for LDataType { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { let s1 = self.get_ldata(); let s2 = other.get_ldata(); Some(s1.cmp(s2)) } } impl PartialEq for LDataType { fn eq(&self, other: &Self) -> bool { let s1 = self.get_ldata(); let s2 = other.get_ldata(); s1 == s2 } } #[derive(Debug, Clone, Ord, PartialOrd, PartialEq, Eq)] pub enum RTData { Str(StrType), Char(char), Int(IntType), Bool(bool), Defun(String), Lambda(ClojureType), LData(LDataType), TailCall(TCall, Variables), } fn escape_char(c: char) -> String { match c { '\n' => "\\n".to_string(), '\r' => "\\r".to_string(), '\t' => "\\t".to_string(), '\0' => "\\0".to_string(), _ => c.to_string(), } } impl RTData { fn get_in_lisp(&self, list_head: bool) -> String { match self { RTData::Str(n) => { let mut str = "\"".to_string(); for s in n.get_string().chars() { if s == '"' { str.push_str("\\\""); } else { str.push_str(&escape_char(s)); } } str.push('"'); str } RTData::Char(c) => { if *c == '`' { "`\\``".to_string() } else { let s = escape_char(*c); format!("`{}`", s) } } RTData::Int(n) => { format!("{}", n.get_int()) } RTData::Bool(n) => n.to_string(), RTData::Defun(n) => n.to_string(), RTData::Lambda(n) => format!("(Lambda {})", n.get_clojure().ident), RTData::LData(n) => { let label = &n.get_ldata().label; if label == "Cons" { let e1; let e2; match n.get_ldata().data.as_ref() { Some(ld) => { e1 = ld[0].get_in_lisp(true); e2 = ld[1].get_in_lisp(false); } None => panic!("invalid list"), } if list_head { if e2.is_empty() { format!("'({})", e1) } else { format!("'({} {})", e1, e2) } } else if e2.is_empty() { e1 } else { format!("{} {}", e1, e2) } } else if label == "Nil" { if list_head { "'()".to_string() } else { "".to_string() } } else if label == "Tuple" { match n.get_ldata().data.as_ref() { Some(ld) => { let mut msg = "".to_string(); let len = (*ld).len(); let mut i = 1; for d in ld.iter() { if i == len { msg = format!("{}{}", msg, d.get_in_lisp(true)); } else { msg = format!("{}{} ", msg, d.get_in_lisp(true)); } i += 1; } format!("[{}]", msg) } None => "[]".to_string(), } } else { match n.get_ldata().data.as_ref() { Some(ld) => { let mut msg = format!("({}", label); for d in ld.iter() { msg = format!("{} {}", msg, d.get_in_lisp(true)); } format!("{})", msg) } None => label.to_string(), } } } RTData::TailCall(TCall::Defun(f), _) => format!("(TailCall (Defun {}))", f), RTData::TailCall(TCall::Lambda(f), _) => format!("(TailCall (Lambda {}))", f), } } } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct LabeledData { label: String, data: Option<Vec<RTData>>, } #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] struct Clojure { ident: u64, data: Option<BTreeMap<String, RTData>>, } const MIN_GC_NUM: usize = 1024; #[derive(Debug)] pub(crate) struct RootObject { objects: LinkedList<Pin<Box<(LabeledData, bool)>>>, clojure: LinkedList<Pin<Box<(Clojure, bool)>>>, integers: LinkedList<Pin<Box<(BigInt, bool)>>>, strings: LinkedList<Pin<Box<(String, bool)>>>, threshold: usize, } impl RootObject { fn new() -> RootObject { RootObject { objects: LinkedList::new(), clojure: LinkedList::new(), integers: LinkedList::new(), strings: LinkedList::new(), threshold: MIN_GC_NUM, } } fn len(&self) -> usize { self.objects.len() + self.clojure.len() + self.integers.len() + self.strings.len() } fn make_int(&mut self, n: BigInt) -> IntType { self.integers.push_back(Box::pin((n, false))); let ptr = self.integers.back_mut().unwrap(); IntType(unsafe { ptr.as_mut().get_unchecked_mut() as *mut (BigInt, bool) }) } fn make_str(&mut self, str: String) -> StrType { self.strings.push_back(Box::pin((str, false))); let ptr = self.strings.back_mut().unwrap(); StrType(unsafe { ptr.as_mut().get_unchecked_mut() as *mut (String, bool) }) } fn make_obj(&mut self, label: String, data: Option<Vec<RTData>>) -> LDataType { let obj = LabeledData { label, data }; self.objects.push_back(Box::pin((obj, false))); let ptr = self.objects.back_mut().unwrap(); LDataType(unsafe { ptr.as_mut().get_unchecked_mut() as *mut (LabeledData, bool) }) } fn make_clojure(&mut self, ident: u64, data: Option<BTreeMap<String, RTData>>) -> ClojureType { let obj = Clojure { ident, data }; self.clojure.push_back(Box::pin((obj, false))); let ptr = self.clojure.back_mut().unwrap(); ClojureType(unsafe { ptr.as_mut().get_unchecked_mut() as *mut (Clojure, bool) }) } } pub struct Environment<'a> { pub(crate) ctx: &'a semantics::Context, pub(crate) lambda: &'a BTreeMap<u64, semantics::Lambda>, pub(crate) root: &'a mut RootObject, pub(crate) vars: &'a mut VecDeque<Variables>, } pub(crate) fn eval( code: &str, ctx: &semantics::Context, ) -> Result<LinkedList<Result<String, String>>, LispErr> { let mut ps = parser::Parser::new(code, crate::FileType::Eval); let mut exprs: LinkedList<parser::Expr> = match ps.parse() { Ok(e) => e, Err(e) => { let msg = format!("Syntax Error: {}", e.msg); return Err(LispErr { msg, pos: e.pos }); } }; if let Err(e) = r#macro::process_macros(&mut exprs) { let msg = format!("Macro Error: {}", e.msg); return Err(LispErr::new(msg, e.pos)); } for expr in exprs.iter_mut() { if let Err(e) = r#macro::apply(expr, &ctx.macros) { let msg: String = format!("Macro Error: {}", e.msg); return Err(LispErr { msg, pos: e.pos }); } } let mut typed_exprs = LinkedList::new(); for expr in &exprs { match semantics::typing_expr(expr, ctx) { Ok(e) => { typed_exprs.push_back(e); } Err(e) => { let msg = format!("Typing Error: {}", e.msg); return Err(LispErr { msg, pos: e.pos }); } } } let mut root = RootObject::new(); let mut result = LinkedList::new(); for (expr, lambda) in &typed_exprs { let mut vars = VecDeque::new(); vars.push_back(Variables::new()); let mut env = Environment { ctx, lambda, root: &mut root, vars: &mut vars, }; match eval_expr(expr, &mut env) { Ok(val) => { result.push_back(Ok(val.get_in_lisp(true))); } Err(e) => { let msg = format!( "(RuntimeErr [{} (Pos {} {})])", e.msg, e.pos.line, e.pos.column ); result.push_back(Err(msg)); return Ok(result); } } } Ok(result) } fn get_data_of_id(id: &str, vars: &mut VecDeque<Variables>) -> RTData { match vars.back_mut().unwrap().get(id) { Some(data) => data.clone(), None => RTData::Defun(id.to_string()), } } fn eval_expr(expr: &Expr, env: &mut Environment<'_>) -> Result<RTData, RuntimeErr> { match expr { Expr::LitStr(e) => Ok(RTData::Str(env.root.make_str(e.str.clone()))), Expr::LitNum(e) => Ok(RTData::Int(env.root.make_int(e.num.clone()))), Expr::LitChar(e) => Ok(RTData::Char(e.c)), Expr::LitBool(e) => Ok(RTData::Bool(e.val)), Expr::IfExpr(e) => eval_if(e, env), Expr::DataExpr(e) => eval_data(e, env), Expr::ListExpr(e) => eval_list(e, env), Expr::LetExpr(e) => eval_let(e, env), Expr::MatchExpr(e) => eval_match(e, env), Expr::IDExpr(e) => Ok(eval_id(e, env.vars)), Expr::ApplyExpr(e) => eval_apply(e, env), Expr::TupleExpr(e) => eval_tuple(e, env), Expr::LambdaExpr(e) => Ok(eval_lambda(e, env)), } } fn eval_lambda(expr: &semantics::Lambda, env: &mut Environment<'_>) -> RTData { let data = if !expr.vars.is_empty() { let mut m = BTreeMap::new(); for v in &expr.vars { m.insert(v.to_string(), get_data_of_id(v, env.vars)); } Some(m) } else { None }; let ptr = env.root.make_clojure(expr.ident, data); RTData::Lambda(ptr) } fn eval_tuple(expr: &semantics::Exprs, env: &mut Environment<'_>) -> Result<RTData, RuntimeErr> { let mut v = Vec::new(); for e in expr.exprs.iter() { v.push(eval_expr(e, env)?); } let ptr = env.root.make_obj("Tuple".to_string(), Some(v)); Ok(RTData::LData(ptr)) } fn get_fun<'a>( ctx: &'a semantics::Context, fun_name: &str, expr: &Expr, ) -> Result<&'a semantics::Defun, RuntimeErr> { let fun = match ctx.funs.get(fun_name) { Some(f) => f, None => { let pos = expr.get_pos(); let msg = format!("{} is not defined", fun_name); return Err(RuntimeErr { msg, pos }); } }; Ok(fun) } fn get_lambda<'a>( ctx: &'a semantics::Context, lambda: &'a BTreeMap<u64, semantics::Lambda>, id: u64, expr: &Expr, ) -> Result<&'a semantics::Lambda, RuntimeErr> { let fun; match ctx.lambda.get(&id) { Some(f) => { fun = f; } None => match lambda.get(&id) { Some(f) => { fun = f; } None => { let pos = expr.get_pos(); let msg = format!("could not find (Lambda {})", id); return Err(RuntimeErr { msg, pos }); } }, } Ok(fun) } fn call_lambda( expr: &semantics::Apply, env: &mut Environment<'_>, cloj: &Clojure, iter: core::slice::Iter<semantics::LangExpr>, fun_expr: &semantics::LangExpr, ) -> Result<RTData, RuntimeErr> { // look up lambda let ident = cloj.ident; let fun = get_lambda(env.ctx, env.lambda, ident, fun_expr)?; // set up arguments let mut vars_fun = Variables::new(); for (e, arg) in iter.zip(fun.args.iter()) { let data = eval_expr(e, env)?; vars_fun.insert(arg.id.to_string(), data); } // set up free variables match &cloj.data { Some(d) => { for (key, val) in d { vars_fun.insert(key.to_string(), val.clone()); } } None => (), } // tail call optimization if expr.is_tail { Ok(RTData::TailCall(TCall::Lambda(ident), vars_fun)) } else { env.vars.push_back(vars_fun); let result = eval_tail_call(&fun.expr, env); env.vars.pop_back(); result } } fn eval_apply(expr: &semantics::Apply, env: &mut Environment<'_>) -> Result<RTData, RuntimeErr> { let mut iter = expr.exprs.iter(); let fun_expr = match iter.next() { Some(e) => e, None => { let pos = expr.pos; return Err(RuntimeErr { msg: "empty application".to_string(), pos, }); } }; match eval_expr(fun_expr, env)? { RTData::Defun(fun_name) => { // call built-in function if env.ctx.built_in.contains(&fun_name) { let mut v = Vec::new(); for e in iter { let data = eval_expr(e, env)?; v.push(data); } return eval_built_in(fun_name, &v, expr.pos, env); } if let Some(ffi) = env.ctx.ext_ffi.get(fun_name.as_str()) { let mut v = Vec::new(); for e in iter { let data = eval_expr(e, env)?; v.push(data); } return Ok(ffi(env, &v)); } // look up defun if let Ok(fun) = get_fun(env.ctx, &fun_name, fun_expr) { // set up arguments let mut vars_fun = Variables::new(); for (e, arg) in iter.zip(fun.args.iter()) { let data = eval_expr(e, env)?; vars_fun.insert(arg.id.to_string(), data); } // tail call optimization if expr.is_tail { Ok(RTData::TailCall(TCall::Defun(fun_name), vars_fun)) } else { env.vars.push_back(vars_fun); let result = eval_tail_call(&fun.expr, env)?; env.vars.pop_back(); Ok(result) } } else { // call clojure if let Some(RTData::Lambda(cloj)) = env.vars.back_mut().unwrap().get(&fun_name) { let c = cloj.clone(); return call_lambda(expr, env, c.get_clojure(), iter, fun_expr); } // could not find such function let pos = fun_expr.get_pos(); let msg = format!("{} is not defined", fun_name); Err(RuntimeErr { msg, pos }) } } RTData::Lambda(f) => { let f = f.get_clojure(); call_lambda(expr, env, f, iter, fun_expr) } _ => { let pos = fun_expr.get_pos(); Err(RuntimeErr { msg: "not function".to_string(), pos, }) } } } fn eval_tail_call<'a>( mut expr: &'a Expr, env: &'a mut Environment<'_>, ) -> Result<RTData, RuntimeErr> { loop { match eval_expr(expr, env)? { RTData::TailCall(TCall::Defun(fun_name), vars_fun) => { let fun = get_fun(env.ctx, &fun_name, expr)?; expr = &fun.expr; env.vars.pop_back(); env.vars.push_back(vars_fun); collect_garbage(env.vars, env.root); // mark and sweep } RTData::TailCall(TCall::Lambda(id), vars_fun) => { let fun = get_lambda(env.ctx, env.lambda, id, expr)?; expr = &fun.expr; env.vars.pop_back(); env.vars.push_back(vars_fun); collect_garbage(env.vars, env.root); // mark and sweep } x => { return Ok(x); } } } } fn get_int(args: &[RTData], pos: Pos) -> Result<*const BigInt, RuntimeErr> { match &args[0] { RTData::Int(n) => Ok(n.get_int()), _ => Err(RuntimeErr { msg: "there must be exactly 2 integers".to_string(), pos, }), } } fn get_int_int(args: &[RTData], pos: Pos) -> Result<(*const BigInt, *const BigInt), RuntimeErr> { match (&args[0], &args[1]) { (RTData::Int(n1), RTData::Int(n2)) => Ok((n1.get_int(), n2.get_int())), _ => Err(RuntimeErr { msg: "there must be exactly 2 integers".to_string(), pos, }), } } fn get_int_int_int( args: &[RTData], pos: Pos, ) -> Result<(*const BigInt, *const BigInt, *const BigInt), RuntimeErr> { match (&args[0], &args[1], &args[2]) { (RTData::Int(n1), RTData::Int(n2), RTData::Int(n3)) => { Ok((n1.get_int(), n2.get_int(), n3.get_int())) } _ => Err(RuntimeErr { msg: "there must be exactly 3 integers".to_string(), pos, }), } } fn get_bool_bool(args: &[RTData], pos: Pos) -> Result<(bool, bool), RuntimeErr> { match (args[0].clone(), args[1].clone()) { (RTData::Bool(n1), RTData::Bool(n2)) => Ok((n1, n2)), _ => Err(RuntimeErr { msg: "there must be exactly 2 boolean values".to_string(), pos, }), } } fn get_bool(args: &[RTData], pos: Pos) -> Result<bool, RuntimeErr> { match args[0].clone() { RTData::Bool(n) => Ok(n), _ => Err(RuntimeErr { msg: "there must be exactly 1 boolean value".to_string(), pos, }), } } fn eval_built_in( fun_name: String, args: &[RTData], pos: Pos, env: &mut Environment<'_>, ) -> Result<RTData, RuntimeErr> { match fun_name.as_str() { "+" => { let (n1, n2) = get_int_int(args, pos)?; let n = unsafe { &*n1 + &*n2 }; Ok(RTData::Int(env.root.make_int(n))) } "-" => { let (n1, n2) = get_int_int(args, pos)?; let n = unsafe { &*n1 - &*n2 }; Ok(RTData::Int(env.root.make_int(n))) } "*" => { let (n1, n2) = get_int_int(args, pos)?; let n = unsafe { &*n1 * &*n2 }; Ok(RTData::Int(env.root.make_int(n))) } "/" => { let (n1, n2) = get_int_int(args, pos)?; let n = unsafe { &*n1 / &*n2 }; Ok(RTData::Int(env.root.make_int(n))) } "%" => { let (n1, n2) = get_int_int(args, pos)?; let n = unsafe { &*n1 % &*n2 }; Ok(RTData::Int(env.root.make_int(n))) } "=" | "eq" => Ok(RTData::Bool(args[0] == args[1])), "!=" | "neq" => Ok(RTData::Bool(args[0] != args[1])), "<=" | "leq" => Ok(RTData::Bool(args[0] <= args[1])), ">=" | "geq" => Ok(RTData::Bool(args[0] >= args[1])), ">" | "gt" => Ok(RTData::Bool(args[0] > args[1])), "<" | "lt" => Ok(RTData::Bool(args[0] < args[1])), "and" => { let (n1, n2) = get_bool_bool(args, pos)?; Ok(RTData::Bool(n1 && n2)) } "or" => { let (n1, n2) = get_bool_bool(args, pos)?; Ok(RTData::Bool(n1 || n2)) } "xor" => { let (n1, n2) = get_bool_bool(args, pos)?; Ok(RTData::Bool(n1 ^ n2)) } "not" => { let n = get_bool(args, pos)?; Ok(RTData::Bool(!n)) } "band" => { let (n1, n2) = get_int_int(args, pos)?; let n = unsafe { &*n1 & &*n2 }; Ok(RTData::Int(env.root.make_int(n))) } "bor" => { let (n1, n2) = get_int_int(args, pos)?; let n = unsafe { &*n1 | &*n2 }; Ok(RTData::Int(env.root.make_int(n))) } "bxor" => { let (n1, n2) = get_int_int(args, pos)?; let n = unsafe { &*n1 ^ &*n2 }; Ok(RTData::Int(env.root.make_int(n))) } "sqrt" => { let n = get_int(args, pos)?; if unsafe { (*n) >= Zero::zero() } { let n = unsafe { (*n).sqrt() }; let n = RTData::Int(env.root.make_int(n)); let ptr = env.root.make_obj("Some".to_string(), Some(vec![n])); Ok(RTData::LData(ptr)) } else { let ptr = env.root.make_obj("None".to_string(), None); Ok(RTData::LData(ptr)) } } "pow" => { let (n1, n2) = get_int_int(args, pos)?; if let Some(e) = unsafe { (*n2).to_u32() } { let n = unsafe { (*n1).pow(e) }; let n = RTData::Int(env.root.make_int(n)); let ptr = env.root.make_obj("Some".to_string(), Some(vec![n])); Ok(RTData::LData(ptr)) } else { let ptr = env.root.make_obj("None".to_string(), None); Ok(RTData::LData(ptr)) } } ">>" => { let (n1, n2) = get_int_int(args, pos)?; if let Some(e) = unsafe { (*n2).to_u64() } { let n = unsafe { (*n1).clone() }; let n = n.shr(e); let n = RTData::Int(env.root.make_int(n)); let ptr = env.root.make_obj("Some".to_string(), Some(vec![n])); Ok(RTData::LData(ptr)) } else { let ptr = env.root.make_obj("None".to_string(), None); Ok(RTData::LData(ptr)) } } "<<" => { let (n1, n2) = get_int_int(args, pos)?; if let Some(e) = unsafe { (*n2).to_u64() } { let n = unsafe { (*n1).clone() }; let n = n.shl(e); let n = RTData::Int(env.root.make_int(n)); let ptr = env.root.make_obj("Some".to_string(), Some(vec![n])); Ok(RTData::LData(ptr)) } else { let ptr = env.root.make_obj("None".to_string(), None); Ok(RTData::LData(ptr)) } } "chars" => { let mut tail = RTData::LData(env.root.make_obj("Nil".to_string(), None)); if let RTData::Str(st) = &args[0] { let s = st.get_string(); for c in s.chars().rev() { let c = RTData::Char(c); let cons = RTData::LData(env.root.make_obj("Cons".to_string(), Some(vec![c, tail]))); tail = cons; } } Ok(tail) } "str" => { let mut head = &args[0]; let mut s = "".to_string(); loop { if let RTData::LData(data) = head { if data.get_ldata().label == "Cons" { if let Some(d) = &data.get_ldata().data { if let RTData::Char(c) = &d[0] { s.push(*c); head = &d[1]; } else { return Err(RuntimeErr { msg: "not char".to_string(), pos, }); } } else { return Err(RuntimeErr { msg: "invalid cons".to_string(), pos, }); } } else if data.get_ldata().label == "Nil" { break; } else { return Err(RuntimeErr { msg: "not list".to_string(), pos, }); } } } let ptr = env.root.make_str(s); Ok(RTData::Str(ptr)) } "call-rust" => { let (n1, n2, n3) = get_int_int_int(args, pos)?; let n = unsafe { (env.ctx.callback)(&*n1, &*n2, &*n3) }; if let Some(n) = n { let n = RTData::Int(env.root.make_int(n)); let ptr = env.root.make_obj("Some".to_string(), Some(vec![n])); Ok(RTData::LData(ptr)) } else { let ptr = env.root.make_obj("None".to_string(), None); Ok(RTData::LData(ptr)) } } _ => Err(RuntimeErr { msg: "unknown built-in function".to_string(), pos, }), } } fn eval_match( expr: &semantics::MatchNode, env: &mut Environment<'_>, ) -> Result<RTData, RuntimeErr> { let data = eval_expr(&expr.expr, env)?; for c in &expr.cases { env.vars.back_mut().unwrap().push(); if eval_pat(&c.pattern, data.clone(), env.vars) { let retval = eval_expr(&c.expr, env)?; env.vars.back_mut().unwrap().pop(); return Ok(retval); } env.vars.back_mut().unwrap().pop(); } let pos = expr.pos; Err(RuntimeErr { msg: "pattern-matching is not exhaustive".to_string(), pos, }) } fn eval_id(expr: &semantics::IDNode, vars: &mut VecDeque<Variables>) -> RTData { let id = expr.id.to_string(); get_data_of_id(&id, vars) } fn eval_list(expr: &semantics::Exprs, env: &mut Environment<'_>) -> Result<RTData, RuntimeErr> { let mut elm = env.root.make_obj("Nil".to_string(), None); for e in expr.exprs.iter().rev() { let val = eval_expr(e, env)?; elm = env .root .make_obj("Cons".to_string(), Some(vec![val, RTData::LData(elm)])); } Ok(RTData::LData(elm)) } fn eval_if(expr: &semantics::IfNode, env: &mut Environment<'_>) -> Result<RTData, RuntimeErr> { let cond = eval_expr(&expr.cond_expr, env)?; let flag = match cond { RTData::Bool(e) => e, _ => { let pos = expr.cond_expr.get_pos(); return Err(RuntimeErr { msg: "type mismatched".to_string(), pos, }); } }; if flag { eval_expr(&expr.then_expr, env) } else { eval_expr(&expr.else_expr, env) } } fn eval_data(expr: &semantics::DataNode, env: &mut Environment<'_>) -> Result<RTData, RuntimeErr> { let data = if expr.exprs.is_empty() { None } else { let mut v = Vec::new(); for e in &expr.exprs { v.push(eval_expr(e, env)?); } Some(v) }; let ptr = env.root.make_obj(expr.label.id.to_string(), data); Ok(RTData::LData(ptr)) } fn eval_let(expr: &semantics::LetNode, env: &mut Environment<'_>) -> Result<RTData, RuntimeErr> { env.vars.back_mut().unwrap().push(); for def in &expr.def_vars { let data = eval_expr(&def.expr, env)?; if !eval_pat(&def.pattern, data, env.vars) { let pos = def.pattern.get_pos(); return Err(RuntimeErr { msg: "failed pattern matching".to_string(), pos, }); } } let result = eval_expr(&expr.expr, env)?; env.vars.back_mut().unwrap().pop(); Ok(result) } fn eval_pat(pat: &Pattern, data: RTData, vars: &mut VecDeque<Variables>) -> bool { match pat { Pattern::PatID(p) => { vars.back_mut().unwrap().insert(p.id.to_string(), data); true } Pattern::PatStr(p) => match data { RTData::Str(n) => n.get_string() == &p.str, _ => false, }, Pattern::PatChar(p) => match data { RTData::Char(n) => n == p.c, _ => false, }, Pattern::PatNum(p) => match data { RTData::Int(n) => n.get_int() == &p.num, _ => false, }, Pattern::PatBool(p) => match data { RTData::Bool(n) => n == p.val, _ => false, }, Pattern::PatNil(_) => match data { RTData::LData(ptr) => ptr.get_ldata().label == "Nil", _ => false, }, Pattern::PatTuple(p) => match data { RTData::LData(ptr) => { if ptr.get_ldata().label != "Tuple" { return false; } match &ptr.get_ldata().data { Some(rds) => { for (pat2, rd) in p.pattern.iter().zip(rds.iter()) { if !eval_pat(pat2, rd.clone(), vars) { return false; } } true } None => true, } } _ => false, }, Pattern::PatData(p) => match data { RTData::LData(ptr) => { if ptr.get_ldata().label != p.label.id { return false; } match &ptr.get_ldata().data { Some(rds) => { for (pat2, rd) in p.pattern.iter().zip(rds.iter()) { if !eval_pat(pat2, rd.clone(), vars) { return false; } } true } None => true, } } _ => false, }, } } /// do garbage collection fn collect_garbage(vars: &mut VecDeque<Variables>, root: &mut RootObject) { let n = root.len(); if n < root.threshold { return; } mark(vars); sweep(&mut root.clojure); sweep(&mut root.objects); sweep(&mut root.integers); sweep(&mut root.strings); let n = root.len(); root.threshold = n * 2; if root.threshold < (MIN_GC_NUM >> 1) { root.threshold = MIN_GC_NUM; } } /// mark reachable objects fn mark(vars: &mut VecDeque<Variables>) { for v in vars.iter_mut() { for var in v.vars.iter_mut() { for (_, v) in var.iter_mut() { mark_obj(v); } } } } /// mark reachable objects recursively fn mark_obj(data: &mut RTData) { match data { RTData::Str(ptr) => unsafe { write_volatile(ptr.get_ref(), true); }, RTData::Int(ptr) => unsafe { write_volatile(ptr.get_ref(), true); }, RTData::Lambda(ptr) => unsafe { if !read_volatile(ptr.get_ref()) { write_volatile(ptr.get_ref(), true); if let Some(data) = &mut ptr.get_clojure_mut().data { for (_, v) in data.iter_mut() { mark_obj(v); } } } }, RTData::LData(ptr) => unsafe { if !read_volatile(ptr.get_ref()) { write_volatile(ptr.get_ref(), true); if let Some(data) = &mut ptr.get_ldata_mut().data { for v in data.iter_mut() { mark_obj(v); } } } }, _ => (), } } /// remove unreachable objects fn sweep<T>(root: &mut LinkedList<Pin<Box<(T, bool)>>>) { let mut tail = root.split_off(0); loop { if tail.is_empty() { break; } // take head let mut head; if tail.len() == 1 { head = tail.split_off(0); } else { let tmp = tail.split_off(1); head = tail; tail = tmp; }; // check the head is reachable or not let h = head.front_mut().unwrap(); let marked = unsafe { read_volatile(&h.as_ref().1) }; let flag = if marked { // the head is reachable let h = h.as_mut(); unsafe { h.get_unchecked_mut().1 = false; } true } else { // the head unreachable false }; // if reachable, append the head if flag { root.append(&mut head); } } } pub trait RTDataToRust<T> { fn into(&self) -> T; } /// Get a BigInt value. impl RTDataToRust<BigInt> for RTData { fn into(&self) -> BigInt { if let RTData::Int(data) = self { data.get_int().clone() } else { panic!("data is not BigInt"); } } } /// Get a char value. impl RTDataToRust<char> for RTData { fn into(&self) -> char { if let RTData::Char(data) = self { *data } else { panic!("data is not Char"); } } } /// Get a String value. impl RTDataToRust<String> for RTData { fn into(&self) -> String { if let RTData::Str(data) = self { data.get_string().clone() } else { panic!("data is not String"); } } } /// Get a boolean value. impl RTDataToRust<bool> for RTData { fn into(&self) -> bool { if let RTData::Bool(data) = self { *data } else { panic!("data is not Bool"); } } } /// Convert a BLisp's List to a Rust's Vec. impl<T> RTDataToRust<Vec<T>> for RTData where RTData: RTDataToRust<T>, { fn into(&self) -> Vec<T> { if let RTData::LData(data) = self { let ldata = data.get_ldata(); let mut result = Vec::new(); list_to_vec(ldata, &mut result); return result; } panic!("data is not List"); } } /// Convert a BLisp's Option to a Rust's Option. impl<T> RTDataToRust<Option<T>> for RTData where RTData: RTDataToRust<T>, { fn into(&self) -> Option<T> { if let RTData::LData(data) = self { let ldata = data.get_ldata(); match ldata.label.as_str() { "Some" => { if let Some(v) = &ldata.data { let e: T = RTDataToRust::into(&v[0]); Some(e) } else { panic!("invalid Some") } } "None" => None, _ => panic!("label is neither Some nor None"), } } else { panic!("data is not Option"); } } } /// Convert a BLisp's list to a Rust's Vec. fn list_to_vec<T>(mut ldata: &LabeledData, result: &mut Vec<T>) where RTData: RTDataToRust<T>, { loop { match ldata.label.as_str() { "Cons" => { if let Some(v) = &ldata.data { let e: T = RTDataToRust::into(&v[0]); result.push(e); if let RTData::LData(data) = &v[1] { ldata = data.get_ldata(); } else { panic!("no next in Cons") } } else { panic!("invalid Cons"); } } "Nil" => break, _ => panic!("label is neither Cons nor Nil"), } } } /// Convert a BLisp's Result to a Rust's Result. impl<T, E> RTDataToRust<Result<T, E>> for RTData where RTData: RTDataToRust<T> + RTDataToRust<E>, { fn into(&self) -> Result<T, E> { if let RTData::LData(data) = self { let ldata = data.get_ldata(); match ldata.label.as_str() { "Ok" => { if let Some(v) = &ldata.data { let e: T = RTDataToRust::into(&v[0]); Ok(e) } else { panic!("invalid Ok") } } "Err" => { if let Some(v) = &ldata.data { let e: E = RTDataToRust::into(&v[0]); Err(e) } else { panic!("invalid Err") } } _ => panic!("label is neither Ok nor Err"), } } else { panic!("data is not Result"); } } } /// Convert a BLisp's Tuple to a Rust's Tuple /// where the length is 2. impl<T0, T1> RTDataToRust<(T0, T1)> for RTData where RTData: RTDataToRust<T0> + RTDataToRust<T1>, { fn into(&self) -> (T0, T1) { if let RTData::LData(data) = self { let ldata = data.get_ldata(); match ldata.label.as_str() { "Tuple" => { if let Some(v) = &ldata.data { let v0: T0 = RTDataToRust::into(&v[0]); let v1: T1 = RTDataToRust::into(&v[1]); (v0, v1) } else { panic!("invalid Tuple") } } _ => panic!("label is not Tuple"), } } else { panic!("data is not Tuple"); } } } /// Convert a BLisp's Tuple to a Rust's Tuple /// where the length is 3. impl<T0, T1, T2> RTDataToRust<(T0, T1, T2)> for RTData where RTData: RTDataToRust<T0> + RTDataToRust<T1> + RTDataToRust<T2>, { fn into(&self) -> (T0, T1, T2) { if let RTData::LData(data) = self { let ldata = data.get_ldata(); match ldata.label.as_str() { "Tuple" => { if let Some(v) = &ldata.data { let v0: T0 = RTDataToRust::into(&v[0]); let v1: T1 = RTDataToRust::into(&v[1]); let v2: T2 = RTDataToRust::into(&v[2]); (v0, v1, v2) } else { panic!("invalid Tuple") } } _ => panic!("label is not Tuple"), } } else { panic!("data is not Tuple"); } } } /// Convert a BLisp's Tuple to a Rust's Tuple /// where the length is 4. impl<T0, T1, T2, T3> RTDataToRust<(T0, T1, T2, T3)> for RTData where RTData: RTDataToRust<T0> + RTDataToRust<T1> + RTDataToRust<T2> + RTDataToRust<T3>, { fn into(&self) -> (T0, T1, T2, T3) { if let RTData::LData(data) = self { let ldata = data.get_ldata(); match ldata.label.as_str() { "Tuple" => { if let Some(v) = &ldata.data { let v0: T0 = RTDataToRust::into(&v[0]); let v1: T1 = RTDataToRust::into(&v[1]); let v2: T2 = RTDataToRust::into(&v[2]); let v3: T3 = RTDataToRust::into(&v[3]); (v0, v1, v2, v3) } else { panic!("invalid Tuple") } } _ => panic!("label is not Tuple"), } } else { panic!("data is not Tuple"); } } } /// Convert a BLisp's Tuple to a Rust's Tuple /// where the length is 5. impl<T0, T1, T2, T3, T4> RTDataToRust<(T0, T1, T2, T3, T4)> for RTData where RTData: RTDataToRust<T0> + RTDataToRust<T1> + RTDataToRust<T2> + RTDataToRust<T3> + RTDataToRust<T4>, { fn into(&self) -> (T0, T1, T2, T3, T4) { if let RTData::LData(data) = self { let ldata = data.get_ldata(); match ldata.label.as_str() { "Tuple" => { if let Some(v) = &ldata.data { let v0: T0 = RTDataToRust::into(&v[0]); let v1: T1 = RTDataToRust::into(&v[1]); let v2: T2 = RTDataToRust::into(&v[2]); let v3: T3 = RTDataToRust::into(&v[3]); let v4: T4 = RTDataToRust::into(&v[4]); (v0, v1, v2, v3, v4) } else { panic!("invalid Tuple") } } _ => panic!("label is not Tuple"), } } else { panic!("data is not Tuple"); } } } pub trait RustToRTData<T> { fn from(env: &mut Environment<'_>, value: T) -> Self; } impl RustToRTData<BigInt> for RTData { fn from(env: &mut Environment<'_>, value: BigInt) -> Self { RTData::Int(env.root.make_int(value)) } } impl RustToRTData<char> for RTData { fn from(_env: &mut Environment<'_>, value: char) -> Self { RTData::Char(value) } } impl RustToRTData<bool> for RTData { fn from(_env: &mut Environment<'_>, value: bool) -> Self { RTData::Bool(value) } } impl RustToRTData<String> for RTData { fn from(env: &mut Environment<'_>, value: String) -> Self { RTData::Str(env.root.make_str(value)) } } impl<T> RustToRTData<Option<T>> for RTData where RTData: RustToRTData<T>, { fn from(env: &mut Environment<'_>, value: Option<T>) -> Self { if let Some(value) = value { let value = RustToRTData::from(env, value); RTData::LData(env.root.make_obj("Some".to_string(), Some(vec![value]))) } else { RTData::LData(env.root.make_obj("None".to_string(), None)) } } } impl<T, E> RustToRTData<Result<T, E>> for RTData where RTData: RustToRTData<T> + RustToRTData<E>, { fn from(env: &mut Environment<'_>, value: Result<T, E>) -> Self { match value { Ok(value) => { let value = RustToRTData::from(env, value); RTData::LData(env.root.make_obj("Ok".to_string(), Some(vec![value]))) } Err(value) => { let value = RustToRTData::from(env, value); RTData::LData(env.root.make_obj("Err".to_string(), Some(vec![value]))) } } } } impl RustToRTData<()> for RTData { fn from(env: &mut Environment<'_>, _: ()) -> Self { RTData::LData(env.root.make_obj("Tuple".to_string(), Some(vec![]))) } } impl<T0, T1> RustToRTData<(T0, T1)> for RTData where RTData: RustToRTData<T0> + RustToRTData<T1>, { fn from(env: &mut Environment<'_>, (v0, v1): (T0, T1)) -> Self { let v0 = RustToRTData::from(env, v0); let v1 = RustToRTData::from(env, v1); RTData::LData(env.root.make_obj("Tuple".to_string(), Some(vec![v0, v1]))) } } impl<T0, T1, T2> RustToRTData<(T0, T1, T2)> for RTData where RTData: RustToRTData<T0> + RustToRTData<T1> + RustToRTData<T2>, { fn from(env: &mut Environment<'_>, (v0, v1, v2): (T0, T1, T2)) -> Self { let v0 = RustToRTData::from(env, v0); let v1 = RustToRTData::from(env, v1); let v2 = RustToRTData::from(env, v2); RTData::LData( env.root .make_obj("Tuple".to_string(), Some(vec![v0, v1, v2])), ) } } impl<T0, T1, T2, T3> RustToRTData<(T0, T1, T2, T3)> for RTData where RTData: RustToRTData<T0> + RustToRTData<T1> + RustToRTData<T2> + RustToRTData<T3>, { fn from(env: &mut Environment<'_>, (v0, v1, v2, v3): (T0, T1, T2, T3)) -> Self { let v0 = RustToRTData::from(env, v0); let v1 = RustToRTData::from(env, v1); let v2 = RustToRTData::from(env, v2); let v3 = RustToRTData::from(env, v3); RTData::LData( env.root .make_obj("Tuple".to_string(), Some(vec![v0, v1, v2, v3])), ) } } impl<T0, T1, T2, T3, T4> RustToRTData<(T0, T1, T2, T3, T4)> for RTData where RTData: RustToRTData<T0> + RustToRTData<T1> + RustToRTData<T2> + RustToRTData<T3> + RustToRTData<T4>, { fn from(env: &mut Environment<'_>, (v0, v1, v2, v3, v4): (T0, T1, T2, T3, T4)) -> Self { let v0 = RustToRTData::from(env, v0); let v1 = RustToRTData::from(env, v1); let v2 = RustToRTData::from(env, v2); let v3 = RustToRTData::from(env, v3); let v4 = RustToRTData::from(env, v4); RTData::LData( env.root .make_obj("Tuple".to_string(), Some(vec![v0, v1, v2, v3, v4])), ) } } pub trait FFI { /// Extern expression of BLisp fn blisp_extern(&self) -> &'static str; /// Return the corresponding FFI. fn ffi(&self) -> fn(env: &mut Environment<'_>, args: &[RTData]) -> RTData; /// The function name. fn name(&self) -> &'static str; }
mod asset_manager; pub use asset_manager::*; mod asset_path; pub use asset_path::*;
#[doc = "Reader of register CC"] pub type R = crate::R<u32, super::CC>; #[doc = "Writer for register CC"] pub type W = crate::W<u32, super::CC>; #[doc = "Register CC `reset()`'s with value 0"] impl crate::ResetValue for super::CC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "PWM Clock Divider\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PWMDIV_A { #[doc = "0: /2"] _2 = 0, #[doc = "1: /4"] _4 = 1, #[doc = "2: /8"] _8 = 2, #[doc = "3: /16"] _16 = 3, #[doc = "4: /32"] _32 = 4, #[doc = "5: /64"] _64 = 5, } impl From<PWMDIV_A> for u8 { #[inline(always)] fn from(variant: PWMDIV_A) -> Self { variant as _ } } #[doc = "Reader of field `PWMDIV`"] pub type PWMDIV_R = crate::R<u8, PWMDIV_A>; impl PWMDIV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, PWMDIV_A> { use crate::Variant::*; match self.bits { 0 => Val(PWMDIV_A::_2), 1 => Val(PWMDIV_A::_4), 2 => Val(PWMDIV_A::_8), 3 => Val(PWMDIV_A::_16), 4 => Val(PWMDIV_A::_32), 5 => Val(PWMDIV_A::_64), i => Res(i), } } #[doc = "Checks if the value of the field is `_2`"] #[inline(always)] pub fn is_2(&self) -> bool { *self == PWMDIV_A::_2 } #[doc = "Checks if the value of the field is `_4`"] #[inline(always)] pub fn is_4(&self) -> bool { *self == PWMDIV_A::_4 } #[doc = "Checks if the value of the field is `_8`"] #[inline(always)] pub fn is_8(&self) -> bool { *self == PWMDIV_A::_8 } #[doc = "Checks if the value of the field is `_16`"] #[inline(always)] pub fn is_16(&self) -> bool { *self == PWMDIV_A::_16 } #[doc = "Checks if the value of the field is `_32`"] #[inline(always)] pub fn is_32(&self) -> bool { *self == PWMDIV_A::_32 } #[doc = "Checks if the value of the field is `_64`"] #[inline(always)] pub fn is_64(&self) -> bool { *self == PWMDIV_A::_64 } } #[doc = "Write proxy for field `PWMDIV`"] pub struct PWMDIV_W<'a> { w: &'a mut W, } impl<'a> PWMDIV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PWMDIV_A) -> &'a mut W { unsafe { self.bits(variant.into()) } } #[doc = "/2"] #[inline(always)] pub fn _2(self) -> &'a mut W { self.variant(PWMDIV_A::_2) } #[doc = "/4"] #[inline(always)] pub fn _4(self) -> &'a mut W { self.variant(PWMDIV_A::_4) } #[doc = "/8"] #[inline(always)] pub fn _8(self) -> &'a mut W { self.variant(PWMDIV_A::_8) } #[doc = "/16"] #[inline(always)] pub fn _16(self) -> &'a mut W { self.variant(PWMDIV_A::_16) } #[doc = "/32"] #[inline(always)] pub fn _32(self) -> &'a mut W { self.variant(PWMDIV_A::_32) } #[doc = "/64"] #[inline(always)] pub fn _64(self) -> &'a mut W { self.variant(PWMDIV_A::_64) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07); self.w } } #[doc = "Reader of field `USEPWM`"] pub type USEPWM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USEPWM`"] pub struct USEPWM_W<'a> { w: &'a mut W, } impl<'a> USEPWM_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8); self.w } } impl R { #[doc = "Bits 0:2 - PWM Clock Divider"] #[inline(always)] pub fn pwmdiv(&self) -> PWMDIV_R { PWMDIV_R::new((self.bits & 0x07) as u8) } #[doc = "Bit 8 - Use PWM Clock Divisor"] #[inline(always)] pub fn usepwm(&self) -> USEPWM_R { USEPWM_R::new(((self.bits >> 8) & 0x01) != 0) } } impl W { #[doc = "Bits 0:2 - PWM Clock Divider"] #[inline(always)] pub fn pwmdiv(&mut self) -> PWMDIV_W { PWMDIV_W { w: self } } #[doc = "Bit 8 - Use PWM Clock Divisor"] #[inline(always)] pub fn usepwm(&mut self) -> USEPWM_W { USEPWM_W { w: self } } }
use anyhow::{anyhow, Result}; use std::{collections::BTreeMap, fmt}; use tokio::process::Command; const CMD: &str = "/usr/bin/ansible-playbook"; pub const INSTALL_HOST_PLAYBOOK: &str = "playbooks/roles/setup_host/playbook.yml"; #[derive(Debug)] pub struct AnsibleCommand<'a> { playbook: &'a str, user: &'a str, host: &'a str, extra_params: BTreeMap<String, String>, } impl<'a> AnsibleCommand<'a> { pub fn new( playbook: &'a str, user: &'a str, host: &'a str, extra_params: BTreeMap<String, String>, ) -> Self { AnsibleCommand { playbook, user, host, extra_params, } } pub async fn run_playbook(&self) -> Result<()> { // TODO: handle errors and write output properly let mut process = Command::new(CMD) .args(self.to_string().split(' ')) .spawn() .expect("Ansible failed"); match process.wait().await { Ok(status) => { if status.success() { Ok(()) } else { Err(anyhow!("playbook failed, '{}'", status)) } } Err(e) => Err(anyhow!(e)), } } } impl<'a> fmt::Display for AnsibleCommand<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let mut output = format!("{} -i {}, -u {}", self.playbook, self.host, self.user); for (k, v) in self.extra_params.iter() { output.push_str(format!(" -e {}={}", k, v).as_str()); } write!(f, "{}", output) } } #[cfg(test)] mod test { use super::*; #[test] fn test_generate_command() { let mut extra_params = BTreeMap::new(); extra_params.insert(String::from("ansible_password"), String::from("fedora")); extra_params.insert(String::from("fcversion"), String::from("0.21.1")); let ac = AnsibleCommand::new(CMD, "root", "192.168.122.45", extra_params); const OUTPUT: &str = "/usr/bin/ansible-playbook -i 192.168.122.45, -u root -e ansible_password=fedora -e fcversion=0.21.1"; assert_eq!(ac.to_string(), OUTPUT); } }
// See LICENSE file for copyright and license details. use glfw; use cgmath::{Vector2}; use visualizer::mgl; use visualizer::types::{Time, ScreenPos}; use visualizer::gui::{ButtonManager, Button, ButtonId}; use visualizer::context::Context; use visualizer::state_visualizer::{ StateVisualizer, StateChangeCommand, StartGame, QuitMenu, }; pub struct MenuStateVisualizer { button_manager: ButtonManager, button_start_id: ButtonId, button_quit_id: ButtonId, commands_rx: Receiver<StateChangeCommand>, commands_tx: Sender<StateChangeCommand>, } impl MenuStateVisualizer { pub fn new(context: &Context) -> MenuStateVisualizer { let mut button_manager = ButtonManager::new(); let button_start_id = button_manager.add_button(Button::new( "start", context.font_stash.borrow_mut().deref_mut(), &context.shader, ScreenPos{v: Vector2{x: 10, y: 40}}) ); let button_quit_id = button_manager.add_button(Button::new( "quit", context.font_stash.borrow_mut().deref_mut(), &context.shader, ScreenPos{v: Vector2{x: 10, y: 10}}) ); let (commands_tx, commands_rx) = channel(); MenuStateVisualizer { button_manager: button_manager, button_start_id: button_start_id, button_quit_id: button_quit_id, commands_rx: commands_rx, commands_tx: commands_tx, } } fn handle_mouse_button_event(&mut self, context: &Context) { match self.button_manager.get_clicked_button_id(context) { Some(button_id) => { if button_id == self.button_start_id { self.commands_tx.send(StartGame); } else if button_id == self.button_quit_id { self.commands_tx.send(QuitMenu); } }, None => {}, } } } impl StateVisualizer for MenuStateVisualizer { fn logic(&mut self, _: &Context) {} fn draw(&mut self, context: &Context, _: Time) { use glfw::Context; mgl::set_clear_color(mgl::BLACK_3); mgl::clear_screen(); context.shader.activate(); context.shader.uniform_color(context.basic_color_id, mgl::WHITE); self.button_manager.draw(context); context.win.swap_buffers(); } fn handle_event(&mut self, context: &Context, event: glfw::WindowEvent) { match event { glfw::KeyEvent(key, _, glfw::Press, _) => { match key { glfw::Key1 => { self.commands_tx.send(StartGame); }, glfw::KeyEscape | glfw::KeyQ => { self.commands_tx.send(QuitMenu); }, _ => {}, } }, glfw::MouseButtonEvent(glfw::MouseButtonLeft, glfw::Press, _) => { self.handle_mouse_button_event(context); }, _ => {}, } } fn get_command(&self) -> Option<StateChangeCommand> { match self.commands_rx.try_recv() { Ok(cmd) => Some(cmd), Err(_) => None, } } } // vim: set tabstop=4 shiftwidth=4 softtabstop=4 expandtab:
extern crate secp256k1; #[macro_use] extern crate lazy_static; extern crate generic_array; extern crate digest; extern crate sha2; extern crate ripemd160; extern crate base58; extern crate rand; extern crate pbkdf2; extern crate hmac; #[macro_use] extern crate hex_literal; extern crate byteorder; use std::marker::PhantomData; use digest::Digest; use sha2::{Sha256, Sha512}; use ripemd160::Ripemd160; use generic_array::{ GenericArray, sequence::Split, typenum::U4 }; use base58::ToBase58; use rand::{thread_rng, Rng}; use pbkdf2::pbkdf2; use hmac::Hmac; use byteorder::{BigEndian, ByteOrder}; lazy_static! { static ref SECP256K1_ENGINE: secp256k1::Secp256k1 = secp256k1::Secp256k1::new(); } #[derive(Debug)] pub enum BitError { Secp256k1(secp256k1::Error) } pub type Result<T> = std::result::Result<T, BitError>; #[derive(Debug)] pub struct SecretKey(secp256k1::key::SecretKey); impl SecretKey { pub const UNCOMPRESSED_SIZE: usize = secp256k1::constants::SECRET_KEY_SIZE; pub const COMPRESSED_SIZE: usize = SecretKey::UNCOMPRESSED_SIZE + 1; pub fn from_slice<T: AsRef<[u8]>>(bytes: T) -> Result<SecretKey> { match secp256k1::key::SecretKey::from_slice(&SECP256K1_ENGINE, bytes.as_ref()) { Ok(key) => Ok(SecretKey(key)), Err(err) => Err(BitError::Secp256k1(err)) } } pub fn bytes_uncompressed(&self) -> Vec<u8> { Vec::from(&self.0[..]) } pub fn bytes_compressed(&self) -> Vec<u8> { let mut vec = Vec::with_capacity(SecretKey::COMPRESSED_SIZE); vec.extend(&self.0[..]); vec.push(0x01); vec } } #[derive(Debug)] pub struct PublicKey(secp256k1::key::PublicKey); impl PublicKey { pub const UNCOMPRESSED_SIZE: usize = secp256k1::constants::SECRET_KEY_SIZE; pub const COMPRESSED_SIZE: usize = SecretKey::UNCOMPRESSED_SIZE + 1; pub fn from_secret_key(secret_key: &SecretKey) -> Result<PublicKey> { match secp256k1::key::PublicKey::from_secret_key(&SECP256K1_ENGINE, &secret_key.0) { Ok(key) => Ok(PublicKey(key)), Err(err) => Err(BitError::Secp256k1(err)) } } pub fn bytes_uncompressed(&self) -> Vec<u8> { Vec::from(self.0.serialize_vec(&SECP256K1_ENGINE, false).as_slice()) } pub fn bytes_compressed(&self) -> Vec<u8> { Vec::from(self.0.serialize_vec(&SECP256K1_ENGINE, true).as_slice()) } } #[derive(Debug)] pub struct Address(Vec<u8>); impl Address { pub fn from_public_key(public_key: &PublicKey, compressed: bool) -> Address { let k = if compressed { public_key.bytes_compressed() } else { public_key.bytes_uncompressed() }; Address(Vec::from(Ripemd160::digest(&Sha256::digest(&k)).as_slice())) } } impl AsRef<[u8]> for Address { fn as_ref(&self) -> &[u8] { &self.0 } } pub trait ToBase58Check { fn to_base58_check(&self, prefix: &[u8]) -> String; } impl<T: AsRef<[u8]>> ToBase58Check for T { fn to_base58_check(&self, prefix: &[u8]) -> String { //Add version prefix let mut result = Vec::with_capacity(self.as_ref().len() + prefix.len() + 4); result.extend(prefix); result.extend(self.as_ref()); //checksum = Sha256(Sha256(prefix+digest)) let checksum_digest = Sha256::digest(&Sha256::digest(&result)); //use only first 4 bytes let (checksum, _): (GenericArray<u8, U4>, _) = checksum_digest.split(); //concat & base58 result.extend(checksum); result.to_base58() } } pub trait MnemonicSize { fn entropy_bytes() -> usize; fn entropy_bits() -> usize; fn checksum_bits() -> usize; fn checksum_mask() -> u8; fn total_bits() -> usize; fn total_bytes() -> usize; fn words() -> usize; } macro_rules! gen_mnemonic_size { ($name:ident, $bits:expr) => { pub struct $name; impl MnemonicSize for $name { fn entropy_bytes() -> usize { $bits / 8 } fn entropy_bits() -> usize { $bits } fn checksum_bits() -> usize { $bits / 32 } fn checksum_mask() -> u8 { (((1 << $bits / 32 as u16) - 1) as u8) << 8 - $bits / 32 } fn total_bits() -> usize { $bits + $bits / 32 } fn total_bytes() -> usize { $bits / 8 + 1 } fn words() -> usize { ($bits + $bits / 32) / 11 } } }; } //entropy + checksum = total = 11 * words //128 + 4 = 132 bits = 11 * 12 words //160 + 5 = 165 bits = 11 * 15 words //192 + 6 = 198 bits = 11 * 18 words //224 + 7 = 231 bits = 11 * 21 words //256 + 8 = 256 bits = 11 * 24 words gen_mnemonic_size!(MnemonicSize12w, 128); gen_mnemonic_size!(MnemonicSize15w, 160); gen_mnemonic_size!(MnemonicSize18w, 192); gen_mnemonic_size!(MnemonicSize21w, 224); gen_mnemonic_size!(MnemonicSize24w, 256); #[derive(Debug)] pub struct Mnemonic<S: MnemonicSize>(Vec<u8>, PhantomData<S>); impl<S: MnemonicSize> Mnemonic<S> { pub fn generate() -> Mnemonic<S> { let mut rng = thread_rng(); let mut entropy = vec![0; S::entropy_bytes()]; rng.fill(&mut entropy[..]); Mnemonic(entropy, PhantomData) } pub fn from_entropy(entropy: Vec<u8>) -> Mnemonic<S> { debug_assert_eq!(entropy.len(), S::entropy_bytes()); Mnemonic(entropy, PhantomData) } pub fn words(self, dictionary: &[String]) -> String { let mut array = Vec::with_capacity(S::total_bytes()); array.extend(self.0); array.push(0); //add checksum let checksum = Sha256::digest(&array[..S::entropy_bytes()]); array[S::entropy_bytes()] = checksum[0] & S::checksum_mask(); //split into 11bits segments let mut segments = Vec::with_capacity(S::words()); let mut r = 8; let mut j = 0; for _ in 0..S::words() { let al = 11 - r; let be = 8 - al; if be < 0 { let de = 8 + be; segments.push( ((array[j] as u16) << al | (array[j + 1] as u16) << -be | (array[j + 2] >> de) as u16) & 0b11111111111 ); j += 2; r = de; } else { segments.push( ((array[j] as u16) << al | (array[j + 1] >> be) as u16) & 0b11111111111 ); j += 1; r = be; } } //map with dictionnary segments[..].iter() .map(|el| &dictionary[*el as usize]) .map(|el| el.as_str()) .collect::<Vec<_>>() .join(" ") } } #[derive(Debug)] pub struct Seed(Vec<u8>); impl Seed { pub const SIZE: usize = 512 / 8; //512 bits pub fn from_words(words: &str, passphrase: &str) -> Seed { let mut vec = vec![0; Seed::SIZE]; pbkdf2::<Hmac<Sha512>>(words.as_bytes(), ("mnemonic".to_owned() + passphrase).as_bytes(), 2048, &mut vec); Seed(vec) } } impl AsRef<[u8]> for Seed { fn as_ref(&self) -> &[u8] { &self.0 } } #[derive(Debug)] #[derive(PartialEq)] #[derive(Clone)] pub struct ExtendedKey<'a> { pub key_type: KeyType, pub net: Net, pub depth: u8, pub parent_fingerprint: u32, pub child_number: u32, pub chain_code: &'a [u8], pub key: &'a [u8], } #[derive(Debug)] #[derive(PartialEq)] #[derive(Copy)] #[derive(Clone)] pub enum KeyType { Public, Private } #[derive(Debug)] #[derive(PartialEq)] #[derive(Copy)] #[derive(Clone)] pub enum Net { MainNet, TestNet } #[derive(Debug)] pub struct KeyParseError; impl<'a> ExtendedKey<'a> { pub fn parse(xkey: &'a [u8]) -> std::result::Result<ExtendedKey<'a>, KeyParseError> { if xkey.len() != 78 { return Err(KeyParseError) } let (key_type, net) = match xkey[..4] { ref b if b == hex!("0488b21e") => (KeyType::Public, Net::MainNet), ref b if b == hex!("0488ade4") => (KeyType::Private, Net::MainNet), ref b if b == hex!("043587cf") => (KeyType::Public, Net::TestNet), ref b if b == hex!("04358394") => (KeyType::Private, Net::TestNet), _ => return Err(KeyParseError) }; let depth = xkey[4]; let parent_fingerprint = BigEndian::read_u32(&xkey[5..9]); let child_number = BigEndian::read_u32(&xkey[9..13]); let chain_code = &xkey[13..45]; let key = &xkey[45..78]; Ok(ExtendedKey { key_type, net, depth, parent_fingerprint, child_number, chain_code, key }) } pub fn serialize(&self) -> String { let mut ser = Vec::with_capacity(78); let prefix = match (self.key_type, self.net) { (KeyType::Public, Net::MainNet) => hex!("0488b21e"), (KeyType::Private, Net::MainNet) => hex!("0488ade4"), (KeyType::Public, Net::TestNet) => hex!("043587cf"), (KeyType::Private, Net::TestNet) => hex!("04358394") }; ser.extend(&prefix); ser.push(self.depth); ser.extend(&[0; 4]); BigEndian::write_u32(&mut ser[5..9], self.parent_fingerprint); ser.extend(&[0; 4]); BigEndian::write_u32(&mut ser[9..13], self.child_number); ser.extend(self.chain_code); ser.extend(self.key); ser.to_base58_check(&[]) } } #[cfg(test)] mod tests { use super::*; use std::fs::File; use std::io::{BufRead, BufReader}; use base58::FromBase58; #[test] fn uncompressed_secret_key() { let secret_key = SecretKey::from_slice(&hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6")).unwrap(); let test: &[u8] = &hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6"); assert_eq!(secret_key.bytes_uncompressed(), test); } #[test] fn compressed_secret_key() { let secret_key = SecretKey::from_slice(&hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6")).unwrap(); let test: &[u8] = &hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa601"); assert_eq!(secret_key.bytes_compressed(), test); } #[test] fn wif_uncompressed_secret_key() { let secret_key = SecretKey::from_slice(&hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6")).unwrap(); assert_eq!(secret_key.bytes_uncompressed().to_base58_check(&[0x80]), "5JG9hT3beGTJuUAmCQEmNaxAuMacCTfXuw1R3FCXig23RQHMr4K"); } #[test] fn wif_compressed_secret_key() { let secret_key = SecretKey::from_slice(&hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6")).unwrap(); assert_eq!(secret_key.bytes_compressed().to_base58_check(&[0x80]), "KyBsPXxTuVD82av65KZkrGrWi5qLMah5SdNq6uftawDbgKa2wv6S"); } #[test] fn uncompressed_public_key() { let secret_key = SecretKey::from_slice(&hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6")).unwrap(); let public_key = PublicKey::from_secret_key(&secret_key).unwrap(); let test: &[u8] = &hex!("045c0de3b9c8ab18dd04e3511243ec2952002dbfadc864b9628910169d9b9b00ec243bcefdd4347074d44bd7356d6a53c495737dd96295e2a9374bf5f02ebfc176"); assert_eq!(public_key.bytes_uncompressed(), test); } #[test] fn compressed_public_key() { let secret_key = SecretKey::from_slice(&hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6")).unwrap(); let public_key = PublicKey::from_secret_key(&secret_key).unwrap(); let test: &[u8] = &hex!("025c0de3b9c8ab18dd04e3511243ec2952002dbfadc864b9628910169d9b9b00ec"); assert_eq!(public_key.bytes_compressed(), test); } #[test] fn uncompressed_address() { let secret_key = SecretKey::from_slice(&hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6")).unwrap(); let public_key = PublicKey::from_secret_key(&secret_key).unwrap(); let address = Address::from_public_key(&public_key, false); assert_eq!(address.to_base58_check(&[0x00]), "1thMirt546nngXqyPEz532S8fLwbozud8"); } #[test] fn compressed_address() { let secret_key = SecretKey::from_slice(&hex!("3aba4162c7251c891207b747840551a71939b0de081f85c4e44cf7c13e41daa6")).unwrap(); let public_key = PublicKey::from_secret_key(&secret_key).unwrap(); let address = Address::from_public_key(&public_key, true); assert_eq!(address.to_base58_check(&[0x00]), "14cxpo3MBCYYWCgF74SWTdcmxipnGUsPw3"); } #[test] fn mnemonic_from_entropy() { let f = File::open("english.txt").expect("file not found"); let reader = BufReader::new(f); let lines = reader.lines() .map(|el| el.unwrap()) .collect::<Vec<_>>(); let entropy: &[u8] = &hex!("0c1e24e5917779d297e14d45f14e1a1a"); let mnemonic = Mnemonic::<MnemonicSize12w>::from_entropy(Vec::from(entropy)); let test: &[u8] = &hex!("5b56c417303faa3fcba7e57400e120a0ca83ec5a4fc9ffba757fbe63fbd77a89a1a3be4c67196f57c39a88b76373733891bfaba16ed27a813ceed498804c0570"); assert_eq!(Seed::from_words(mnemonic.words(&lines).as_str(), "").as_ref(), test); } #[test] fn mnemonic_seed() { let words = "army van defense carry jealous true garbage claim echo media make crunch"; let test: &[u8] = &hex!("5b56c417303faa3fcba7e57400e120a0ca83ec5a4fc9ffba757fbe63fbd77a89a1a3be4c67196f57c39a88b76373733891bfaba16ed27a813ceed498804c0570"); assert_eq!(Seed::from_words(words, "").as_ref(), test); } #[test] fn extended_key_parse1() { let a = "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8".from_base58().unwrap(); let k = ExtendedKey::parse(&a[..78]).unwrap(); assert_eq!(k.key_type, KeyType::Public); assert_eq!(k.net, Net::MainNet); assert_eq!(k.depth, 0); assert_eq!(k.parent_fingerprint, 0); assert_eq!(k.child_number, 0); let chain_code: &[u8] = &hex!("873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508"); assert_eq!(k.chain_code, chain_code); let key: &[u8] = &hex!("0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2"); assert_eq!(k.key, key); } #[test] fn extended_key_parse2() { let a = "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi".from_base58().unwrap(); let k = ExtendedKey::parse(&a[..78]).unwrap(); assert_eq!(k.key_type, KeyType::Private); assert_eq!(k.net, Net::MainNet); assert_eq!(k.depth, 0); assert_eq!(k.parent_fingerprint, 0); assert_eq!(k.child_number, 0); let chain_code: &[u8] = &hex!("873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508"); assert_eq!(k.chain_code, chain_code); let key: &[u8] = &hex!("00e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35"); assert_eq!(k.key, key); } #[test] fn extended_key_serialize1() { let k = ExtendedKey { key_type: KeyType::Public, net: Net::MainNet, depth: 0, parent_fingerprint: 0, child_number: 0, chain_code: &hex!("873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508"), key: &hex!("0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2") }; assert_eq!(k.serialize(), "xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8"); } #[test] fn extended_key_serialize2() { let k = ExtendedKey { key_type: KeyType::Private, net: Net::MainNet, depth: 0, parent_fingerprint: 0, child_number: 0, chain_code: &hex!("873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508"), key: &hex!("00e8f32e723decf4051aefac8e2c93c9c5b214313817cdb01a1494b917c8436b35") }; assert_eq!(k.serialize(), "xprv9s21ZrQH143K3QTDL4LXw2F7HEK3wJUD2nW2nRk4stbPy6cq3jPPqjiChkVvvNKmPGJxWUtg6LnF5kejMRNNU3TGtRBeJgk33yuGBxrMPHi"); } }
#![recursion_limit = "1024"] extern crate chrono; #[macro_use] extern crate error_chain; extern crate lalrpop_util; #[macro_use] extern crate lazy_static; extern crate petgraph; extern crate postgres; extern crate regex; extern crate rust_decimal; extern crate serde; extern crate serde_json; #[macro_use] extern crate slog; extern crate glob; extern crate slog_stdlog; extern crate zip; mod errors; pub use crate::errors::*; mod connection; mod model; mod semver; mod sql; pub mod ast { pub use crate::sql::ast::*; } pub use crate::connection::ConnectionBuilder; pub use crate::errors::{PsqlpackErrorKind, PsqlpackResult}; pub use crate::model::{ template, Capabilities, Delta, Dependency, GenerationOptions, Package, Project, PublishProfile, Toggle, }; pub use crate::semver::Semver; /// Allows usage of no logging, std `log`, or slog. pub enum LogConfig { NoLogging, StdLog, } pub use crate::LogConfig::*; impl From<LogConfig> for slog::Logger { fn from(config: LogConfig) -> Self { use slog::{Discard, Drain, Logger}; match config { NoLogging => Logger::root(Discard.fuse(), o!()), StdLog => Logger::root(slog_stdlog::StdLog.fuse(), o!()), } } }
// Copyright 2017 Dasein Phaos aka. Luxko // // 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. //! Heap traits use super::raw::*; use super::description::*; use super::{DefaultHeap, UploadHeap, ReadbackHeap}; /// a resource heap pub trait Heap { /// returns the raw heap reference fn as_raw(&self) -> &RawHeap; /// returns the mutable raw heap reference fn as_raw_mut(&mut self) ->&mut RawHeap; /// get heap size #[inline] fn size(&self) -> u64 { self.as_raw().size() } /// get heap alignment #[inline] fn alignment(&self) -> HeapAlignment { self.as_raw().alignment() } } /// a resource heap that accept buffers pub unsafe trait AcceptBuffer: Heap { } /// a resource heap that allows display pub unsafe trait AllowDisplay: Heap { } /// a resource heap that accepts MS textures pub unsafe trait AcceptMsTexture: Heap { } /// a resource heap with type Upload pub unsafe trait Upload: Heap { } /// a resource heap with type Readback pub unsafe trait Readback: Heap { } /// a resource heap with type Default pub unsafe trait GpuOnly: Heap { } pub unsafe trait AllowRtDs: Heap { } pub unsafe trait AllowNonRtDs: Heap { } impl_as_raw!(Heap, DefaultHeap, RawHeap); unsafe impl AcceptBuffer for DefaultHeap {} unsafe impl GpuOnly for DefaultHeap {} unsafe impl AllowRtDs for DefaultHeap {} unsafe impl AllowNonRtDs for DefaultHeap {} impl_as_raw!(Heap, UploadHeap, RawHeap); unsafe impl AcceptBuffer for UploadHeap {} unsafe impl Upload for UploadHeap {} unsafe impl AllowRtDs for UploadHeap {} unsafe impl AllowNonRtDs for UploadHeap {} impl_as_raw!(Heap, ReadbackHeap, RawHeap); unsafe impl AcceptBuffer for ReadbackHeap {} unsafe impl Readback for ReadbackHeap {} unsafe impl AllowRtDs for ReadbackHeap {} unsafe impl AllowNonRtDs for ReadbackHeap {}
use num_bigint::BigUint; use pyo3::exceptions::PyValueError; use pyo3::prelude::*; use stark_curve::FieldElement; use stark_hash::{stark_hash, Felt}; /// Computes the Pedersen hash. /// /// Inputs are expected to be big-endian 32 byte slices. #[pyfunction] fn pedersen_hash_func(a: &[u8], b: &[u8]) -> PyResult<Vec<u8>> { let a = Felt::from_be_slice(a).map_err(|e| PyValueError::new_err(e.to_string()))?; let b = Felt::from_be_slice(b).map_err(|e| PyValueError::new_err(e.to_string()))?; let hash = stark_hash(a, b); Ok(hash.to_be_bytes().to_vec()) } /// Computes the Pedersen hash. /// /// Inputs are expected to be Python integers. #[pyfunction] fn pedersen_hash(a: BigUint, b: BigUint) -> PyResult<BigUint> { let a = Felt::from_be_slice(&a.to_bytes_be()).map_err(|e| PyValueError::new_err(e.to_string()))?; let b = Felt::from_be_slice(&b.to_bytes_be()).map_err(|e| PyValueError::new_err(e.to_string()))?; let hash = stark_hash(a, b); Ok(BigUint::from_bytes_be(&hash.to_be_bytes())) } /// Computes the Poseidon hash of two felts. /// /// Inputs are expected to be big-endian 32 byte slices. #[pyfunction] fn poseidon_hash_func(a: &[u8], b: &[u8]) -> PyResult<Vec<u8>> { let a = Felt::from_be_slice(a).map_err(|e| PyValueError::new_err(e.to_string()))?; let b = Felt::from_be_slice(b).map_err(|e| PyValueError::new_err(e.to_string()))?; let hash: Felt = stark_poseidon::poseidon_hash(a.into(), b.into()).into(); Ok(hash.to_be_bytes().to_vec()) } /// Computes the Poseidon hash of two felts. /// /// Inputs are expected to be Python integers. #[pyfunction] fn poseidon_hash(a: BigUint, b: BigUint, poseidon_params: Option<PyObject>) -> PyResult<BigUint> { assert!( poseidon_params.is_none(), "Non-default Poseidon parameters are not supported" ); let a = Felt::from_be_slice(&a.to_bytes_be()).map_err(|e| PyValueError::new_err(e.to_string()))?; let b = Felt::from_be_slice(&b.to_bytes_be()).map_err(|e| PyValueError::new_err(e.to_string()))?; let hash: Felt = stark_poseidon::poseidon_hash(a.into(), b.into()).into(); Ok(BigUint::from_bytes_be(&hash.to_be_bytes())) } /// Computes the Poseidon hash of a sequence of felts. /// /// Input is expected to be a sequence of Python integers. #[pyfunction] fn poseidon_hash_many(array: Vec<BigUint>, poseidon_params: Option<PyObject>) -> PyResult<BigUint> { assert!( poseidon_params.is_none(), "Non-default Poseidon parameters are not supported" ); let array = array .into_iter() .map(|a| { Felt::from_be_slice(&a.to_bytes_be()) .map(Into::into) .map_err(|e| PyValueError::new_err(e.to_string())) }) .collect::<Result<Vec<FieldElement>, PyErr>>()?; let hash: Felt = stark_poseidon::poseidon_hash_many(&array).into(); Ok(BigUint::from_bytes_be(&hash.to_be_bytes())) } #[pyfunction] fn poseidon_perm(a: BigUint, b: BigUint, c: BigUint) -> PyResult<Vec<BigUint>> { let a = Felt::from_be_slice(&a.to_bytes_be()).map_err(|e| PyValueError::new_err(e.to_string()))?; let b = Felt::from_be_slice(&b.to_bytes_be()).map_err(|e| PyValueError::new_err(e.to_string()))?; let c = Felt::from_be_slice(&c.to_bytes_be()).map_err(|e| PyValueError::new_err(e.to_string()))?; let mut state: stark_poseidon::PoseidonState = [a.into(), b.into(), c.into()]; stark_poseidon::permute_comp(&mut state); let output = state .into_iter() .map(|e| BigUint::from_bytes_be(&Felt::from(e).to_be_bytes())) .collect(); Ok(output) } #[pymodule] fn starknet_pathfinder_crypto(_py: Python<'_>, m: &PyModule) -> PyResult<()> { m.add_function(wrap_pyfunction!(pedersen_hash, m)?)?; m.add_function(wrap_pyfunction!(pedersen_hash_func, m)?)?; m.add_function(wrap_pyfunction!(poseidon_hash, m)?)?; m.add_function(wrap_pyfunction!(poseidon_hash_func, m)?)?; m.add_function(wrap_pyfunction!(poseidon_hash_many, m)?)?; m.add_function(wrap_pyfunction!(poseidon_perm, m)?)?; Ok(()) }
// Copyright (c) 2018-2022 Ministerio de Fomento // Instituto de Ciencias de la Construcción Eduardo Torroja (IETcc-CSIC) // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // Author(s): Rafael Villar Burke <pachi@ietcc.csic.es>, // Daniel Jiménez González <dani@ietcc.csic.es>, // Marta Sorribes Gil <msorribes@ietcc.csic.es> use std::{fmt, str}; use serde::{Deserialize, Serialize}; use super::{EAux, EOut, EProd, EUsed}; use crate::types::{Carrier, HasValues, ProdSource, Service, Source}; /// Componentes de energía generada, consumida, auxiliar o saliente (entregada/absorbida) #[derive(Debug, Clone, Serialize, Deserialize)] pub enum Energy { /// Energía generada (producida). E_pr;cr,i;t /// /// Representa la producción de energía del vector energético j /// (con origen dado en el sistema j) para los pasos de cálculo t, /// a lo largo del periodo de cálculo. Ej. E_pr,j;cr,i;t Prod(EProd), /// Energía usada (consumida). E_X;Y;in;cr,j;t /// /// Representa el consumo de energía del vector energético j /// para el servicio X en el subsistema Y y sistema i, (id=i), /// para los distintos pasos de cálculo t, /// a lo largo del periodo de cálculo. Ej. E_X;gen,i;in;cr,j;t /// /// Las cantidades de energía de combustibles son en relación al poder calorífico superior. Used(EUsed), /// Energía auxiliar (consumida). W_X;Y;aux;t /// /// Representa el consumo de energía (eléctrica) para usos auxiliares /// del servicio X en el subsistema Y y sistema i (id=i), /// para los distintos pasos de cálculo. Ej. W_X;gen_i;aux;t Aux(EAux), /// Energía saliente (entregada o absorbida). Q_X;Y;out /// /// Representa la energía térmica entregada o absorbida para el servicio X por los sistemas i /// pertenecientes al subsistema Y del edificio. Ej. Q_X;gen,i;out Out(EOut), } impl Energy { /// Get id for this service pub fn id(&self) -> i32 { match self { Energy::Prod(e) => e.id, Energy::Used(e) => e.id, Energy::Aux(e) => e.id, Energy::Out(e) => e.id, } } /// Get carrier for this component pub fn carrier(&self) -> Carrier { match self { Energy::Prod(e) => e.source.into(), Energy::Used(e) => e.carrier, Energy::Aux(_) => Carrier::ELECTRICIDAD, Energy::Out(_) => unreachable!(), } } /// Get production source (INSITU / COGEN) for this component pub fn source(&self) -> Source { match self { Energy::Prod(e) => e.source.into(), Energy::Used(_) | Energy::Aux(_) | Energy::Out(_) => { unreachable!() } } } /// Get production source (TERMOSOLAR / EL_INSITU / EL_COGEN / EAMBIENTE) for this component pub fn prod_source(&self) -> ProdSource { match self { Energy::Prod(e) => e.source, Energy::Used(_) | Energy::Aux(_) | Energy::Out(_) => { unreachable!() } } } /// Get service for this component pub fn service(&self) -> Service { match self { Energy::Prod(_) => unreachable!(), Energy::Used(e) => e.service, Energy::Aux(e) => e.service, Energy::Out(e) => e.service, } } /// Get comment for this component pub fn comment(&self) -> &str { match self { Energy::Prod(e) => &e.comment, Energy::Used(e) => &e.comment, Energy::Aux(e) => &e.comment, Energy::Out(e) => &e.comment, } } /// Is this of kind UsedEnergy? pub fn is_used(&self) -> bool { match self { Energy::Prod(_) => false, Energy::Used(_) => true, Energy::Aux(_) => false, Energy::Out(_) => false, } } /// Is this energy of the produced energy kind? pub fn is_generated(&self) -> bool { match self { Energy::Prod(_) => true, Energy::Used(_) => false, Energy::Aux(_) => false, Energy::Out(_) => false, } } /// Is this energy of the auxiliary energy kind? pub fn is_aux(&self) -> bool { match self { Energy::Prod(_) => false, Energy::Used(_) => false, Energy::Aux(_) => true, Energy::Out(_) => false, } } /// Is this energy of the output energy kind? pub fn is_out(&self) -> bool { match self { Energy::Prod(_) => false, Energy::Used(_) => false, Energy::Aux(_) => false, Energy::Out(_) => true, } } /// Is this of kind UsedEnergy and destination is an EPB service (includes aux and used)? pub fn is_epb_use(&self) -> bool { match self { Energy::Prod(_) => false, Energy::Used(e) => e.service.is_epb(), Energy::Aux(e) => e.service.is_epb(), Energy::Out(_) => false, } } /// Is this of kind UsedEnergy and destination is a non EPB service (but not COGEN)? pub fn is_nepb_use(&self) -> bool { match self { Energy::Prod(_) => false, Energy::Used(e) => e.service.is_nepb(), Energy::Aux(e) => e.service.is_nepb(), Energy::Out(_) => false, } } /// Is this of kind UsedEnergy and destination is cogeneration (COGEN)? pub fn is_cogen_use(&self) -> bool { match self { Energy::Prod(_) => false, Energy::Used(e) => e.service.is_cogen(), Energy::Aux(_) => false, Energy::Out(_) => false, } } /// Is this energy of the onsite produced kind? pub fn is_onsite_pr(&self) -> bool { match self { Energy::Prod(e) => e.source != ProdSource::EL_COGEN, Energy::Used(_) => false, Energy::Aux(_) => false, Energy::Out(_) => false, } } /// Is this energy of the cogeneration produced kind? pub fn is_cogen_pr(&self) -> bool { match self { Energy::Prod(e) => e.source == ProdSource::EL_COGEN, Energy::Used(_) => false, Energy::Aux(_) => false, Energy::Out(_) => false, } } /// Is this a production or use of the electricity carrier? pub fn is_electricity(&self) -> bool { match self { Energy::Aux(_) => true, _ => self.carrier() == Carrier::ELECTRICIDAD, } } /// Has this component this service? pub fn has_service(&self, srv: Service) -> bool { self.service() == srv } /// Has this component this carrier? pub fn has_carrier(&self, carrier: Carrier) -> bool { match self { Energy::Out(_) => false, _ => self.carrier() == carrier, } } /// Has this component this id? pub fn has_id(&self, id: i32) -> bool { self.id() == id } } impl std::fmt::Display for Energy { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Energy::Prod(e) => e.fmt(f), Energy::Used(e) => e.fmt(f), Energy::Aux(e) => e.fmt(f), Energy::Out(e) => e.fmt(f), } } } impl HasValues for Energy { fn values(&self) -> &[f32] { match self { Energy::Prod(e) => e.values(), Energy::Used(e) => e.values(), Energy::Aux(e) => e.values(), Energy::Out(e) => e.values(), } } }
use std::any::Any; use crate::{DefaultMutator, Mutator}; /* These mutators try to achieve multiple things: * avoid repetitions, such that if the value “7” was already produced, then it will not appear again * cover most of the search space as quickly as possible. For example, for 8-bit unsigned integers, it is good to produce a sequence such as: 0, 255, 128, 192, 64, 224, 32, etc. * also produce values close to the original integer first. So mutating 100 will first produce numbers such as 101, 99, 102, 98, etc. * be very fast One idea to create arbitrary integers that don't repeat themselves and span the whole search space was to use a binary-search-like approach, as written in the function binary_search_arbitrary. However that turns out to be quite slow for an integer mutator. So what I do instead is create a sequence of 256 random non-repeating integers, which I store in a variable called “shuffled integers” Now, for an 8-bit integer type, it is enough to simply index that vector to get an arbitrary value that respects all the criteria I laid above. But for types that have 16, 32, 64, or 128 bits, I can't do that. So I index the shuffled_integers vector multiple times until I have all the bits I need. For an u32, I need to index it four times. It is done in the following way: 1. first I look at the lower 8 bits of steps to get the first index * so if step == 67, then I use the index 67 * but if step == 259, then I use the index 3 2. I get a number between 0 and 255 by getting shuffled_integers[first_index], I memorize that pick. 3. I place the picked number on the highest 8 bits of the generated integer * so imagine the step was 259, then the index is 3 and shuffled_integers[3] is 192 * so the generated integer, so far, is (192 << 24) == 3_221_225_472 Let's stop to think about what that achieves. It means that for the first 256 steps, the 8 highest bits of the generated integer will be [0, 256, 128, 192, ...]. So we are covering a huge part of the possible space in the first 256 steps alone. The goal is to use that strategy recursively for the remaining bits, while adding a little but of arbitrariness to it. 4. Then I shift the step right by 8 bits. If it was 259 originally, it is now equal to (259 >> 8) == 3. 5. And then I XOR that index with the the previous pick (the purpose of that is to make the generation a little bit more arbitrary/less predictable) * so the new index is (3 ^ 192) == 195 6. I then get the next pick by getting shuffled_integers[192], let's say it is == 43. 7. Then we update the generated integer, it is now (192 << 24) | (43 << 16) 8. The next step is (259 >> 16) ^ 43 == 43 9. etc. You can find more details on how it is done in `uniform_permutation` */ macro_rules! binary_search_arbitrary { ($name_function: ident, $uxx:ty) => { #[no_coverage] pub(crate) fn $name_function(low: $uxx, high: $uxx, step: u64) -> $uxx { let next = low.wrapping_add(high.wrapping_sub(low) / 2); if low.wrapping_add(1) >= high { if step % 2 == 0 { high } else { low } } else if step == 0 { next } else if step % 2 == 1 { $name_function(next.wrapping_add(1), high, step / 2) } else { // step % 2 == 0 $name_function(low, next.wrapping_sub(1), (step - 1) / 2) } } }; } binary_search_arbitrary!(binary_search_arbitrary_u8, u8); binary_search_arbitrary!(binary_search_arbitrary_u16, u16); binary_search_arbitrary!(binary_search_arbitrary_u32, u32); binary_search_arbitrary!(binary_search_arbitrary_u64, u64); const INITIAL_MUTATION_STEP: u64 = 0; macro_rules! impl_int_mutator { ($name:ident, $name_unsigned: ident, $name_mutator:ident) => { #[derive(Clone)] pub struct $name_mutator { shuffled_integers: [u8; 256], rng: fastrand::Rng, } impl Default for $name_mutator { #[no_coverage] fn default() -> Self { let mut shuffled_integers = [0; 256]; for i in 0..=255_u8 { shuffled_integers[i as usize] = i; } let rng = fastrand::Rng::default(); rng.shuffle(&mut shuffled_integers); $name_mutator { shuffled_integers, rng, } } } impl $name_mutator { #[no_coverage] fn uniform_permutation(&self, step: u64) -> $name_unsigned { let size = <$name>::BITS as u64; // granularity is the number of bits provided by shuffled_integers // in this case, it is fixed to 8 but I could use something different // xxxx ... xxxx xxxx xxxx xxxx <- 64 bits for usize // 0000 ... 0000 0001 0000 0000 <- - 57 leading zeros for shuffled_integers.len() // ____ ... ____ ____ xxxx xxxx <- - 1 // = 8 const GRANULARITY: u64 = ((usize::BITS as usize) - (256u64.leading_zeros() as usize) - 1) as u64; const STEP_MASK: u64 = ((u8::MAX as usize) >> (8 - GRANULARITY)) as u64; // if I have a number, such as 983487234238, I can `AND` it with the step_mask // to get an index I can use on shuffled_integers. // in this case, the step_mask is fixed to // 0000 ... 0000 1111 1111 // it gives a number between 0 and 256 // step_i is used to index into shuffled_integers. The first value is the step // given as argument to this function. let step_i = (step & STEP_MASK) as usize; // now we start building the integer by taking bits from shuffled_integers // repeatedly. First by indexing it with step_i let mut prev = unsafe { *self.shuffled_integers.get_unchecked(step_i) as $name_unsigned }; // I put those bits at the highest position, then I will fill in the lower bits let mut result = (prev << (size - GRANULARITY)) as $name_unsigned; // remember, granularity is the number of bits we fill in at a time // and size is the total size of the generated integer, in bits // For u64 and a granularity of 8, we get // for i in [1, 2, 3, 4, 5, 6, 7] { ... } for i in 1..(size / GRANULARITY) { // each time, we shift step by `granularity` (e.g. 8) more bits to the right // so, for a step of 167 and a granularity of 8, then the next step will be 0 // it's only after steps larger than 255 that the next step will be greater than 0 // and then we XOR it with previous integer picked from shuffled_integers[step_i] // to get the next index into shuffled_integers, which we insert into // the generated integer at the right place let step_i = (((step >> (i * GRANULARITY)) ^ prev as u64) & STEP_MASK) as usize; prev = unsafe { *self.shuffled_integers.get_unchecked(step_i) as $name_unsigned }; result |= prev << (size - (i + 1) * GRANULARITY); } result } } impl Mutator<$name> for $name_mutator { #[doc(hidden)] type Cache = (); #[doc(hidden)] type MutationStep = u64; // mutation step #[doc(hidden)] type ArbitraryStep = u64; #[doc(hidden)] type UnmutateToken = $name; // old value #[doc(hidden)] #[no_coverage] fn initialize(&self) {} #[doc(hidden)] #[no_coverage] fn default_arbitrary_step(&self) -> Self::ArbitraryStep { <_>::default() } #[doc(hidden)] #[no_coverage] fn is_valid(&self, _value: &$name) -> bool { true } #[doc(hidden)] #[no_coverage] fn validate_value(&self, _value: &$name) -> Option<Self::Cache> { Some(()) } #[doc(hidden)] #[no_coverage] fn default_mutation_step(&self, _value: &$name, _cache: &Self::Cache) -> Self::MutationStep { INITIAL_MUTATION_STEP } #[doc(hidden)] #[no_coverage] fn global_search_space_complexity(&self) -> f64 { <$name>::BITS as f64 } /// The maximum complexity of an input of this type #[doc(hidden)] #[no_coverage] fn max_complexity(&self) -> f64 { <$name>::BITS as f64 } /// The minimum complexity of an input of this type #[doc(hidden)] #[no_coverage] fn min_complexity(&self) -> f64 { <$name>::BITS as f64 } #[doc(hidden)] #[no_coverage] fn complexity(&self, _value: &$name, _cache: &Self::Cache) -> f64 { <$name>::BITS as f64 } #[doc(hidden)] #[no_coverage] fn ordered_arbitrary(&self, step: &mut Self::ArbitraryStep, max_cplx: f64) -> Option<($name, f64)> { if max_cplx < self.min_complexity() { return None; } if *step > <$name_unsigned>::MAX as u64 { None } else { let value = self.uniform_permutation(*step) as $name; *step += 1; Some((value, <$name>::BITS as f64)) } } #[doc(hidden)] #[no_coverage] fn random_arbitrary(&self, _max_cplx: f64) -> ($name, f64) { let value = self.rng.$name(..); (value, <$name>::BITS as f64) } #[doc(hidden)] #[no_coverage] fn ordered_mutate( &self, value: &mut $name, _cache: &mut Self::Cache, step: &mut Self::MutationStep, _subvalue_provider: &dyn crate::SubValueProvider, max_cplx: f64, ) -> Option<(Self::UnmutateToken, f64)> { if max_cplx < self.min_complexity() { return None; } if *step > 10u64.saturating_add(<$name>::MAX as u64) { return None; } let token = *value; *value = { let mut tmp_step = *step; if tmp_step < 8 { let nudge = (tmp_step + 2) as $name; if nudge % 2 == 0 { value.wrapping_add(nudge / 2) } else { value.wrapping_sub(nudge / 2) } } else { tmp_step -= 7; self.uniform_permutation(tmp_step) as $name } }; *step = step.wrapping_add(1); Some((token, <$name>::BITS as f64)) } #[doc(hidden)] #[no_coverage] fn random_mutate( &self, value: &mut $name, _cache: &mut Self::Cache, _max_cplx: f64, ) -> (Self::UnmutateToken, f64) { (std::mem::replace(value, self.rng.$name(..)), <$name>::BITS as f64) } #[doc(hidden)] #[no_coverage] fn unmutate(&self, value: &mut $name, _cache: &mut Self::Cache, t: Self::UnmutateToken) { *value = t; } #[doc(hidden)] #[no_coverage] fn visit_subvalues<'a>( &self, _value: &'a $name, _cache: &'a Self::Cache, _visit: &mut dyn FnMut(&'a dyn Any, f64), ) { } } impl DefaultMutator for $name { type Mutator = $name_mutator; #[no_coverage] fn default_mutator() -> Self::Mutator { <$name_mutator>::default() } } }; } impl_int_mutator!(u8, u8, U8Mutator); impl_int_mutator!(u16, u16, U16Mutator); impl_int_mutator!(u32, u32, U32Mutator); impl_int_mutator!(u64, u64, U64Mutator); impl_int_mutator!(usize, usize, USizeMutator); impl_int_mutator!(i8, u8, I8Mutator); impl_int_mutator!(i16, u16, I16Mutator); impl_int_mutator!(i32, u32, I32Mutator); impl_int_mutator!(i64, u64, I64Mutator); impl_int_mutator!(isize, isize, ISizeMutator);
pub use self::as_any::AsAny; pub use self::dyn_iter::DynIter; pub use self::from_bytes::FromBytes; pub use self::id::Id; pub use self::inner_thread::InnerThread; pub use self::map_access::MapAccess; pub use self::network_abuser::NetworkAbuser; pub use self::time::{Tick, Time}; pub mod view_lock; mod as_any; mod dyn_iter; mod from_bytes; mod id; mod inner_thread; mod map_access; mod network_abuser; mod time;
use std::fmt; #[derive(Debug, Clone)] pub struct Registers { pub pc: u16, // Program Counter pub sp: u16, // Stack Pointer pub a: u8, // Accumulator pub f: u8, // Flag Register // General Purpose Flags pub b: u8, pub c: u8, pub d: u8, pub e: u8, pub h: u8, // High pub l: u8, // Low } impl Registers { pub fn init() -> Self { Self { pc: 0x0000, sp: 0xfffe, a: 0x00, f: 0x00, b: 0x00, c: 0x00, d: 0x00, e: 0x00, h: 0x00, l: 0x00, } } } impl Registers { fn get_flag_bit(&self, bit: usize) -> bool { (self.f & ((1 << bit) as u8)) != 0 } fn set_flag_bit(&mut self, bit: usize, val: bool) { if val { self.f |= (1 << bit) as u8; } else { self.f &= 0xff ^ ((1 << bit) as u8); } } pub fn get_z_flag(&self) -> bool { self.get_flag_bit(7) } pub fn set_z_flag(&mut self, val: bool) { self.set_flag_bit(7, val); } pub fn get_n_flag(&self) -> bool { self.get_flag_bit(6) } pub fn set_n_flag(&mut self, val: bool) { self.set_flag_bit(6, val); } pub fn get_h_flag(&self) -> bool { self.get_flag_bit(5) } pub fn set_h_flag(&mut self, val: bool) { self.set_flag_bit(5, val); } pub fn get_c_flag(&self) -> bool { self.get_flag_bit(4) } pub fn set_c_flag(&mut self, val: bool) { self.set_flag_bit(4, val); } } impl Registers { // Getting 16 bit values pub fn get_af(&self) -> u16 { ((self.a as u16) << 8) | (self.f as u16) } pub fn get_bc(&self) -> u16 { ((self.b as u16) << 8) | (self.c as u16) } pub fn get_de(&self) -> u16 { ((self.d as u16) << 8) | (self.e as u16) } pub fn get_hl(&self) -> u16 { ((self.h as u16) << 8) | (self.l as u16) } // Setting 16 bit values pub fn set_af(&mut self, val: u16) { self.a = ((val >> 8) & 0xff) as u8; self.f = ((val >> 0) & 0xff) as u8; } pub fn set_bc(&mut self, val: u16) { self.b = ((val >> 8) & 0xff) as u8; self.c = ((val >> 0) & 0xff) as u8; } pub fn set_de(&mut self, val: u16) { self.d = ((val >> 8) & 0xff) as u8; self.e = ((val >> 0) & 0xff) as u8; } pub fn set_hl(&mut self, val: u16) { self.h = ((val >> 8) & 0xff) as u8; self.l = ((val >> 0) & 0xff) as u8; } } impl fmt::Display for Registers { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "[pc: {:#06x}, sp: {:#06x}, a: {:#04x}, f: {:#04x}, b: {:#04x}, c: {:#04x}, d: {:#04x}, e: {:#04x}, h: {:#04x}, l: {:#04x}]", self.pc, self.sp, self.a, self.f, self.b, self.c, self.d, self.e, self.h, self.l ) } }
// Box // adalah tipe pointer u/ mengalokasi heap(tumpukan) // menyediakan bentuk yang paling sederhana dari pengalokasikan heap di rust. // Box menyediakan ownership untuk alokasi ini, dan drop isinya // saat mereka keluar dari scope(lingkup) // use std::boxed::Box; fn main() { let slot = Box::new(3); helper(&slot); helper(&slot); example(); } fn helper(slot: &Box<i32>) { println!("The number was: {}", slot); } fn example() { let val: u8 = 5; let boxed: Box<u8> = Box::new(val); println!("{:?}", boxed); }
pub mod init; mod low_level; mod command; use dma; use embed_stm::sdmmc::Sdmmc; /// SD handle // represents SD_HandleTypeDef pub struct SdHandle { registers: &'static mut Sdmmc, lock_type: LockType, rx_dma_transfer: dma::DmaTransfer, tx_dma_transfer: dma::DmaTransfer, context: Context, state: State, error_code: low_level::SdmmcErrorCode, sd_card: CardInfo, } // represents Status #[derive(Debug, PartialEq, Eq)] // TODO: remove pub pub enum Status { Ok = 0x0, Error = 0x1, Busy = 0x2, Timeout = 0x3, } // represents HAL_LockTypeDef #[derive(Debug, PartialEq, Eq)] enum LockType { Locked, Unlocked, } // represents a group of defines in stm32f7xx_hal_sd.h, e.g. SD_CONTEXT_NONE /// Context decribes which kind of operation is to be performed #[derive(Debug, PartialEq, Eq)] enum Context { None = 0x0, //TODO: No response or no data ?? ReadSingleBlock = 0x01, ReadMultipleBlocks = 0x02, WriteSingleBlock = 0x10, WriteMultipleBlocks = 0x20, InterruptMode = 0x08, DmaMode = 0x80, } // represents HAL_SD_StateTypeDef #[derive(Debug, PartialEq, Eq)] enum State { Reset = 0x0, Ready = 0x1, Timeout = 0x2, Busy = 0x3, Programming = 0x4, Receiving = 0x5, Transfer = 0x6, Error = 0xF, } impl State { fn to_str(&self) -> &str { match *self { State::Reset => "Reset", State::Ready => "Ready", State::Timeout => "Timeout", State::Busy => "Busy", State::Programming => "Programming", State::Receiving => "Receiving", State::Transfer => "Transfer", State::Error => "Error", } } } // represents HAL_SD_CardInfoTypeDef #[derive(Debug, PartialEq, Eq)] struct CardInfo { card_type: CardType, version: CardVersion, class: u16, // einfach Resp2 >> 20 relative_card_address: u16, number_of_blocks: usize, block_size: usize, logical_number_of_blocks: usize, logical_block_size: usize, cid: [u32; 4], // Card indentification number data csd: [u32; 4], // Card specific data } impl CardInfo { pub fn new() -> CardInfo { CardInfo { card_type: CardType::Sdsc, version: CardVersion::V1x, class: 0, relative_card_address: 0x0, number_of_blocks: 0, block_size: 0, logical_number_of_blocks: 0, logical_block_size: 0, cid: [0, 0, 0, 0], csd: [0, 0, 0, 0], } } } // represents a group of defines in stm32f7xx_hal_sd.h, e.g. CARD_SDSC #[derive(Debug, PartialEq, Eq)] enum CardType { Sdsc = 0, SdhcSdxc = 1, Secured = 3, } #[derive(Debug, PartialEq, Eq, Copy, Clone)] pub enum CardCapacity { High = 0x4000_0000, Standard = 0x0, } #[derive(Debug, PartialEq, Eq)] enum CardVersion { V1x = 0b0, V2x = 0b1, } /// Bus modes that can be selected via the clkcr register #[derive(Debug, PartialEq, Eq)] pub enum BusMode { Default = 0b00, Wide4 = 0b01, Wide8 = 0b10, } #[derive(Debug, PartialEq, Eq)] enum PowerSupply { Off = 0b00, On = 0b11, } /// Possible values of the `WaitResp` field in the command register #[derive(Debug, PartialEq, Eq)] //TODO: remove 'pub' pub enum WaitResp { No = 0b00, Short = 0b01, Long = 0b11, } #[derive(Debug, PartialEq, Eq)] // TODO: remove pub pub enum CardState { Idle = 0, Ready = 1, Ident = 2, } impl SdHandle { /// Bus can be 1, 4 or 8 bits wide. // represents HAL_SD_ConfigWideBusOperation pub fn set_bus_operation_mode(&mut self, mode: BusMode) -> Status { self.state = State::Busy; if self.sd_card.card_type != CardType::Secured { match mode { BusMode::Wide8 => self.error_code |= low_level::UNSUPPORTED_FEATURE, BusMode::Wide4 => self.error_code |= self.enable_wide_bus(), BusMode::Default => self.error_code |= self.disable_wide_bus(), } } else { // secured cards do not support wide bus feature self.error_code |= low_level::UNSUPPORTED_FEATURE; } if self.error_code == low_level::NONE { // Configure SDMMC peripheral self.registers.clkcr.update(|clkcr| clkcr.set_widbus(mode as u8)); } else { self.clear_all_static_status_flags(); self.state = State::Ready; return Status::Error; } self.state = State::Ready; Status::Ok } /// enable 4-bit wide bus mode fn enable_wide_bus(&mut self) -> low_level::SdmmcErrorCode { unimplemented!(); } /// disable 4-bit wide bus mode -> set 1-bit mode fn disable_wide_bus(&mut self) -> low_level::SdmmcErrorCode { unimplemented!(); } fn clear_all_static_status_flags(&mut self) { // clear all static flags -> all flags in SDMMC_ICR except SDIOIT, CEATAEND and STBITERR self.registers.icr.update(|icr| { icr.set_dbckendc(true); icr.set_dataendc(true); icr.set_cmdsentc(true); icr.set_cmdrendc(true); icr.set_rxoverrc(true); icr.set_txunderrc(true); icr.set_dtimeoutc(true); icr.set_ctimeoutc(true); icr.set_dcrcfailc(true); icr.set_ccrcfailc(true); }); } }
const X: i32 = 10; pub fn print() { println!("lib::print {}", X) }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] pub const DFS_ADD_VOLUME: u32 = 1u32; pub const DFS_FORCE_REMOVE: u32 = 2147483648u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_GET_PKT_ENTRY_STATE_ARG { pub DfsEntryPathLen: u16, pub ServerNameLen: u16, pub ShareNameLen: u16, pub Level: u32, pub Buffer: [u16; 1], } impl DFS_GET_PKT_ENTRY_STATE_ARG {} impl ::core::default::Default for DFS_GET_PKT_ENTRY_STATE_ARG { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_GET_PKT_ENTRY_STATE_ARG { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_GET_PKT_ENTRY_STATE_ARG").field("DfsEntryPathLen", &self.DfsEntryPathLen).field("ServerNameLen", &self.ServerNameLen).field("ShareNameLen", &self.ShareNameLen).field("Level", &self.Level).field("Buffer", &self.Buffer).finish() } } impl ::core::cmp::PartialEq for DFS_GET_PKT_ENTRY_STATE_ARG { fn eq(&self, other: &Self) -> bool { self.DfsEntryPathLen == other.DfsEntryPathLen && self.ServerNameLen == other.ServerNameLen && self.ShareNameLen == other.ShareNameLen && self.Level == other.Level && self.Buffer == other.Buffer } } impl ::core::cmp::Eq for DFS_GET_PKT_ENTRY_STATE_ARG {} unsafe impl ::windows::core::Abi for DFS_GET_PKT_ENTRY_STATE_ARG { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_1 { pub EntryPath: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_1 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_1 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_1").field("EntryPath", &self.EntryPath).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_1 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_1 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_1 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_100 { pub Comment: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_100 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_100 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_100 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_100").field("Comment", &self.Comment).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_100 { fn eq(&self, other: &Self) -> bool { self.Comment == other.Comment } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_100 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_100 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_INFO_101 { pub State: u32, } impl DFS_INFO_101 {} impl ::core::default::Default for DFS_INFO_101 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_INFO_101 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_101").field("State", &self.State).finish() } } impl ::core::cmp::PartialEq for DFS_INFO_101 { fn eq(&self, other: &Self) -> bool { self.State == other.State } } impl ::core::cmp::Eq for DFS_INFO_101 {} unsafe impl ::windows::core::Abi for DFS_INFO_101 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_INFO_102 { pub Timeout: u32, } impl DFS_INFO_102 {} impl ::core::default::Default for DFS_INFO_102 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_INFO_102 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_102").field("Timeout", &self.Timeout).finish() } } impl ::core::cmp::PartialEq for DFS_INFO_102 { fn eq(&self, other: &Self) -> bool { self.Timeout == other.Timeout } } impl ::core::cmp::Eq for DFS_INFO_102 {} unsafe impl ::windows::core::Abi for DFS_INFO_102 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_INFO_103 { pub PropertyFlagMask: u32, pub PropertyFlags: u32, } impl DFS_INFO_103 {} impl ::core::default::Default for DFS_INFO_103 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_INFO_103 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_103").field("PropertyFlagMask", &self.PropertyFlagMask).field("PropertyFlags", &self.PropertyFlags).finish() } } impl ::core::cmp::PartialEq for DFS_INFO_103 { fn eq(&self, other: &Self) -> bool { self.PropertyFlagMask == other.PropertyFlagMask && self.PropertyFlags == other.PropertyFlags } } impl ::core::cmp::Eq for DFS_INFO_103 {} unsafe impl ::windows::core::Abi for DFS_INFO_103 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_INFO_104 { pub TargetPriority: DFS_TARGET_PRIORITY, } impl DFS_INFO_104 {} impl ::core::default::Default for DFS_INFO_104 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_INFO_104 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_104").field("TargetPriority", &self.TargetPriority).finish() } } impl ::core::cmp::PartialEq for DFS_INFO_104 { fn eq(&self, other: &Self) -> bool { self.TargetPriority == other.TargetPriority } } impl ::core::cmp::Eq for DFS_INFO_104 {} unsafe impl ::windows::core::Abi for DFS_INFO_104 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_105 { pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub PropertyFlagMask: u32, pub PropertyFlags: u32, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_105 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_105 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_105 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_105").field("Comment", &self.Comment).field("State", &self.State).field("Timeout", &self.Timeout).field("PropertyFlagMask", &self.PropertyFlagMask).field("PropertyFlags", &self.PropertyFlags).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_105 { fn eq(&self, other: &Self) -> bool { self.Comment == other.Comment && self.State == other.State && self.Timeout == other.Timeout && self.PropertyFlagMask == other.PropertyFlagMask && self.PropertyFlags == other.PropertyFlags } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_105 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_105 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_INFO_106 { pub State: u32, pub TargetPriority: DFS_TARGET_PRIORITY, } impl DFS_INFO_106 {} impl ::core::default::Default for DFS_INFO_106 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_INFO_106 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_106").field("State", &self.State).field("TargetPriority", &self.TargetPriority).finish() } } impl ::core::cmp::PartialEq for DFS_INFO_106 { fn eq(&self, other: &Self) -> bool { self.State == other.State && self.TargetPriority == other.TargetPriority } } impl ::core::cmp::Eq for DFS_INFO_106 {} unsafe impl ::windows::core::Abi for DFS_INFO_106 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct DFS_INFO_107 { pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub PropertyFlagMask: u32, pub PropertyFlags: u32, pub SdLengthReserved: u32, pub pSecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl DFS_INFO_107 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::default::Default for DFS_INFO_107 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::fmt::Debug for DFS_INFO_107 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_107") .field("Comment", &self.Comment) .field("State", &self.State) .field("Timeout", &self.Timeout) .field("PropertyFlagMask", &self.PropertyFlagMask) .field("PropertyFlags", &self.PropertyFlags) .field("SdLengthReserved", &self.SdLengthReserved) .field("pSecurityDescriptor", &self.pSecurityDescriptor) .finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::PartialEq for DFS_INFO_107 { fn eq(&self, other: &Self) -> bool { self.Comment == other.Comment && self.State == other.State && self.Timeout == other.Timeout && self.PropertyFlagMask == other.PropertyFlagMask && self.PropertyFlags == other.PropertyFlags && self.SdLengthReserved == other.SdLengthReserved && self.pSecurityDescriptor == other.pSecurityDescriptor } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::Eq for DFS_INFO_107 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] unsafe impl ::windows::core::Abi for DFS_INFO_107 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct DFS_INFO_150 { pub SdLengthReserved: u32, pub pSecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl DFS_INFO_150 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::default::Default for DFS_INFO_150 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::fmt::Debug for DFS_INFO_150 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_150").field("SdLengthReserved", &self.SdLengthReserved).field("pSecurityDescriptor", &self.pSecurityDescriptor).finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::PartialEq for DFS_INFO_150 { fn eq(&self, other: &Self) -> bool { self.SdLengthReserved == other.SdLengthReserved && self.pSecurityDescriptor == other.pSecurityDescriptor } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::Eq for DFS_INFO_150 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] unsafe impl ::windows::core::Abi for DFS_INFO_150 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_INFO_1_32 { pub EntryPath: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl DFS_INFO_1_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for DFS_INFO_1_32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for DFS_INFO_1_32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_1_32").field("EntryPath", &self.EntryPath).finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for DFS_INFO_1_32 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for DFS_INFO_1_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for DFS_INFO_1_32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_2 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub NumberOfStorages: u32, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_2 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_2 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_2 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_2").field("EntryPath", &self.EntryPath).field("Comment", &self.Comment).field("State", &self.State).field("NumberOfStorages", &self.NumberOfStorages).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_2 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.NumberOfStorages == other.NumberOfStorages } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_2 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_2 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_200 { pub FtDfsName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_200 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_200 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_200 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_200").field("FtDfsName", &self.FtDfsName).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_200 { fn eq(&self, other: &Self) -> bool { self.FtDfsName == other.FtDfsName } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_200 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_200 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_INFO_2_32 { pub EntryPath: u32, pub Comment: u32, pub State: u32, pub NumberOfStorages: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl DFS_INFO_2_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for DFS_INFO_2_32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for DFS_INFO_2_32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_2_32").field("EntryPath", &self.EntryPath).field("Comment", &self.Comment).field("State", &self.State).field("NumberOfStorages", &self.NumberOfStorages).finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for DFS_INFO_2_32 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.NumberOfStorages == other.NumberOfStorages } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for DFS_INFO_2_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for DFS_INFO_2_32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_3 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub NumberOfStorages: u32, pub Storage: *mut DFS_STORAGE_INFO, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_3 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_3 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_3 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_3").field("EntryPath", &self.EntryPath).field("Comment", &self.Comment).field("State", &self.State).field("NumberOfStorages", &self.NumberOfStorages).field("Storage", &self.Storage).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_3 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.NumberOfStorages == other.NumberOfStorages && self.Storage == other.Storage } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_3 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_3 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_300 { pub Flags: u32, pub DfsName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_300 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_300 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_300 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_300").field("Flags", &self.Flags).field("DfsName", &self.DfsName).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_300 { fn eq(&self, other: &Self) -> bool { self.Flags == other.Flags && self.DfsName == other.DfsName } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_300 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_300 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_INFO_3_32 { pub EntryPath: u32, pub Comment: u32, pub State: u32, pub NumberOfStorages: u32, pub Storage: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl DFS_INFO_3_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for DFS_INFO_3_32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for DFS_INFO_3_32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_3_32").field("EntryPath", &self.EntryPath).field("Comment", &self.Comment).field("State", &self.State).field("NumberOfStorages", &self.NumberOfStorages).field("Storage", &self.Storage).finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for DFS_INFO_3_32 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.NumberOfStorages == other.NumberOfStorages && self.Storage == other.Storage } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for DFS_INFO_3_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for DFS_INFO_3_32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_4 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows::core::GUID, pub NumberOfStorages: u32, pub Storage: *mut DFS_STORAGE_INFO, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_4 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_4 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_4 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_4").field("EntryPath", &self.EntryPath).field("Comment", &self.Comment).field("State", &self.State).field("Timeout", &self.Timeout).field("Guid", &self.Guid).field("NumberOfStorages", &self.NumberOfStorages).field("Storage", &self.Storage).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_4 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.Timeout == other.Timeout && self.Guid == other.Guid && self.NumberOfStorages == other.NumberOfStorages && self.Storage == other.Storage } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_4 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_4 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_INFO_4_32 { pub EntryPath: u32, pub Comment: u32, pub State: u32, pub Timeout: u32, pub Guid: ::windows::core::GUID, pub NumberOfStorages: u32, pub Storage: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl DFS_INFO_4_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for DFS_INFO_4_32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for DFS_INFO_4_32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_4_32").field("EntryPath", &self.EntryPath).field("Comment", &self.Comment).field("State", &self.State).field("Timeout", &self.Timeout).field("Guid", &self.Guid).field("NumberOfStorages", &self.NumberOfStorages).field("Storage", &self.Storage).finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for DFS_INFO_4_32 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.Timeout == other.Timeout && self.Guid == other.Guid && self.NumberOfStorages == other.NumberOfStorages && self.Storage == other.Storage } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for DFS_INFO_4_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for DFS_INFO_4_32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_5 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows::core::GUID, pub PropertyFlags: u32, pub MetadataSize: u32, pub NumberOfStorages: u32, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_5 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_5 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_5 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_5") .field("EntryPath", &self.EntryPath) .field("Comment", &self.Comment) .field("State", &self.State) .field("Timeout", &self.Timeout) .field("Guid", &self.Guid) .field("PropertyFlags", &self.PropertyFlags) .field("MetadataSize", &self.MetadataSize) .field("NumberOfStorages", &self.NumberOfStorages) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_5 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.Timeout == other.Timeout && self.Guid == other.Guid && self.PropertyFlags == other.PropertyFlags && self.MetadataSize == other.MetadataSize && self.NumberOfStorages == other.NumberOfStorages } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_5 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_5 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_INFO_50 { pub NamespaceMajorVersion: u32, pub NamespaceMinorVersion: u32, pub NamespaceCapabilities: u64, } impl DFS_INFO_50 {} impl ::core::default::Default for DFS_INFO_50 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_INFO_50 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_50").field("NamespaceMajorVersion", &self.NamespaceMajorVersion).field("NamespaceMinorVersion", &self.NamespaceMinorVersion).field("NamespaceCapabilities", &self.NamespaceCapabilities).finish() } } impl ::core::cmp::PartialEq for DFS_INFO_50 { fn eq(&self, other: &Self) -> bool { self.NamespaceMajorVersion == other.NamespaceMajorVersion && self.NamespaceMinorVersion == other.NamespaceMinorVersion && self.NamespaceCapabilities == other.NamespaceCapabilities } } impl ::core::cmp::Eq for DFS_INFO_50 {} unsafe impl ::windows::core::Abi for DFS_INFO_50 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_INFO_6 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows::core::GUID, pub PropertyFlags: u32, pub MetadataSize: u32, pub NumberOfStorages: u32, pub Storage: *mut DFS_STORAGE_INFO_1, } #[cfg(feature = "Win32_Foundation")] impl DFS_INFO_6 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_INFO_6 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_INFO_6 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_6") .field("EntryPath", &self.EntryPath) .field("Comment", &self.Comment) .field("State", &self.State) .field("Timeout", &self.Timeout) .field("Guid", &self.Guid) .field("PropertyFlags", &self.PropertyFlags) .field("MetadataSize", &self.MetadataSize) .field("NumberOfStorages", &self.NumberOfStorages) .field("Storage", &self.Storage) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_INFO_6 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.Timeout == other.Timeout && self.Guid == other.Guid && self.PropertyFlags == other.PropertyFlags && self.MetadataSize == other.MetadataSize && self.NumberOfStorages == other.NumberOfStorages && self.Storage == other.Storage } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_INFO_6 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_INFO_6 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_INFO_7 { pub GenerationGuid: ::windows::core::GUID, } impl DFS_INFO_7 {} impl ::core::default::Default for DFS_INFO_7 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_INFO_7 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_7").field("GenerationGuid", &self.GenerationGuid).finish() } } impl ::core::cmp::PartialEq for DFS_INFO_7 { fn eq(&self, other: &Self) -> bool { self.GenerationGuid == other.GenerationGuid } } impl ::core::cmp::Eq for DFS_INFO_7 {} unsafe impl ::windows::core::Abi for DFS_INFO_7 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct DFS_INFO_8 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows::core::GUID, pub PropertyFlags: u32, pub MetadataSize: u32, pub SdLengthReserved: u32, pub pSecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, pub NumberOfStorages: u32, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl DFS_INFO_8 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::default::Default for DFS_INFO_8 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::fmt::Debug for DFS_INFO_8 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_8") .field("EntryPath", &self.EntryPath) .field("Comment", &self.Comment) .field("State", &self.State) .field("Timeout", &self.Timeout) .field("Guid", &self.Guid) .field("PropertyFlags", &self.PropertyFlags) .field("MetadataSize", &self.MetadataSize) .field("SdLengthReserved", &self.SdLengthReserved) .field("pSecurityDescriptor", &self.pSecurityDescriptor) .field("NumberOfStorages", &self.NumberOfStorages) .finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::PartialEq for DFS_INFO_8 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.Timeout == other.Timeout && self.Guid == other.Guid && self.PropertyFlags == other.PropertyFlags && self.MetadataSize == other.MetadataSize && self.SdLengthReserved == other.SdLengthReserved && self.pSecurityDescriptor == other.pSecurityDescriptor && self.NumberOfStorages == other.NumberOfStorages } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::Eq for DFS_INFO_8 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] unsafe impl ::windows::core::Abi for DFS_INFO_8 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] pub struct DFS_INFO_9 { pub EntryPath: super::super::Foundation::PWSTR, pub Comment: super::super::Foundation::PWSTR, pub State: u32, pub Timeout: u32, pub Guid: ::windows::core::GUID, pub PropertyFlags: u32, pub MetadataSize: u32, pub SdLengthReserved: u32, pub pSecurityDescriptor: *mut super::super::Security::SECURITY_DESCRIPTOR, pub NumberOfStorages: u32, pub Storage: *mut DFS_STORAGE_INFO_1, } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl DFS_INFO_9 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::default::Default for DFS_INFO_9 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::fmt::Debug for DFS_INFO_9 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_INFO_9") .field("EntryPath", &self.EntryPath) .field("Comment", &self.Comment) .field("State", &self.State) .field("Timeout", &self.Timeout) .field("Guid", &self.Guid) .field("PropertyFlags", &self.PropertyFlags) .field("MetadataSize", &self.MetadataSize) .field("SdLengthReserved", &self.SdLengthReserved) .field("pSecurityDescriptor", &self.pSecurityDescriptor) .field("NumberOfStorages", &self.NumberOfStorages) .field("Storage", &self.Storage) .finish() } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::PartialEq for DFS_INFO_9 { fn eq(&self, other: &Self) -> bool { self.EntryPath == other.EntryPath && self.Comment == other.Comment && self.State == other.State && self.Timeout == other.Timeout && self.Guid == other.Guid && self.PropertyFlags == other.PropertyFlags && self.MetadataSize == other.MetadataSize && self.SdLengthReserved == other.SdLengthReserved && self.pSecurityDescriptor == other.pSecurityDescriptor && self.NumberOfStorages == other.NumberOfStorages && self.Storage == other.Storage } } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] impl ::core::cmp::Eq for DFS_INFO_9 {} #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] unsafe impl ::windows::core::Abi for DFS_INFO_9 { type Abi = Self; } pub const DFS_MOVE_FLAG_REPLACE_IF_EXISTS: u32 = 1u32; #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DFS_NAMESPACE_VERSION_ORIGIN(pub i32); pub const DFS_NAMESPACE_VERSION_ORIGIN_COMBINED: DFS_NAMESPACE_VERSION_ORIGIN = DFS_NAMESPACE_VERSION_ORIGIN(0i32); pub const DFS_NAMESPACE_VERSION_ORIGIN_SERVER: DFS_NAMESPACE_VERSION_ORIGIN = DFS_NAMESPACE_VERSION_ORIGIN(1i32); pub const DFS_NAMESPACE_VERSION_ORIGIN_DOMAIN: DFS_NAMESPACE_VERSION_ORIGIN = DFS_NAMESPACE_VERSION_ORIGIN(2i32); impl ::core::convert::From<i32> for DFS_NAMESPACE_VERSION_ORIGIN { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DFS_NAMESPACE_VERSION_ORIGIN { type Abi = Self; } pub const DFS_PROPERTY_FLAG_ABDE: u32 = 32u32; pub const DFS_PROPERTY_FLAG_CLUSTER_ENABLED: u32 = 16u32; pub const DFS_PROPERTY_FLAG_INSITE_REFERRALS: u32 = 1u32; pub const DFS_PROPERTY_FLAG_ROOT_SCALABILITY: u32 = 2u32; pub const DFS_PROPERTY_FLAG_SITE_COSTING: u32 = 4u32; pub const DFS_PROPERTY_FLAG_TARGET_FAILBACK: u32 = 8u32; pub const DFS_RESTORE_VOLUME: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_SITELIST_INFO { pub cSites: u32, pub Site: [DFS_SITENAME_INFO; 1], } #[cfg(feature = "Win32_Foundation")] impl DFS_SITELIST_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_SITELIST_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_SITELIST_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_SITELIST_INFO").field("cSites", &self.cSites).field("Site", &self.Site).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_SITELIST_INFO { fn eq(&self, other: &Self) -> bool { self.cSites == other.cSites && self.Site == other.Site } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_SITELIST_INFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_SITELIST_INFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_SITENAME_INFO { pub SiteFlags: u32, pub SiteName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DFS_SITENAME_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_SITENAME_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_SITENAME_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_SITENAME_INFO").field("SiteFlags", &self.SiteFlags).field("SiteName", &self.SiteName).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_SITENAME_INFO { fn eq(&self, other: &Self) -> bool { self.SiteFlags == other.SiteFlags && self.SiteName == other.SiteName } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_SITENAME_INFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_SITENAME_INFO { type Abi = Self; } pub const DFS_SITE_PRIMARY: u32 = 1u32; pub const DFS_STORAGE_FLAVOR_UNUSED2: u32 = 768u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_STORAGE_INFO { pub State: u32, pub ServerName: super::super::Foundation::PWSTR, pub ShareName: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl DFS_STORAGE_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_STORAGE_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_STORAGE_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_STORAGE_INFO").field("State", &self.State).field("ServerName", &self.ServerName).field("ShareName", &self.ShareName).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_STORAGE_INFO { fn eq(&self, other: &Self) -> bool { self.State == other.State && self.ServerName == other.ServerName && self.ShareName == other.ShareName } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_STORAGE_INFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_STORAGE_INFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] pub struct DFS_STORAGE_INFO_0_32 { pub State: u32, pub ServerName: u32, pub ShareName: u32, } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl DFS_STORAGE_INFO_0_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::default::Default for DFS_STORAGE_INFO_0_32 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::fmt::Debug for DFS_STORAGE_INFO_0_32 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_STORAGE_INFO_0_32").field("State", &self.State).field("ServerName", &self.ServerName).field("ShareName", &self.ShareName).finish() } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::PartialEq for DFS_STORAGE_INFO_0_32 { fn eq(&self, other: &Self) -> bool { self.State == other.State && self.ServerName == other.ServerName && self.ShareName == other.ShareName } } #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] impl ::core::cmp::Eq for DFS_STORAGE_INFO_0_32 {} #[cfg(any(target_arch = "x86_64", target_arch = "aarch64",))] unsafe impl ::windows::core::Abi for DFS_STORAGE_INFO_0_32 { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct DFS_STORAGE_INFO_1 { pub State: u32, pub ServerName: super::super::Foundation::PWSTR, pub ShareName: super::super::Foundation::PWSTR, pub TargetPriority: DFS_TARGET_PRIORITY, } #[cfg(feature = "Win32_Foundation")] impl DFS_STORAGE_INFO_1 {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for DFS_STORAGE_INFO_1 { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for DFS_STORAGE_INFO_1 { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_STORAGE_INFO_1").field("State", &self.State).field("ServerName", &self.ServerName).field("ShareName", &self.ShareName).field("TargetPriority", &self.TargetPriority).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for DFS_STORAGE_INFO_1 { fn eq(&self, other: &Self) -> bool { self.State == other.State && self.ServerName == other.ServerName && self.ShareName == other.ShareName && self.TargetPriority == other.TargetPriority } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for DFS_STORAGE_INFO_1 {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for DFS_STORAGE_INFO_1 { type Abi = Self; } pub const DFS_STORAGE_STATES: u32 = 15u32; pub const DFS_STORAGE_STATE_ACTIVE: u32 = 4u32; pub const DFS_STORAGE_STATE_OFFLINE: u32 = 1u32; pub const DFS_STORAGE_STATE_ONLINE: u32 = 2u32; #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_SUPPORTED_NAMESPACE_VERSION_INFO { pub DomainDfsMajorVersion: u32, pub DomainDfsMinorVersion: u32, pub DomainDfsCapabilities: u64, pub StandaloneDfsMajorVersion: u32, pub StandaloneDfsMinorVersion: u32, pub StandaloneDfsCapabilities: u64, } impl DFS_SUPPORTED_NAMESPACE_VERSION_INFO {} impl ::core::default::Default for DFS_SUPPORTED_NAMESPACE_VERSION_INFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_SUPPORTED_NAMESPACE_VERSION_INFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_SUPPORTED_NAMESPACE_VERSION_INFO") .field("DomainDfsMajorVersion", &self.DomainDfsMajorVersion) .field("DomainDfsMinorVersion", &self.DomainDfsMinorVersion) .field("DomainDfsCapabilities", &self.DomainDfsCapabilities) .field("StandaloneDfsMajorVersion", &self.StandaloneDfsMajorVersion) .field("StandaloneDfsMinorVersion", &self.StandaloneDfsMinorVersion) .field("StandaloneDfsCapabilities", &self.StandaloneDfsCapabilities) .finish() } } impl ::core::cmp::PartialEq for DFS_SUPPORTED_NAMESPACE_VERSION_INFO { fn eq(&self, other: &Self) -> bool { self.DomainDfsMajorVersion == other.DomainDfsMajorVersion && self.DomainDfsMinorVersion == other.DomainDfsMinorVersion && self.DomainDfsCapabilities == other.DomainDfsCapabilities && self.StandaloneDfsMajorVersion == other.StandaloneDfsMajorVersion && self.StandaloneDfsMinorVersion == other.StandaloneDfsMinorVersion && self.StandaloneDfsCapabilities == other.StandaloneDfsCapabilities } } impl ::core::cmp::Eq for DFS_SUPPORTED_NAMESPACE_VERSION_INFO {} unsafe impl ::windows::core::Abi for DFS_SUPPORTED_NAMESPACE_VERSION_INFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct DFS_TARGET_PRIORITY { pub TargetPriorityClass: DFS_TARGET_PRIORITY_CLASS, pub TargetPriorityRank: u16, pub Reserved: u16, } impl DFS_TARGET_PRIORITY {} impl ::core::default::Default for DFS_TARGET_PRIORITY { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for DFS_TARGET_PRIORITY { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("DFS_TARGET_PRIORITY").field("TargetPriorityClass", &self.TargetPriorityClass).field("TargetPriorityRank", &self.TargetPriorityRank).field("Reserved", &self.Reserved).finish() } } impl ::core::cmp::PartialEq for DFS_TARGET_PRIORITY { fn eq(&self, other: &Self) -> bool { self.TargetPriorityClass == other.TargetPriorityClass && self.TargetPriorityRank == other.TargetPriorityRank && self.Reserved == other.Reserved } } impl ::core::cmp::Eq for DFS_TARGET_PRIORITY {} unsafe impl ::windows::core::Abi for DFS_TARGET_PRIORITY { type Abi = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct DFS_TARGET_PRIORITY_CLASS(pub i32); pub const DfsInvalidPriorityClass: DFS_TARGET_PRIORITY_CLASS = DFS_TARGET_PRIORITY_CLASS(-1i32); pub const DfsSiteCostNormalPriorityClass: DFS_TARGET_PRIORITY_CLASS = DFS_TARGET_PRIORITY_CLASS(0i32); pub const DfsGlobalHighPriorityClass: DFS_TARGET_PRIORITY_CLASS = DFS_TARGET_PRIORITY_CLASS(1i32); pub const DfsSiteCostHighPriorityClass: DFS_TARGET_PRIORITY_CLASS = DFS_TARGET_PRIORITY_CLASS(2i32); pub const DfsSiteCostLowPriorityClass: DFS_TARGET_PRIORITY_CLASS = DFS_TARGET_PRIORITY_CLASS(3i32); pub const DfsGlobalLowPriorityClass: DFS_TARGET_PRIORITY_CLASS = DFS_TARGET_PRIORITY_CLASS(4i32); impl ::core::convert::From<i32> for DFS_TARGET_PRIORITY_CLASS { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for DFS_TARGET_PRIORITY_CLASS { type Abi = Self; } pub const DFS_VOLUME_FLAVORS: u32 = 768u32; pub const DFS_VOLUME_FLAVOR_AD_BLOB: u32 = 512u32; pub const DFS_VOLUME_FLAVOR_STANDALONE: u32 = 256u32; pub const DFS_VOLUME_FLAVOR_UNUSED1: u32 = 0u32; pub const DFS_VOLUME_STATES: u32 = 15u32; pub const DFS_VOLUME_STATE_FORCE_SYNC: u32 = 64u32; pub const DFS_VOLUME_STATE_INCONSISTENT: u32 = 2u32; pub const DFS_VOLUME_STATE_OFFLINE: u32 = 3u32; pub const DFS_VOLUME_STATE_OK: u32 = 1u32; pub const DFS_VOLUME_STATE_ONLINE: u32 = 4u32; pub const DFS_VOLUME_STATE_RESYNCHRONIZE: u32 = 16u32; pub const DFS_VOLUME_STATE_STANDBY: u32 = 32u32; pub const FSCTL_DFS_BASE: u32 = 6u32; pub const FSCTL_DFS_GET_PKT_ENTRY_STATE: u32 = 401340u32; pub const NET_DFS_SETDC_FLAGS: u32 = 0u32; pub const NET_DFS_SETDC_INITPKT: u32 = 2u32; pub const NET_DFS_SETDC_TIMEOUT: u32 = 1u32; #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsAdd<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dfsentrypath: Param0, servername: Param1, sharename: Param2, comment: Param3, flags: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsAdd(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, comment: super::super::Foundation::PWSTR, flags: u32) -> u32; } ::core::mem::transmute(NetDfsAdd(dfsentrypath.into_param().abi(), servername.into_param().abi(), sharename.into_param().abi(), comment.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsAddFtRoot<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(servername: Param0, rootshare: Param1, ftdfsname: Param2, comment: Param3, flags: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsAddFtRoot(servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, ftdfsname: super::super::Foundation::PWSTR, comment: super::super::Foundation::PWSTR, flags: u32) -> u32; } ::core::mem::transmute(NetDfsAddFtRoot(servername.into_param().abi(), rootshare.into_param().abi(), ftdfsname.into_param().abi(), comment.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsAddRootTarget<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(pdfspath: Param0, ptargetpath: Param1, majorversion: u32, pcomment: Param3, flags: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsAddRootTarget(pdfspath: super::super::Foundation::PWSTR, ptargetpath: super::super::Foundation::PWSTR, majorversion: u32, pcomment: super::super::Foundation::PWSTR, flags: u32) -> u32; } ::core::mem::transmute(NetDfsAddRootTarget(pdfspath.into_param().abi(), ptargetpath.into_param().abi(), ::core::mem::transmute(majorversion), pcomment.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsAddStdRoot<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(servername: Param0, rootshare: Param1, comment: Param2, flags: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsAddStdRoot(servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, comment: super::super::Foundation::PWSTR, flags: u32) -> u32; } ::core::mem::transmute(NetDfsAddStdRoot(servername.into_param().abi(), rootshare.into_param().abi(), comment.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsEnum<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dfsname: Param0, level: u32, prefmaxlen: u32, buffer: *mut *mut u8, entriesread: *mut u32, resumehandle: *mut u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsEnum(dfsname: super::super::Foundation::PWSTR, level: u32, prefmaxlen: u32, buffer: *mut *mut u8, entriesread: *mut u32, resumehandle: *mut u32) -> u32; } ::core::mem::transmute(NetDfsEnum(dfsname.into_param().abi(), ::core::mem::transmute(level), ::core::mem::transmute(prefmaxlen), ::core::mem::transmute(buffer), ::core::mem::transmute(entriesread), ::core::mem::transmute(resumehandle))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsGetClientInfo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dfsentrypath: Param0, servername: Param1, sharename: Param2, level: u32, buffer: *mut *mut u8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsGetClientInfo(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, level: u32, buffer: *mut *mut u8) -> u32; } ::core::mem::transmute(NetDfsGetClientInfo(dfsentrypath.into_param().abi(), servername.into_param().abi(), sharename.into_param().abi(), ::core::mem::transmute(level), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] #[inline] pub unsafe fn NetDfsGetFtContainerSecurity<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(domainname: Param0, securityinformation: u32, ppsecuritydescriptor: *mut *mut super::super::Security::SECURITY_DESCRIPTOR, lpcbsecuritydescriptor: *mut u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsGetFtContainerSecurity(domainname: super::super::Foundation::PWSTR, securityinformation: u32, ppsecuritydescriptor: *mut *mut super::super::Security::SECURITY_DESCRIPTOR, lpcbsecuritydescriptor: *mut u32) -> u32; } ::core::mem::transmute(NetDfsGetFtContainerSecurity(domainname.into_param().abi(), ::core::mem::transmute(securityinformation), ::core::mem::transmute(ppsecuritydescriptor), ::core::mem::transmute(lpcbsecuritydescriptor))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsGetInfo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dfsentrypath: Param0, servername: Param1, sharename: Param2, level: u32, buffer: *mut *mut u8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsGetInfo(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, level: u32, buffer: *mut *mut u8) -> u32; } ::core::mem::transmute(NetDfsGetInfo(dfsentrypath.into_param().abi(), servername.into_param().abi(), sharename.into_param().abi(), ::core::mem::transmute(level), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] #[inline] pub unsafe fn NetDfsGetSecurity<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dfsentrypath: Param0, securityinformation: u32, ppsecuritydescriptor: *mut *mut super::super::Security::SECURITY_DESCRIPTOR, lpcbsecuritydescriptor: *mut u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsGetSecurity(dfsentrypath: super::super::Foundation::PWSTR, securityinformation: u32, ppsecuritydescriptor: *mut *mut super::super::Security::SECURITY_DESCRIPTOR, lpcbsecuritydescriptor: *mut u32) -> u32; } ::core::mem::transmute(NetDfsGetSecurity(dfsentrypath.into_param().abi(), ::core::mem::transmute(securityinformation), ::core::mem::transmute(ppsecuritydescriptor), ::core::mem::transmute(lpcbsecuritydescriptor))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] #[inline] pub unsafe fn NetDfsGetStdContainerSecurity<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(machinename: Param0, securityinformation: u32, ppsecuritydescriptor: *mut *mut super::super::Security::SECURITY_DESCRIPTOR, lpcbsecuritydescriptor: *mut u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsGetStdContainerSecurity(machinename: super::super::Foundation::PWSTR, securityinformation: u32, ppsecuritydescriptor: *mut *mut super::super::Security::SECURITY_DESCRIPTOR, lpcbsecuritydescriptor: *mut u32) -> u32; } ::core::mem::transmute(NetDfsGetStdContainerSecurity(machinename.into_param().abi(), ::core::mem::transmute(securityinformation), ::core::mem::transmute(ppsecuritydescriptor), ::core::mem::transmute(lpcbsecuritydescriptor))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsGetSupportedNamespaceVersion<'a, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(origin: DFS_NAMESPACE_VERSION_ORIGIN, pname: Param1, ppversioninfo: *mut *mut DFS_SUPPORTED_NAMESPACE_VERSION_INFO) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsGetSupportedNamespaceVersion(origin: DFS_NAMESPACE_VERSION_ORIGIN, pname: super::super::Foundation::PWSTR, ppversioninfo: *mut *mut DFS_SUPPORTED_NAMESPACE_VERSION_INFO) -> u32; } ::core::mem::transmute(NetDfsGetSupportedNamespaceVersion(::core::mem::transmute(origin), pname.into_param().abi(), ::core::mem::transmute(ppversioninfo))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsMove<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(olddfsentrypath: Param0, newdfsentrypath: Param1, flags: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsMove(olddfsentrypath: super::super::Foundation::PWSTR, newdfsentrypath: super::super::Foundation::PWSTR, flags: u32) -> u32; } ::core::mem::transmute(NetDfsMove(olddfsentrypath.into_param().abi(), newdfsentrypath.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsRemove<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dfsentrypath: Param0, servername: Param1, sharename: Param2) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsRemove(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR) -> u32; } ::core::mem::transmute(NetDfsRemove(dfsentrypath.into_param().abi(), servername.into_param().abi(), sharename.into_param().abi())) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsRemoveFtRoot<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(servername: Param0, rootshare: Param1, ftdfsname: Param2, flags: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsRemoveFtRoot(servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, ftdfsname: super::super::Foundation::PWSTR, flags: u32) -> u32; } ::core::mem::transmute(NetDfsRemoveFtRoot(servername.into_param().abi(), rootshare.into_param().abi(), ftdfsname.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsRemoveFtRootForced<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param3: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(domainname: Param0, servername: Param1, rootshare: Param2, ftdfsname: Param3, flags: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsRemoveFtRootForced(domainname: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, ftdfsname: super::super::Foundation::PWSTR, flags: u32) -> u32; } ::core::mem::transmute(NetDfsRemoveFtRootForced(domainname.into_param().abi(), servername.into_param().abi(), rootshare.into_param().abi(), ftdfsname.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsRemoveRootTarget<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(pdfspath: Param0, ptargetpath: Param1, flags: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsRemoveRootTarget(pdfspath: super::super::Foundation::PWSTR, ptargetpath: super::super::Foundation::PWSTR, flags: u32) -> u32; } ::core::mem::transmute(NetDfsRemoveRootTarget(pdfspath.into_param().abi(), ptargetpath.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsRemoveStdRoot<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(servername: Param0, rootshare: Param1, flags: u32) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsRemoveStdRoot(servername: super::super::Foundation::PWSTR, rootshare: super::super::Foundation::PWSTR, flags: u32) -> u32; } ::core::mem::transmute(NetDfsRemoveStdRoot(servername.into_param().abi(), rootshare.into_param().abi(), ::core::mem::transmute(flags))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsSetClientInfo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dfsentrypath: Param0, servername: Param1, sharename: Param2, level: u32, buffer: *const u8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsSetClientInfo(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, level: u32, buffer: *const u8) -> u32; } ::core::mem::transmute(NetDfsSetClientInfo(dfsentrypath.into_param().abi(), servername.into_param().abi(), sharename.into_param().abi(), ::core::mem::transmute(level), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] #[inline] pub unsafe fn NetDfsSetFtContainerSecurity<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(domainname: Param0, securityinformation: u32, psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsSetFtContainerSecurity(domainname: super::super::Foundation::PWSTR, securityinformation: u32, psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> u32; } ::core::mem::transmute(NetDfsSetFtContainerSecurity(domainname.into_param().abi(), ::core::mem::transmute(securityinformation), ::core::mem::transmute(psecuritydescriptor))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(feature = "Win32_Foundation")] #[inline] pub unsafe fn NetDfsSetInfo<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>, Param2: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dfsentrypath: Param0, servername: Param1, sharename: Param2, level: u32, buffer: *const u8) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsSetInfo(dfsentrypath: super::super::Foundation::PWSTR, servername: super::super::Foundation::PWSTR, sharename: super::super::Foundation::PWSTR, level: u32, buffer: *const u8) -> u32; } ::core::mem::transmute(NetDfsSetInfo(dfsentrypath.into_param().abi(), servername.into_param().abi(), sharename.into_param().abi(), ::core::mem::transmute(level), ::core::mem::transmute(buffer))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] #[inline] pub unsafe fn NetDfsSetSecurity<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(dfsentrypath: Param0, securityinformation: u32, psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsSetSecurity(dfsentrypath: super::super::Foundation::PWSTR, securityinformation: u32, psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> u32; } ::core::mem::transmute(NetDfsSetSecurity(dfsentrypath.into_param().abi(), ::core::mem::transmute(securityinformation), ::core::mem::transmute(psecuritydescriptor))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_Security"))] #[inline] pub unsafe fn NetDfsSetStdContainerSecurity<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::PWSTR>>(machinename: Param0, securityinformation: u32, psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> u32 { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn NetDfsSetStdContainerSecurity(machinename: super::super::Foundation::PWSTR, securityinformation: u32, psecuritydescriptor: *const super::super::Security::SECURITY_DESCRIPTOR) -> u32; } ::core::mem::transmute(NetDfsSetStdContainerSecurity(machinename.into_param().abi(), ::core::mem::transmute(securityinformation), ::core::mem::transmute(psecuritydescriptor))) } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); }
// This file is part of Webb. // Copyright (C) 2021 Webb Technologies Inc. // SPDX-License-Identifier: Apache-2.0 // 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. //! # Anchor Handler Module //! //! Add description #TODO //! //! ## Overview //! //! //! ### Terminology //! //! ### Goals //! //! The anchor handler system in Webb is designed to make the following //! possible: //! //! * Define. //! //! ## Interface //! //! ## Related Modules //! //! * [`System`](../frame_system/index.html) //! * [`Support`](../frame_support/index.html) // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] #[cfg(test)] pub mod mock; #[cfg(test)] mod tests; use frame_support::{ dispatch::DispatchResultWithPostInfo, ensure, traits::{Currency, EnsureOrigin}, }; use frame_system::pallet_prelude::OriginFor; pub use pallet::*; use pallet_anchor::types::{AnchorInspector, AnchorInterface, EdgeMetadata}; use sp_std::prelude::*; use pallet_bridge::types::ResourceId; pub mod types; use types::*; // ChainId is available in both bridge and anchor pallet type ChainId<T> = <T as pallet_anchor::Config>::ChainId; #[frame_support::pallet] pub mod pallet { use super::*; use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*}; use frame_system::pallet_prelude::*; use pallet_anchor::types::{AnchorInspector, EdgeMetadata}; #[pallet::pallet] #[pallet::generate_store(pub(super) trait Store)] pub struct Pallet<T>(PhantomData<T>); #[pallet::config] /// The module configuration trait. pub trait Config: frame_system::Config + pallet_anchor::Config + pallet_bridge::Config { /// The overarching event type. type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>; /// Specifies the origin check provided by the bridge for calls that can /// only be called by the bridge pallet type BridgeOrigin: EnsureOrigin<Self::Origin, Success = Self::AccountId>; /// The currency mechanism. type Currency: Currency<Self::AccountId>; /// Anchor Interface type Anchor: AnchorInterface<Self> + AnchorInspector<Self>; } /// The map of trees to their anchor metadata #[pallet::storage] #[pallet::getter(fn anchor_handlers)] pub type AnchorHandlers<T: Config> = StorageMap<_, Blake2_128Concat, ResourceId, T::TreeId, ValueQuery>; #[pallet::storage] #[pallet::getter(fn update_records)] /// sourceChainID => nonce => Update Record pub type UpdateRecords<T: Config> = StorageDoubleMap< _, Blake2_128Concat, ChainId<T>, Blake2_128Concat, u64, UpdateRecord<T::TreeId, ResourceId, ChainId<T>, T::Element, T::BlockNumber>, ValueQuery, >; #[pallet::storage] #[pallet::getter(fn counts)] /// The number of updates pub(super) type Counts<T: Config> = StorageMap<_, Blake2_128Concat, ChainId<T>, u64, ValueQuery>; #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event<T: Config> { MaintainerSet(T::AccountId, T::AccountId), AnchorCreated, AnchorEdgeAdded, AnchorEdgeUpdated, } #[pallet::error] pub enum Error<T> { /// Access violation. InvalidPermissions, // Anchor handler already exists for specified resource Id. ResourceIsAlreadyAnchored, // Anchor handler doesn't exist for specified resoure Id. AnchorHandlerNotFound, // Source chain Id is not registered. SourceChainIdNotFound, /// Storage overflowed. StorageOverflow, } #[pallet::hooks] impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {} #[pallet::call] impl<T: Config> Pallet<T> { /// This will be called by bridge when proposal to create an /// anchor has been successfully voted on. #[pallet::weight(195_000_000)] pub fn execute_anchor_create_proposal( origin: OriginFor<T>, src_chain_id: ChainId<T>, r_id: ResourceId, max_edges: u32, tree_depth: u8, ) -> DispatchResultWithPostInfo { Self::ensure_bridge_origin(origin)?; Self::create_anchor(src_chain_id, r_id, max_edges, tree_depth) } /// This will be called by bridge when proposal to add/update edge of an /// anchor has been successfully voted on. #[pallet::weight(195_000_000)] pub fn execute_anchor_update_proposal( origin: OriginFor<T>, r_id: ResourceId, anchor_metadata: EdgeMetadata<ChainId<T>, T::Element, T::BlockNumber>, ) -> DispatchResultWithPostInfo { Self::ensure_bridge_origin(origin)?; Self::update_anchor(r_id, anchor_metadata) } } } impl<T: Config> Pallet<T> { fn ensure_bridge_origin(origin: T::Origin) -> DispatchResultWithPostInfo { T::BridgeOrigin::ensure_origin(origin)?; Ok(().into()) } fn create_anchor( src_chain_id: ChainId<T>, r_id: ResourceId, max_edges: u32, tree_depth: u8, ) -> DispatchResultWithPostInfo { ensure!( !AnchorHandlers::<T>::contains_key(r_id), Error::<T>::ResourceIsAlreadyAnchored ); let tree_id = T::Anchor::create(T::AccountId::default(), tree_depth, max_edges)?; AnchorHandlers::<T>::insert(r_id, tree_id); Counts::<T>::insert(src_chain_id, 0); Self::deposit_event(Event::AnchorCreated); Ok(().into()) } fn update_anchor( r_id: ResourceId, anchor_metadata: EdgeMetadata<ChainId<T>, T::Element, T::BlockNumber>, ) -> DispatchResultWithPostInfo { let tree_id = AnchorHandlers::<T>::try_get(r_id).map_err(|_| Error::<T>::AnchorHandlerNotFound)?; let (src_chain_id, merkle_root, block_height) = ( anchor_metadata.src_chain_id, anchor_metadata.root, anchor_metadata.height, ); if T::Anchor::has_edge(tree_id, src_chain_id) { T::Anchor::update_edge(tree_id, src_chain_id, merkle_root, block_height)?; Self::deposit_event(Event::AnchorEdgeUpdated); } else { T::Anchor::add_edge(tree_id, src_chain_id, merkle_root, block_height)?; Self::deposit_event(Event::AnchorEdgeAdded); } let nonce = Counts::<T>::try_get(src_chain_id).map_err(|_| Error::<T>::SourceChainIdNotFound)?; let record = UpdateRecord { tree_id, resource_id: r_id, edge_metadata: anchor_metadata, }; UpdateRecords::<T>::insert(src_chain_id, nonce, record); Counts::<T>::mutate(src_chain_id, |val| -> DispatchResultWithPostInfo { *val = val.checked_add(1).ok_or(Error::<T>::StorageOverflow)?; Ok(().into()) }) } }
use semver::Version; use semver::VersionReq; use semver::ReqParseError; fn fix_exact_version_for_range(range: Option<String>) -> Result<VersionReq, ReqParseError> { range.map(|r| { Version::parse(r.as_str()) .map(|v| VersionReq::exact(&v)) .or_else(|_| VersionReq::parse(r.as_str())) }).unwrap_or(Ok(VersionReq::any())) } pub fn filter_and_sort(versions_strs: Vec<String>, range: Option<String>) -> Result<Vec<Version>, ReqParseError> { fix_exact_version_for_range(range).map(|r| { let mut versions: Vec<Version> = versions_strs.iter() .map(|s| Version::parse(s.as_str())) .filter_map(Result::ok) .filter(|v| r.matches(&v)) .collect(); versions.sort_unstable(); versions }) } #[cfg(test)] mod tests { use super::*; #[test] fn already_sorted() { let input = vec!["1.0.0".to_string(), "1.0.1".to_string(), "1.0.2".to_string()]; let output = vec![Version::parse("1.0.0").unwrap(), Version::parse("1.0.1").unwrap(), Version::parse("1.0.2").unwrap()]; assert_eq!(filter_and_sort(input, None).unwrap(), output); } #[test] fn output_is_sorted() { let input = vec!["2.0.0".to_string(), "1.0.1".to_string(), "1.0.20".to_string()]; let output = vec![Version::parse("1.0.1").unwrap(), Version::parse("1.0.20").unwrap(), Version::parse("2.0.0").unwrap()]; assert_eq!(filter_and_sort(input, None).unwrap(), output); } #[test] fn wrong_versions_ignored() { let input = vec!["2.0.a".to_string(), "1.0.1".to_string(), "1...aiue".to_string()]; let output = vec![Version::parse("1.0.1").unwrap()]; assert_eq!(filter_and_sort(input, None).unwrap(), output); } #[test] fn filter_exact() { let input = vec!["2.0.0".to_string(), "1.0.1".to_string(), "1.0.20".to_string(), "1.1.0".to_string()]; let output = vec![Version::parse("1.0.1").unwrap()]; assert_eq!(filter_and_sort(input, Some("1.0.1".to_string())).unwrap(), output); } #[test] fn filter_explicit_exact() { let input = vec!["2.0.0".to_string(), "1.0.1".to_string(), "1.0.20".to_string(), "1.1.0".to_string()]; let output = vec![Version::parse("1.0.1").unwrap()]; assert_eq!(filter_and_sort(input, Some("=1.0.1".to_string())).unwrap(), output); } #[test] #[should_panic] fn filter_bad_range_error() { let input = vec!["2.0.0".to_string(), "1.0.1".to_string(), "1.0.20".to_string(), "1.1.0".to_string()]; let output = vec![Version::parse("1.0.1").unwrap()]; assert_eq!(filter_and_sort(input, Some("==1.0.1".to_string())).unwrap(), output); } #[test] fn filter_on_wildcard() { let input = vec!["2.0.0".to_string(), "1.0.1".to_string(), "1.0.20".to_string(), "1.1.0".to_string()]; let output = vec![Version::parse("1.0.1").unwrap(), Version::parse("1.0.20").unwrap()]; assert_eq!(filter_and_sort(input, Some("1.0.*".to_string())).unwrap(), output); } }
//! Modfile interface use std::ffi::OsStr; use std::path::Path; use mime::APPLICATION_OCTET_STREAM; use tokio_io::AsyncRead; use url::form_urlencoded; use crate::multipart::{FileSource, FileStream}; use crate::prelude::*; pub use crate::types::mods::{Download, File, FileHash}; /// Interface for the modfiles the authenticated user uploaded. pub struct MyFiles { modio: Modio, } impl MyFiles { pub(crate) fn new(modio: Modio) -> Self { Self { modio } } /// Return all modfiles the authenticated user uploaded. [required: token] /// /// See [Filters and sorting](filters/index.html). pub fn list(&self, filter: &Filter) -> Future<List<File>> { token_required!(self.modio); let mut uri = vec!["/me/files".to_owned()]; let query = filter.to_query_string(); if !query.is_empty() { uri.push(query); } self.modio.get(&uri.join("?")) } /// Provides a stream over all modfiles the authenticated user uploaded. [required: token] /// /// See [Filters and sorting](filters/index.html). pub fn iter(&self, filter: &Filter) -> Stream<File> { token_required!(s self.modio); let mut uri = vec!["/me/files".to_owned()]; let query = filter.to_query_string(); if !query.is_empty() { uri.push(query); } self.modio.stream(&uri.join("?")) } } /// Interface for the modfiles of a mod. pub struct Files { modio: Modio, game: u32, mod_id: u32, } impl Files { pub(crate) fn new(modio: Modio, game: u32, mod_id: u32) -> Self { Self { modio, game, mod_id, } } fn path(&self, more: &str) -> String { format!("/games/{}/mods/{}/files{}", self.game, self.mod_id, more) } /// Return all files that are published for a mod this `Files` refers to. /// /// See [Filters and sorting](filters/index.html). pub fn list(&self, filter: &Filter) -> Future<List<File>> { let mut uri = vec![self.path("")]; let query = filter.to_query_string(); if !query.is_empty() { uri.push(query); } self.modio.get(&uri.join("?")) } /// Provides a stream over all files that are published for a mod this `Files` refers to. /// /// See [Filters and sorting](filters/index.html). pub fn iter(&self, filter: &Filter) -> Stream<File> { let mut uri = vec![self.path("")]; let query = filter.to_query_string(); if !query.is_empty() { uri.push(query); } self.modio.stream(&uri.join("?")) } /// Return a reference to a file. pub fn get(&self, id: u32) -> FileRef { FileRef::new(self.modio.clone(), self.game, self.mod_id, id) } /// Add a file for a mod that this `Files` refers to. [required: token] pub fn add(&self, options: AddFileOptions) -> Future<File> { token_required!(self.modio); self.modio.post_form(&self.path(""), options) } } /// Reference interface of a modfile. pub struct FileRef { modio: Modio, game: u32, mod_id: u32, id: u32, } impl FileRef { pub(crate) fn new(modio: Modio, game: u32, mod_id: u32, id: u32) -> Self { Self { modio, game, mod_id, id, } } fn path(&self) -> String { format!( "/games/{}/mods/{}/files/{}", self.game, self.mod_id, self.id ) } /// Get a reference to the Modio modfile object that this `FileRef` refers to. pub fn get(&self) -> Future<File> { self.modio.get(&self.path()) } /// Edit details of a modfile. [required: token] pub fn edit(&self, options: &EditFileOptions) -> Future<EntityResult<File>> { token_required!(self.modio); let params = options.to_query_string(); self.modio.put(&self.path(), params) } /// Delete a modfile. [required: token] pub fn delete(&self) -> Future<()> { token_required!(self.modio); self.modio.delete(&self.path(), RequestBody::Empty) } } /// Modfile filters and sorting. /// /// # Filters /// - Fulltext /// - Id /// - ModId /// - DateAdded /// - DateScanned /// - VirusStatus /// - VirusPositive /// - Filesize /// - Filehash /// - Filename /// - Version /// - Changelog /// /// # Sorting /// - Id /// - ModId /// - DateAdded /// - Version /// /// See [modio docs](https://docs.mod.io/#get-all-modfiles) for more information. /// /// By default this returns up to `100` items. You can limit the result by using `limit` and /// `offset`. /// /// # Example /// ``` /// use modio::filter::prelude::*; /// use modio::files::filters::Id; /// /// let filter = Id::_in(vec![1, 2]).order_by(Id::desc()); /// ``` #[rustfmt::skip] pub mod filters { #[doc(inline)] pub use crate::filter::prelude::Fulltext; #[doc(inline)] pub use crate::filter::prelude::Id; #[doc(inline)] pub use crate::filter::prelude::ModId; #[doc(inline)] pub use crate::filter::prelude::DateAdded; filter!(DateScanned, DATE_SCANNED, "date_scanned", Eq, NotEq, In, Cmp); filter!(VirusStatus, VIRUS_STATUS, "virus_status", Eq, NotEq, In, Cmp); filter!(VirusPositive, VIRUS_POSITIVE, "virus_positive", Eq, NotEq, In, Cmp); filter!(Filesize, FILESIZE, "filesize", Eq, NotEq, In, Cmp, OrderBy); filter!(Filehash, FILEHASH, "filehash", Eq, NotEq, In, Like); filter!(Filename, FILENAME, "filename", Eq, NotEq, In, Like); filter!(Version, VERSION, "version", Eq, NotEq, In, Like, OrderBy); filter!(Changelog, CHANGELOG, "changelog", Eq, NotEq, In, Like); } pub struct AddFileOptions { source: FileSource, version: Option<String>, changelog: Option<String>, active: Option<bool>, filehash: Option<String>, metadata_blob: Option<String>, } impl AddFileOptions { pub fn with_read<R, S>(inner: R, filename: S) -> AddFileOptions where R: AsyncRead + 'static + Send + Sync, S: Into<String>, { AddFileOptions { source: FileSource { inner: FileStream::new(inner), filename: filename.into(), mime: APPLICATION_OCTET_STREAM, }, version: None, changelog: None, active: None, filehash: None, metadata_blob: None, } } pub fn with_file<P: AsRef<Path>>(file: P) -> AddFileOptions { let file = file.as_ref(); let filename = file .file_name() .and_then(OsStr::to_str) .map_or_else(String::new, ToString::to_string); Self::with_file_name(file, filename) } pub fn with_file_name<P, S>(file: P, filename: S) -> AddFileOptions where P: AsRef<Path>, S: Into<String>, { let file = file.as_ref(); AddFileOptions { source: FileSource { inner: FileStream::open(file), filename: filename.into(), mime: APPLICATION_OCTET_STREAM, }, version: None, changelog: None, active: None, filehash: None, metadata_blob: None, } } option!(version); option!(changelog); option!(active: bool); option!(filehash); option!(metadata_blob); } #[doc(hidden)] impl From<AddFileOptions> for Form { fn from(opts: AddFileOptions) -> Form { let mut form = Form::new(); if let Some(version) = opts.version { form = form.text("version", version); } if let Some(changelog) = opts.changelog { form = form.text("changelog", changelog); } if let Some(active) = opts.active { form = form.text("active", active.to_string()); } if let Some(filehash) = opts.filehash { form = form.text("filehash", filehash); } if let Some(metadata_blob) = opts.metadata_blob { form = form.text("metadata_blob", metadata_blob); } form.part("filedata", opts.source.into()) } } #[derive(Default)] pub struct EditFileOptions { params: std::collections::BTreeMap<&'static str, String>, } impl EditFileOptions { option!(version >> "version"); option!(changelog >> "changelog"); option!(active: bool >> "active"); option!(metadata_blob >> "metadata_blob"); } impl QueryString for EditFileOptions { fn to_query_string(&self) -> String { form_urlencoded::Serializer::new(String::new()) .extend_pairs(&self.params) .finish() } }
use yew::prelude::*; use yew_router::components::RouterAnchor; use crate::app::AppRoute; pub struct DbCreate { // link: ComponentLink<Self> } pub enum Msg {} impl Component for DbCreate { type Message = Msg; type Properties = (); fn create(_: Self::Properties, _link: ComponentLink<Self>) -> Self { DbCreate { // link } } fn update(&mut self, _msg: Self::Message) -> ShouldRender { true } fn change(&mut self, _: Self::Properties) -> ShouldRender { false } fn view(&self) -> Html { type Anchor = RouterAnchor<AppRoute>; html! { <div class="py-5 px-4 m-auto" style="max-width: 1048px; font-size:14px;"> <Anchor route=AppRoute::DatabaseHome classes="text-decoration-none domain-link-dark"> <i class="bi bi-arrow-left me-2"></i> {"Back to Database Connection"} </Anchor> <div class="d-flex mb-5 mt-3"> <div class="d-flex flex-column"> <h2>{"New Database Connection"}</h2> </div> </div> <div> <div class="border rounded p-4 d-flex flex-column mb-5" style="font-size: 14px;"> <div class="d-flex flex-row "> <div style="width: 100%;"> <div class="mb-4 "> <p class="mb-2 fw-bold"> {"Name"} </p> <div class="input-group mb-2"> <input type="text" class="form-control bg-input-grey" aria-label="Dollar amount (with dot and two decimal places)" placeholder="Connection name" /> </div> <p class="text-color-disabled"> {"Must start and end with an alphanumeric character and can only contain alphanumeric characters and '-'. Can't have more than 35 characters."} </p> </div> <div class="card db-input my-2"> <div class="card-body-db-input p-2 px-4"> <div class="card p-2 m-2"> <div class="d-flex border-bottom border-1 list-hover justify-content-between align-items-center"> <div class="p-4 d-flex border-bottom" style="width: 40%;"> <div class="d-grid " style="min-width: 40px;"> <span class="fw-bold " style=" width: 200%; font-size: 14px; "> {"Requires Username"} </span> <p class="mb-0 text-muted" style=" width: 200%; font-size: 14px; "> {"Requires the user to provide a username in addition to email."} </p> </div> </div> <div class="form-check form-switch fs-4"> <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault" /> </div> </div> <div class="d-flex list-hover justify-content-between align-items-center"> <div class="p-4 d-flex" style="width: 40%;"> <div class="d-grid " style="min-width: 40px;"> <span class="fw-bold " style=" width: 200%; font-size: 14px; "> {"Username Length"} </span> <p class="mb-0 text-muted" style=" width: 200%; font-size: 14px; "> {"Set the minimum and maximum values allowed for a user to have as username."} </p> </div> </div> </div> <div class="card db-input mx-0 p-0 border-0"> <div class="card-body-db-input pb-2 "> <div class="d-flex list-hover justify-content-start align-items-center"> <div class="d-flex list-hover justify-content-between align-items-center"> <div class="px-2 d-flex"> <div class="d-grid m-2" style="min-width: 40px;"> <span class="fw-bold m-2" style=" font-size: 14px; "> {"Min"} </span> <input type="number" class="form-control" min="1" value="1" width="50px"/> </div> <div class="d-grid m-2"> <span class="fw-bold m-2" style=" font-size: 14px; "> {"Max"} </span> <input type="number" class="form-control" min="1" value="15" width="50px"/> </div> </div> </div> </div> </div> </div> </div> <div class="card db-input mt-4 mx-2"> <div class="card-body-db-input py-2 px-2"> <div class="d-flex list-hover justify-content-between align-items-center"> <div class="p-4 d-flex" style="width: 40%;"> <div class="d-grid " style="min-width: 40px;"> <span class="fw-bold " style=" white-space: nowrap; text-overflow: ellipsis; overflow: hidden; font-size: 14px; text-decoration: none; "> {"Disable Sign Ups"} </span> <p class="mb-0 text-muted" style=" width: 200%; font-size: 14px; "> {"Prevent new user sign ups to your application. You will still be able to create users with your API credentials or from the dashboard."} </p> </div> </div> <div class="form-check form-switch fs-4"> <input class="form-check-input" type="checkbox" id="flexSwitchCheckDefault" /> </div> </div> </div> </div> <div class="card db-input mb-1 mt-4 mx-0 border-0"> <div class="card-body-db-input p-2 px-4 "> <div class="d-flex list-hover justify-content-start align-items-center"> <div class="btn btn-primary d-flex align-items-center mx-2"> <span>{"Create"}</span> </div> <div class="btn btn-secondary d-flex align-items-center mx-2"> <span>{"Cancel"}</span> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> } } }
use structopt::StructOpt; use super::{CliCommand, GlobalFlags}; pub const AFTER_HELP: &str = r#"EXAMPLES: To fetch updates for all repositories: $ deck update To fetch updates for a specific repository: $ deck update --repo stable "#; #[derive(Debug, StructOpt)] pub struct Update { /// Specific repository to update #[structopt(long = "repo", empty_values = false, value_name = "REPO")] repo: Option<String>, } impl CliCommand for Update { fn run(self, _flags: GlobalFlags) -> Result<(), String> { unimplemented!() } }
//! Config for socket addresses. use std::{net::ToSocketAddrs, ops::Deref}; /// Parsable socket address. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct SocketAddr(std::net::SocketAddr); impl Deref for SocketAddr { type Target = std::net::SocketAddr; fn deref(&self) -> &Self::Target { &self.0 } } impl std::fmt::Display for SocketAddr { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.0.fmt(f) } } impl std::str::FromStr for SocketAddr { type Err = String; fn from_str(s: &str) -> Result<Self, Self::Err> { match s.to_socket_addrs() { Ok(mut addrs) => { if let Some(addr) = addrs.next() { Ok(Self(addr)) } else { Err(format!("Found no addresses for '{s}'")) } } Err(e) => Err(format!("Cannot parse socket address '{s}': {e}")), } } } impl From<SocketAddr> for std::net::SocketAddr { fn from(addr: SocketAddr) -> Self { addr.0 } } #[cfg(test)] mod tests { use super::*; use std::{ net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6}, str::FromStr, }; #[test] fn test_socketaddr() { let addr: std::net::SocketAddr = SocketAddr::from_str("127.0.0.1:1234").unwrap().into(); assert_eq!(addr, std::net::SocketAddr::from(([127, 0, 0, 1], 1234)),); let addr: std::net::SocketAddr = SocketAddr::from_str("localhost:1234").unwrap().into(); // depending on where the test runs, localhost will either resolve to a ipv4 or // an ipv6 addr. match addr { std::net::SocketAddr::V4(so) => { assert_eq!(so, SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 1234)) } std::net::SocketAddr::V6(so) => assert_eq!( so, SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 1234, 0, 0) ), }; assert_eq!( SocketAddr::from_str("!@INv_a1d(ad0/resp_!").unwrap_err(), "Cannot parse socket address '!@INv_a1d(ad0/resp_!': invalid socket address", ); } }
// extern crate typed_arena; // #[derive(PartialOrd, PartialEq)] // struct Tree<'a, T: 'a + Ord> { // l: Option<&'a mut Tree<'a, T>>, // r: Option<&'a mut Tree<'a, T>>, // data: T, // } // impl<'a, T: 'a + Ord> Tree<'a, T> { // fn new(t: T) -> Tree<'a, T> { // Tree { // l: None, // data: t, // r: None, // } // } // } // fn count<T: Ord>(tree: &Option<&mut Tree<T>>) -> i32 { // if let &Some(&mut Tree { ref l, ref r, .. }) = tree { // 1 + count(l) + count(r) // } else { // 0 // } // } // fn insert<'a, T: 'a + Ord>(tree: &Option<&'a mut Tree<'a, T>>, item: T) { // if let &Some(&mut Tree { mut l, data, mut r }) = tree { // if item < data { // if l == None { // let t_: Tree<'a, T> = Tree::new(item); // l = Some(&mut t_); // } else { // insert(&l, item); // } // } else if item > data { // if r == None { // let t_: Tree<'a, T> = Tree::new(item); // r = Some(&mut t_); // } else { // insert(&r, item); // } // } // } // } // fn main() {}
//! A custom kubelet backend that can run [waSCC](https://wascc.dev/) based workloads //! //! The crate provides the [`WasccProvider`] type which can be used //! as a provider with [`kubelet`]. //! //! # Example //! ```rust,no_run //! use kubelet::{Kubelet, config::Config}; //! use kubelet::store::oci::FileStore; //! use std::sync::Arc; //! use wascc_provider::WasccProvider; //! //! async fn start() { //! // Get a configuration for the Kubelet //! let kubelet_config = Config::default(); //! let client = oci_distribution::Client::default(); //! let store = Arc::new(FileStore::new(client, &std::path::PathBuf::from(""))); //! //! // Load a kubernetes configuration //! let kubeconfig = kube::Config::infer().await.unwrap(); //! //! // Instantiate the provider type //! let provider = WasccProvider::new(store, &kubelet_config, kubeconfig.clone()).await.unwrap(); //! //! // Instantiate the Kubelet //! let kubelet = Kubelet::new(provider, kubeconfig, kubelet_config).await.unwrap(); //! // Start the Kubelet and block on it //! kubelet.start().await.unwrap(); //! } //! ``` #![deny(missing_docs)] use async_trait::async_trait; use k8s_openapi::api::core::v1::{ContainerStatus as KubeContainerStatus, Pod as KubePod}; use kube::{api::DeleteParams, Api}; use kubelet::container::Container; use kubelet::container::{ ContainerKey, Handle as ContainerHandle, HandleMap as ContainerHandleMap, Status as ContainerStatus, }; use kubelet::handle::StopHandler; use kubelet::node::Builder; use kubelet::pod::{key_from_pod, pod_key, Handle}; use kubelet::pod::{ update_status, Phase, Pod, Status as PodStatus, StatusMessage as PodStatusMessage, }; use kubelet::provider::Provider; use kubelet::provider::ProviderError; use kubelet::store::Store; use kubelet::volume::Ref; use log::{debug, error, info, trace}; use std::error::Error; use std::fmt; use tempfile::NamedTempFile; use tokio::sync::watch::{self, Receiver}; use tokio::sync::RwLock; use wascc_fs::FileSystemProvider; use wascc_host::{Actor, NativeCapability, WasccHost}; use wascc_httpsrv::HttpServerProvider; use wascc_logging::{LoggingProvider, LOG_PATH_KEY}; extern crate rand; use rand::Rng; use std::collections::{HashMap, HashSet}; use std::ops::Deref; use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex}; use tokio::sync::Mutex as TokioMutex; /// The architecture that the pod targets. const TARGET_WASM32_WASCC: &str = "wasm32-wascc"; /// The name of the Filesystem capability. const FS_CAPABILITY: &str = "wascc:blobstore"; /// The name of the HTTP capability. const HTTP_CAPABILITY: &str = "wascc:http_server"; /// The name of the Logging capability. const LOG_CAPABILITY: &str = "wascc:logging"; /// The root directory of waSCC logs. const LOG_DIR_NAME: &str = "wascc-logs"; /// The key used to define the root directory of the Filesystem capability. const FS_CONFIG_ROOTDIR: &str = "ROOT"; /// The root directory of waSCC volumes. const VOLUME_DIR: &str = "volumes"; /// Kubernetes' view of environment variables is an unordered map of string to string. type EnvVars = std::collections::HashMap<String, String>; /// A [kubelet::handle::Handle] implementation for a wascc actor pub struct ActorHandle { /// The public key of the wascc Actor that will be stopped pub key: String, host: Arc<Mutex<WasccHost>>, volumes: Vec<VolumeBinding>, } #[async_trait::async_trait] impl StopHandler for ActorHandle { async fn stop(&mut self) -> anyhow::Result<()> { debug!("stopping wascc instance {}", self.key); let host = self.host.clone(); let key = self.key.clone(); let volumes: Vec<VolumeBinding> = self.volumes.drain(0..).collect(); tokio::task::spawn_blocking(move || { let lock = host.lock().unwrap(); lock.remove_actor(&key) .map_err(|e| anyhow::anyhow!("unable to remove actor: {:?}", e))?; for volume in volumes.into_iter() { lock.remove_native_capability(FS_CAPABILITY, Some(volume.name)) .map_err(|e| anyhow::anyhow!("unable to remove volume capability: {:?}", e))?; } Ok(()) }) .await? } async fn wait(&mut self) -> anyhow::Result<()> { // TODO: Figure out if there is a way to wait for an actor to be removed Ok(()) } } /// WasccProvider provides a Kubelet runtime implementation that executes WASM binaries. /// /// Currently, this runtime uses WASCC as a host, loading the primary container as an actor. /// TODO: In the future, we will look at loading capabilities using the "sidecar" metaphor /// from Kubernetes. #[derive(Clone)] pub struct WasccProvider { handles: Arc<RwLock<HashMap<String, Handle<ActorHandle, LogHandleFactory>>>>, store: Arc<dyn Store + Sync + Send>, volume_path: PathBuf, log_path: PathBuf, kubeconfig: kube::Config, host: Arc<Mutex<WasccHost>>, port_map: Arc<TokioMutex<HashMap<i32, String>>>, } impl WasccProvider { /// Returns a new wasCC provider configured to use the proper data directory /// (including creating it if necessary) pub async fn new( store: Arc<dyn Store + Sync + Send>, config: &kubelet::config::Config, kubeconfig: kube::Config, ) -> anyhow::Result<Self> { let host = Arc::new(Mutex::new(WasccHost::new())); let log_path = config.data_dir.join(LOG_DIR_NAME); let volume_path = config.data_dir.join(VOLUME_DIR); let port_map = Arc::new(TokioMutex::new(HashMap::<i32, String>::new())); tokio::fs::create_dir_all(&log_path).await?; tokio::fs::create_dir_all(&volume_path).await?; // wascc has native and portable capabilities. // // Native capabilities are either dynamic libraries (.so, .dylib, .dll) // or statically linked Rust libaries. If the native capabilty is a dynamic // library it must be loaded and configured through [`NativeCapability::from_file`]. // If it is a statically linked libary it can be configured through // [`NativeCapability::from_instance`]. // // Portable capabilities are WASM modules. Portable capabilities // don't fully work, and won't until the WASI spec has matured. // // Here we are using the native capabilties as statically linked libraries that will // be compiled into the wascc-provider binary. let cloned_host = host.clone(); tokio::task::spawn_blocking(move || { info!("Loading HTTP capability"); let http_provider = HttpServerProvider::new(); let data = NativeCapability::from_instance(http_provider, None) .map_err(|e| anyhow::anyhow!("Failed to instantiate HTTP capability: {}", e))?; cloned_host .lock() .unwrap() .add_native_capability(data) .map_err(|e| anyhow::anyhow!("Failed to add HTTP capability: {}", e))?; info!("Loading log capability"); let logging_provider = LoggingProvider::new(); let logging_capability = NativeCapability::from_instance(logging_provider, None) .map_err(|e| anyhow::anyhow!("Failed to instantiate log capability: {}", e))?; cloned_host .lock() .unwrap() .add_native_capability(logging_capability) .map_err(|e| anyhow::anyhow!("Failed to add log capability: {}", e)) }) .await??; Ok(Self { handles: Default::default(), store, volume_path, log_path, kubeconfig, host, port_map, }) } async fn assign_container_port(&self, pod: &Pod, container: &Container) -> anyhow::Result<i32> { let mut port_assigned: i32 = 0; if let Some(container_vec) = container.ports().as_ref() { for c_port in container_vec.iter() { let container_port = c_port.container_port; if let Some(host_port) = c_port.host_port { let mut lock = self.port_map.lock().await; if !lock.contains_key(&host_port) { port_assigned = host_port; lock.insert(port_assigned, pod.name().to_string()); } else { error!( "Failed to assign hostport {}, because it's taken", &host_port ); return Err(anyhow::anyhow!("Port {} is currently in use", &host_port)); } } else if container_port >= 0 && container_port <= 65536 { port_assigned = find_available_port(&self.port_map, pod.name().to_string()).await?; } } } Ok(port_assigned) } async fn start_container( &self, run_context: &mut ModuleRunContext<'_>, container: &Container, pod: &Pod, port_assigned: i32, ) -> anyhow::Result<()> { let env = Self::env_vars(&container, &pod, run_context.client).await; let volume_bindings: Vec<VolumeBinding> = if let Some(volume_mounts) = container.volume_mounts().as_ref() { volume_mounts .iter() .map(|vm| -> anyhow::Result<VolumeBinding> { // Check the volume exists first let vol = run_context.volumes.get(&vm.name).ok_or_else(|| { anyhow::anyhow!( "no volume with the name of {} found for container {}", vm.name, container.name() ) })?; // We can safely assume that this should be valid UTF-8 because it would have // been validated by the k8s API Ok(VolumeBinding { name: vm.name.clone(), host_path: vol.deref().clone(), }) }) .collect::<anyhow::Result<_>>()? } else { vec![] }; debug!("Starting container {} on thread", container.name()); let module_data = run_context .modules .remove(container.name()) .expect("FATAL ERROR: module map not properly populated"); let lp = self.log_path.clone(); let (status_sender, status_recv) = watch::channel(ContainerStatus::Waiting { timestamp: chrono::Utc::now(), message: "No status has been received from the process".into(), }); let host = self.host.clone(); let wascc_result = tokio::task::spawn_blocking(move || { wascc_run( host, module_data, env, volume_bindings, &lp, status_recv, port_assigned, ) }) .await?; match wascc_result { Ok(handle) => { run_context .container_handles .insert(ContainerKey::App(container.name().to_string()), handle); status_sender .broadcast(ContainerStatus::Running { timestamp: chrono::Utc::now(), }) .expect("status should be able to send"); Ok(()) } Err(e) => { // We can't broadcast here because the receiver has been dropped at this point // (it was never used in creating a runtime handle) let mut container_statuses = HashMap::new(); container_statuses.insert( ContainerKey::App(container.name().to_string()), ContainerStatus::Terminated { timestamp: chrono::Utc::now(), failed: true, message: format!("Error while starting container: {:?}", e), }, ); let status = PodStatus { message: PodStatusMessage::LeaveUnchanged, container_statuses, }; pod.patch_status(run_context.client.clone(), status).await; Err(anyhow::anyhow!("Failed to run pod: {}", e)) } } } } struct ModuleRunContext<'a> { client: &'a kube::Client, modules: &'a mut HashMap<String, Vec<u8>>, volumes: &'a HashMap<String, Ref>, container_handles: &'a mut ContainerHandleMap<ActorHandle, LogHandleFactory>, } #[async_trait] impl Provider for WasccProvider { const ARCH: &'static str = TARGET_WASM32_WASCC; async fn node(&self, builder: &mut Builder) -> anyhow::Result<()> { builder.set_architecture("wasm-wasi"); builder.add_taint("NoExecute", "kubernetes.io/arch", Self::ARCH); Ok(()) } async fn add(&self, pod: Pod) -> anyhow::Result<()> { // To run an Add event, we load the actor, and update the pod status // to Running. The wascc runtime takes care of starting the actor. // When the pod finishes, we update the status to Succeeded unless it // produces an error, in which case we mark it Failed. debug!("Pod added {:?}", pod.name()); validate_pod_runnable(&pod)?; info!("Starting containers for pod {:?}", pod.name()); let mut modules = self.store.fetch_pod_modules(&pod).await?; let mut container_handles = HashMap::new(); let client = kube::Client::new(self.kubeconfig.clone()); let volumes = Ref::volumes_from_pod(&self.volume_path, &pod, &client).await?; let mut run_context = ModuleRunContext { client: &client, modules: &mut modules, volumes: &volumes, container_handles: &mut container_handles, }; for container in pod.containers() { let port_assigned = self.assign_container_port(&pod, &container).await?; debug!( "New port assigned to {} is: {}", container.name(), port_assigned ); self.start_container(&mut run_context, &container, &pod, port_assigned) .await? } info!( "All containers started for pod {:?}. Updating status", pod.name() ); let pod_handle_key = key_from_pod(&pod); let pod_handle = Handle::new(container_handles, pod, client, None, None).await?; // Wrap this in a block so the write lock goes out of scope when we are done { let mut handles = self.handles.write().await; handles.insert(pod_handle_key, pod_handle); } Ok(()) } async fn modify(&self, pod: Pod) -> anyhow::Result<()> { // The only things we care about are: // 1. metadata.deletionTimestamp => signal all containers to stop and then mark them // as terminated // 2. spec.containers[*].image, spec.initContainers[*].image => stop the currently // running containers and start new ones? // 3. spec.activeDeadlineSeconds => Leaving unimplemented for now // TODO: Determine what the proper behavior should be if labels change let pod_name = pod.name().to_owned(); let pod_namespace = pod.namespace().to_owned(); debug!( "Got pod modified event for {} in namespace {}", pod_name, pod_namespace ); trace!("Modified pod spec: {:#?}", pod.as_kube_pod()); if let Some(_timestamp) = pod.deletion_timestamp() { debug!( "Found delete timestamp for pod {} in namespace {}. Stopping running actors", pod_name, pod_namespace ); let mut handles = self.handles.write().await; match handles.get_mut(&key_from_pod(&pod)) { Some(h) => { h.stop().await?; debug!( "All actors stopped for pod {} in namespace {}, updating status", pod_name, pod_namespace ); // Having to do this here isn't my favorite thing, but we need to update the // status of the container so it can be deleted. We will probably need to have // some sort of provider that can send a message about status to the Kube API let now = chrono::Utc::now(); let terminated = ContainerStatus::Terminated { timestamp: now, message: "Pod stopped".to_owned(), failed: false, }; let container_statuses: Vec<KubeContainerStatus> = pod .into_kube_pod() .spec .unwrap_or_default() .containers .into_iter() .map(|c| terminated.to_kubernetes(c.name)) .collect(); let json_status = serde_json::json!( { "metadata": { "resourceVersion": "", }, "status": { "message": "Pod stopped", "phase": Phase::Succeeded, "containerStatuses": container_statuses, } } ); let client = kube::client::Client::new(self.kubeconfig.clone()); update_status(client.clone(), &pod_namespace, &pod_name, &json_status).await?; let pod_client: Api<KubePod> = Api::namespaced(client.clone(), &pod_namespace); let dp = DeleteParams { grace_period_seconds: Some(0), ..Default::default() }; match pod_client.delete(&pod_name, &dp).await { Ok(_) => Ok(()), Err(e) => Err(e.into()), } } None => { // This isn't an error with the pod, so don't return an error (otherwise it will // get updated in its status). This is an unlikely case to get into and means // that something is likely out of sync, so just log the error error!( "Unable to find pod {} in namespace {} when trying to stop all containers", pod_name, pod_namespace ); Ok(()) } } } else { Ok(()) } // TODO: Implement behavior for stopping old containers and restarting when the container // image changes } async fn delete(&self, pod: Pod) -> anyhow::Result<()> { let mut delete_key: i32 = 0; let mut lock = self.port_map.lock().await; for (key, val) in lock.iter() { if val == pod.name() { delete_key = *key } } lock.remove(&delete_key); let mut handles = self.handles.write().await; match handles.remove(&key_from_pod(&pod)) { Some(_) => debug!( "Pod {} in namespace {} removed", pod.name(), pod.namespace() ), None => info!( "unable to find pod {} in namespace {}, it was likely already deleted", pod.name(), pod.namespace() ), } Ok(()) } async fn logs( &self, namespace: String, pod_name: String, container_name: String, sender: kubelet::log::Sender, ) -> anyhow::Result<()> { let mut handles = self.handles.write().await; let handle = handles .get_mut(&pod_key(&namespace, &pod_name)) .ok_or_else(|| ProviderError::PodNotFound { pod_name: pod_name.clone(), })?; handle.output(&container_name, sender).await } } fn validate_pod_runnable(pod: &Pod) -> anyhow::Result<()> { if !pod.init_containers().is_empty() { return Err(anyhow::anyhow!( "Cannot run {}: spec specifies init containers which are not supported on wasCC", pod.name() )); } for container in pod.containers() { validate_container_runnable(&container)?; } Ok(()) } fn validate_container_runnable(container: &Container) -> anyhow::Result<()> { if has_args(container) { return Err(anyhow::anyhow!( "Cannot run {}: spec specifies container args which are not supported on wasCC", container.name() )); } Ok(()) } fn has_args(container: &Container) -> bool { match &container.args() { None => false, Some(vec) => !vec.is_empty(), } } struct VolumeBinding { name: String, host_path: PathBuf, } #[derive(Debug)] struct PortAllocationError {} impl PortAllocationError { fn new() -> PortAllocationError { PortAllocationError {} } } impl fmt::Display for PortAllocationError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "all ports are currently in use") } } impl Error for PortAllocationError { fn description(&self) -> &str { "all ports are currently in use" } } async fn find_available_port( port_map: &Arc<TokioMutex<HashMap<i32, String>>>, pod_name: String, ) -> Result<i32, PortAllocationError> { let mut port: Option<i32> = None; let mut empty_port: HashSet<i32> = HashSet::new(); let mut lock = port_map.lock().await; while empty_port.len() < 2768 { let generated_port: i32 = rand::thread_rng().gen_range(30000, 32768); port.replace(generated_port); empty_port.insert(port.unwrap()); if !lock.contains_key(&port.unwrap()) { lock.insert(port.unwrap(), pod_name); break; } } port.ok_or_else(PortAllocationError::new) } /// Capability describes a waSCC capability. /// /// Capabilities are made available to actors through a two-part processthread: /// - They must be registered /// - For each actor, the capability must be configured struct Capability { name: &'static str, binding: Option<String>, env: EnvVars, } /// Holds our tempfile handle. struct LogHandleFactory { temp: NamedTempFile, } impl kubelet::log::HandleFactory<tokio::fs::File> for LogHandleFactory { /// Creates `tokio::fs::File` on demand for log reading. fn new_handle(&self) -> tokio::fs::File { tokio::fs::File::from_std(self.temp.reopen().unwrap()) } } /// Run the given WASM data as a waSCC actor with the given public key. /// /// The provided capabilities will be configured for this actor, but the capabilities /// must first be loaded into the host by some other process, such as register_native_capabilities(). fn wascc_run( host: Arc<Mutex<WasccHost>>, data: Vec<u8>, mut env: EnvVars, volumes: Vec<VolumeBinding>, log_path: &Path, status_recv: Receiver<ContainerStatus>, port_assigned: i32, ) -> anyhow::Result<ContainerHandle<ActorHandle, LogHandleFactory>> { let mut capabilities: Vec<Capability> = Vec::new(); info!("sending actor to wascc host"); let log_output = NamedTempFile::new_in(log_path)?; let mut logenv: HashMap<String, String> = HashMap::new(); logenv.insert( LOG_PATH_KEY.to_string(), log_output.path().to_str().unwrap().to_owned(), ); let load = Actor::from_bytes(data).map_err(|e| anyhow::anyhow!("Error loading WASM: {}", e))?; let pk = load.public_key(); let actor_caps = load.capabilities(); if actor_caps.contains(&LOG_CAPABILITY.to_owned()) { capabilities.push(Capability { name: LOG_CAPABILITY, binding: None, env: logenv, }); } if actor_caps.contains(&HTTP_CAPABILITY.to_owned()) { env.insert("PORT".to_string(), port_assigned.to_string()); capabilities.push(Capability { name: HTTP_CAPABILITY, binding: None, env, }); } if actor_caps.contains(&FS_CAPABILITY.to_owned()) { for vol in &volumes { info!( "Loading File System capability for volume name: '{}' host_path: '{}'", vol.name, vol.host_path.display() ); let mut fsenv: HashMap<String, String> = HashMap::new(); fsenv.insert( FS_CONFIG_ROOTDIR.to_owned(), vol.host_path.as_path().to_str().unwrap().to_owned(), ); let fs_provider = FileSystemProvider::new(); let fs_capability = NativeCapability::from_instance(fs_provider, Some(vol.name.clone())).map_err( |e| anyhow::anyhow!("Failed to instantiate File System capability: {}", e), )?; host.lock() .unwrap() .add_native_capability(fs_capability) .map_err(|e| anyhow::anyhow!("Failed to add File System capability: {}", e))?; capabilities.push(Capability { name: FS_CAPABILITY, binding: Some(vol.name.clone()), env: fsenv, }); } } host.lock() .unwrap() .add_actor(load) .map_err(|e| anyhow::anyhow!("Error adding actor: {}", e))?; capabilities.iter().try_for_each(|cap| { info!("configuring capability {}", cap.name); host.lock() .unwrap() .bind_actor(&pk, cap.name, cap.binding.clone(), cap.env.clone()) .map_err(|e| anyhow::anyhow!("Error configuring capabilities for module: {}", e)) })?; let log_handle_factory = LogHandleFactory { temp: log_output }; info!("wascc actor executing"); Ok(ContainerHandle::new( ActorHandle { host, key: pk, volumes, }, log_handle_factory, status_recv, )) } #[cfg(test)] mod test { use super::*; use k8s_openapi::api::core::v1::Container as KubeContainer; use serde_json::json; fn make_pod_spec(containers: Vec<KubeContainer>) -> Pod { let kube_pod: KubePod = serde_json::from_value(json!({ "apiVersion": "v1", "kind": "Pod", "metadata": { "name": "test-pod-spec" }, "spec": { "containers": containers } })) .unwrap(); Pod::new(kube_pod) } #[test] fn can_run_pod_where_container_has_no_args() { let containers: Vec<KubeContainer> = serde_json::from_value(json!([ { "name": "greet-wascc", "image": "webassembly.azurecr.io/greet-wascc:v0.4", }, ])) .unwrap(); let pod = make_pod_spec(containers); validate_pod_runnable(&pod).unwrap(); } #[test] fn can_run_pod_where_container_has_empty_args() { let containers: Vec<KubeContainer> = serde_json::from_value(json!([ { "name": "greet-wascc", "image": "webassembly.azurecr.io/greet-wascc:v0.4", "args": [], }, ])) .unwrap(); let pod = make_pod_spec(containers); validate_pod_runnable(&pod).unwrap(); } #[test] fn cannot_run_pod_where_container_has_args() { let containers: Vec<KubeContainer> = serde_json::from_value(json!([ { "name": "greet-wascc", "image": "webassembly.azurecr.io/greet-wascc:v0.4", "args": [ "--foo", "--bar" ] }, ])) .unwrap(); let pod = make_pod_spec(containers); assert!(validate_pod_runnable(&pod).is_err()); } #[test] fn cannot_run_pod_where_any_container_has_args() { let containers: Vec<KubeContainer> = serde_json::from_value(json!([ { "name": "greet-1", "image": "webassembly.azurecr.io/greet-wascc:v0.4" }, { "name": "greet-2", "image": "webassembly.azurecr.io/greet-wascc:v0.4", "args": [ "--foo", "--bar" ] }, ])) .unwrap(); let pod = make_pod_spec(containers); let validation = validate_pod_runnable(&pod); assert!(validation.is_err()); let message = format!("{}", validation.unwrap_err()); assert!( message.contains("greet-2"), "validation error did not give name of bad container" ); } }
//! Process-associated operations. #[cfg(not(target_os = "wasi"))] mod chdir; #[cfg(not(any(target_os = "fuchsia", target_os = "wasi")))] mod chroot; mod exit; #[cfg(not(target_os = "wasi"))] // WASI doesn't have get[gpu]id. mod id; #[cfg(not(target_os = "espidf"))] mod ioctl; #[cfg(not(any(target_os = "espidf", target_os = "wasi")))] mod kill; #[cfg(linux_kernel)] mod membarrier; #[cfg(target_os = "linux")] mod pidfd; #[cfg(target_os = "linux")] mod pidfd_getfd; #[cfg(linux_kernel)] mod prctl; #[cfg(not(any(target_os = "fuchsia", target_os = "wasi")))] // WASI doesn't have [gs]etpriority. mod priority; #[cfg(freebsdlike)] mod procctl; #[cfg(not(any( target_os = "espidf", target_os = "fuchsia", target_os = "redox", target_os = "wasi" )))] mod rlimit; #[cfg(any(linux_kernel, target_os = "dragonfly", target_os = "fuchsia"))] mod sched; mod sched_yield; #[cfg(not(target_os = "wasi"))] // WASI doesn't have umask. mod umask; #[cfg(not(any(target_os = "espidf", target_os = "wasi")))] mod wait; #[cfg(not(target_os = "wasi"))] pub use chdir::*; #[cfg(not(any(target_os = "fuchsia", target_os = "wasi")))] pub use chroot::*; pub use exit::*; #[cfg(not(target_os = "wasi"))] pub use id::*; #[cfg(not(target_os = "espidf"))] pub use ioctl::*; #[cfg(not(any(target_os = "espidf", target_os = "wasi")))] pub use kill::*; #[cfg(linux_kernel)] pub use membarrier::*; #[cfg(target_os = "linux")] pub use pidfd::*; #[cfg(target_os = "linux")] pub use pidfd_getfd::*; #[cfg(linux_kernel)] pub use prctl::*; #[cfg(not(any(target_os = "fuchsia", target_os = "wasi")))] pub use priority::*; #[cfg(freebsdlike)] pub use procctl::*; #[cfg(not(any( target_os = "espidf", target_os = "fuchsia", target_os = "redox", target_os = "wasi" )))] pub use rlimit::*; #[cfg(any(linux_kernel, target_os = "dragonfly", target_os = "fuchsia"))] pub use sched::*; pub use sched_yield::sched_yield; #[cfg(not(target_os = "wasi"))] pub use umask::*; #[cfg(not(any(target_os = "espidf", target_os = "wasi")))] pub use wait::*;
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; use crate::erlang::spawn_apply_1; #[native_implemented::function(erlang:spawn/1)] pub fn result(process: &Process, function: Term) -> exception::Result<Term> { spawn_apply_1::result(process, function, Default::default()) }
// 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::collections::btree_map::BTreeMap; use core::ops::Bound::Included; use alloc::vec::Vec; use alloc::sync::Arc; use spin::Mutex; use core::ops::Deref; use super::super::common::*; use super::super::linux_def::*; use super::id::*; #[derive(Default, Debug)] pub struct UserNameSpaceInternal { pub parent: Option<UserNameSpace>, pub owner: KUID, pub uidMapFromParent: IdMap, pub uidMapToParent: IdMap, pub gidMapFromParent: IdMap, pub gidMapToParent: IdMap, } impl UserNameSpaceInternal { pub fn GetIDMap(&self, m: &IdMap) -> Vec<IdMapEntry> { let mut ret = Vec::with_capacity(m.map.len()); for (_, entry) in &m.map { ret.push(IdMapEntry { FirstFromId: entry.FirstFromId, FirstToId: entry.FirstToId, Len: entry.Len, }); } return ret; } pub fn UIPMap(&self) -> Vec<IdMapEntry> { return self.GetIDMap(&self.uidMapToParent) } pub fn GIDMap(&self) -> Vec<IdMapEntry> { return self.GetIDMap(&self.gidMapToParent) } } #[derive(Clone, Default, Debug)] pub struct UserNameSpace(pub Arc<Mutex<UserNameSpaceInternal>>); impl Deref for UserNameSpace { type Target = Arc<Mutex<UserNameSpaceInternal>>; fn deref(&self) -> &Arc<Mutex<UserNameSpaceInternal>> { &self.0 } } impl PartialEq for UserNameSpace { fn eq(&self, other: &Self) -> bool { return Arc::ptr_eq(&self.0, &other.0) } } impl Eq for UserNameSpace {} impl UserNameSpace { pub fn NewRootUserNamespace() -> Self { let internal = UserNameSpaceInternal { parent: None, owner: KUID::default(), uidMapFromParent: IdMap::All(), uidMapToParent: IdMap::All(), gidMapFromParent: IdMap::All(), gidMapToParent: IdMap::All(), }; return Self(Arc::new(Mutex::new(internal))) } /*pub fn SetUIDMap(&mut self, task: &Task, entries: &Vec<IdMapEntry>) -> Result<()> { let creds = &task.creds; if self.uidMapFromParent.IsEmpty() { return Err(Error::SysError(SysErr::EPERM)) } if entries.len() == 0 { return Err(Error::SysError(SysErr::EINVAL)) } if !creds. }*/ pub fn trySetUidMap(&mut self, entries: &Vec<IdMapEntry>) -> Result<()> { let mut me = self.lock(); for entry in entries { me.uidMapToParent.AddEntry(entry.FirstFromId, entry.FirstToId, entry.Len)?; me.uidMapFromParent.AddEntry(entry.FirstToId, entry.FirstFromId, entry.Len)? } return Ok(()) } pub fn trySetGidMap(&mut self, entries: &Vec<IdMapEntry>) -> Result<()> { let mut me = self.lock(); for entry in entries { me.gidMapToParent.AddEntry(entry.FirstFromId, entry.FirstToId, entry.Len)?; me.gidMapFromParent.AddEntry(entry.FirstToId, entry.FirstFromId, entry.Len)? } return Ok(()) } pub fn MapFromKUID(&self, kuid: KUID) -> UID { let me = self.lock(); match &me.parent { None => return UID(kuid.0), Some(parent) => return UID(me.uidMapFromParent.Map(parent.MapFromKUID(kuid).0)) } } pub fn MapFromKGID(&self, kgid: KGID) -> GID { let me = self.lock(); match &me.parent { None => return GID(kgid.0), Some(parent) => return GID(me.gidMapFromParent.Map(parent.MapFromKGID(kgid).0)) } } pub fn MapToKUID(&self, uid: UID) -> KUID { let me = self.lock(); match &me.parent { None => return KUID(uid.0), Some(parent) => return KUID(me.uidMapToParent.Map(parent.MapToKUID(uid).0)) } } pub fn MapToKGID(&self, gid: GID) -> KGID { let me = self.lock(); match &me.parent { None => return KGID(gid.0), Some(parent) => return KGID(me.gidMapToParent.Map(parent.MapToKGID(gid).0)) } } pub fn Depth(&self) -> usize { let mut i = 0; let mut ns = self.clone(); loop { i += 1; let parent = ns.lock().parent.clone(); match parent { None => break, Some(ref n) => ns = n.clone(), } } return i; } pub fn UIDMap(&self) -> Vec<IdMapEntry> { return self.lock().UIPMap(); } pub fn GIDMap(&self) -> Vec<IdMapEntry> { return self.lock().GIDMap(); } } #[derive(Default, Debug, Clone, Copy)] pub struct IdMapEntry { pub FirstFromId: u32, pub FirstToId: u32, pub Len: u32, } #[derive(Debug)] pub struct IdMap { pub map: BTreeMap<u32, IdMapEntry>, } impl Default for IdMap { fn default() -> Self { return Self { map: BTreeMap::new(), } } } impl IdMap { pub fn All() -> Self { let mut res = Self::default(); res.AddEntry(0, 0, core::u32::MAX).unwrap(); return res; } pub fn AddEntry(&mut self, FirstFromId: u32, FirstToId: u32, Len: u32) -> Result<()> { let mut id = FirstFromId; if id < FirstToId { id = FirstToId } if core::u32::MAX - Len < id { return Err(Error::SysError(SysErr::EINVAL)) } //todo: check whether there is overlap self.map.insert(FirstFromId, IdMapEntry { FirstFromId, FirstToId, Len, }); return Ok(()) } pub fn RemoveAll(&mut self) { self.map.clear(); } pub fn Map(&self, id: u32) -> u32 { for (_, &val) in self.map.range((Included(0), Included(id))).rev() { if id < val.FirstFromId || id >= val.FirstFromId + val.Len { return NO_ID } return id - val.FirstFromId + val.FirstToId } return NO_ID } pub fn IsEmpty(&self) -> bool { self.map.len() == 0 } }
//! Base widgets //! ============ //! //! *Note*: this list is not exhaustive as backend crates may also define custom widgets. //! //! Combining widgets //! ----------------- //! //! The set of widgets have been designed to do as little as necessary. This means that you have //! different widgets to specify background color, border color and thickness, and so on. //! //! You are free to combine these widgets. As an example, you can layer two `Border` widgets and //! a `Spacing` to create a double border effect. //! //! Backend crates might define certain arrangements to simplify usage. //! //! Helper functions //! ---------------- //! //! Sometimes we want to reuse a particular combination of widgets. To do this, we can create //! functions that returns the nested structure we describe. //! //! Due to how `embedded-gui` is built, we must specify the exact type of the nested widget //! structure. Thankfully, if we did our part well, the compiler can help us with this. //! //! Consider the following example, where we want to create function that constructs a //! `TextBlock` with a border. We can implement our function like this, purposefully omitting the //! return type: //! //! ```rust,ignore //! fn button_with_style<W: Widget>(inner: W) -> _ { //! Button::new( //! // we need to help the compiler a bit //! Background::<_, BackgroundStyle<BinaryColor>>::new( //! Border::<_, BorderStyle<BinaryColor>>::new( //! FillParent::both(inner) //! .align_horizontal(Center) //! .align_vertical(Center), //! ) //! .border_color(BinaryColor::Off), //! ) //! .background_color(BinaryColor::Off), //! ) //! } //! ``` //! //! If we try to build this, the compiler will give us the correct return type: //! //! ```text //! error[E0121]: the type placeholder `_` is not allowed within types on item signatures for return types //! --> examples\hello_world.rs:108:46 //! | //! 108 | fn button_with_style<W: Widget>(inner: W) -> _ { //! | ^ //! | | //! | not allowed in type signatures //! | help: replace with the correct return type: `Button<Background<Border<FillParent<W, HorizontalAndVertical, embedded_gui::widgets::fill::Center, embedded_gui::widgets::fill::Center>, BorderStyle<BinaryColor>>, BackgroundStyle<BinaryColor>>>` //! ``` //! //! If we have supplied the compiler with enough information, it will be able to tell us the exact //! return type we need to paste in place of the `_`. //! use crate::{ geometry::{measurement::MeasureSpec, BoundingBox, Position}, input::{controller::InputContext, event::InputEvent}, state::WidgetState, }; pub mod background; pub mod border; pub mod button; pub mod fill; pub mod graphical; pub mod label; pub mod layouts; pub mod scroll; pub mod slider; pub mod spacing; pub mod text_block; pub mod text_box; pub mod toggle; pub mod utils; pub mod visibility; pub trait Widget { fn attach(&mut self, parent: usize, index: usize) { debug_assert!(index == 0 || parent != index); debug_assert!( self.children() == 0, "Attach must be implemented by non-leaf widgets" ); self.set_parent(parent); } fn bounding_box(&self) -> BoundingBox; fn bounding_box_mut(&mut self) -> &mut BoundingBox { unimplemented!() } fn children(&self) -> usize { 0 } fn get_child(&self, _idx: usize) -> &dyn Widget { unimplemented!() } fn get_mut_child(&mut self, _idx: usize) -> &mut dyn Widget { unimplemented!() } fn measure(&mut self, measure_spec: MeasureSpec); fn arrange(&mut self, position: Position) { debug_assert!( self.children() == 0, "Arrange must be implemented by non-leaf widgets" ); self.bounding_box_mut().position = position; } fn update(&mut self) {} fn parent_index(&self) -> usize; fn set_parent(&mut self, _index: usize) {} fn test_input(&mut self, _event: InputEvent) -> Option<usize> { None } fn handle_input(&mut self, _ctxt: InputContext, _event: InputEvent) -> bool { false } fn on_state_changed(&mut self, state: WidgetState); fn is_selectable(&self) -> bool { false } }
//! A late-initialized static reference. use std::{ marker::PhantomData, ptr::{self, NonNull}, sync::atomic::{AtomicPtr, Ordering}, }; use crate::{ external_types::RMutex, pointer_trait::{GetPointerKind, ImmutableRef, PK_Reference}, prefix_type::{PrefixRef, PrefixRefTrait}, }; /// A late-initialized static reference,with fallible initialization. /// /// As opposed to `Once`, /// this allows initialization of its static reference to happen fallibly, /// by returning a `Result<_,_>` from the `try_init` function, /// or by panicking inside either initialization function. /// /// On `Err(_)` and panics,one can try initialializing the static reference again. /// /// # Example /// /// This lazily loads a configuration file. /// /// ``` /// /// use abi_stable::{ /// sabi_types::LateStaticRef, /// std_types::{RBox, RBoxError, RHashMap, RString}, /// utils::leak_value, /// }; /// /// use std::{fs, io, path::Path}; /// /// use serde::Deserialize; /// /// #[derive(Deserialize)] /// pub struct Config { /// pub user_actions: RHashMap<RString, UserAction>, /// } /// /// #[derive(Deserialize)] /// pub enum UserAction { /// Include, /// Ignore, /// ReplaceWith, /// } /// /// fn load_config(file_path: &Path) -> Result<&'static Config, RBoxError> { /// static CONFIG: LateStaticRef<&Config> = LateStaticRef::new(); /// /// CONFIG.try_init(|| { /// let file = load_file(file_path).map_err(RBoxError::new)?; /// let config = /// serde_json::from_str::<Config>(&file).map_err(RBoxError::new)?; /// Ok(leak_value(config)) /// }) /// } /// /// # fn load_file(file_path:&Path)->Result<String,RBoxError>{ /// # let str=r##" /// # { /// # "user_actions":{ /// # "oolong":"prolonged", /// # "genius":"idiot" /// # } /// # } /// # "##.to_string(); /// # Ok(str) /// # } /// /// ``` /// #[repr(C)] #[derive(StableAbi)] pub struct LateStaticRef<T> { pointer: AtomicPtr<()>, lock: RMutex<()>, _marker: PhantomData<T>, } #[allow(clippy::declare_interior_mutable_const)] const LOCK: RMutex<()> = RMutex::new(()); unsafe impl<T: Sync> Sync for LateStaticRef<T> {} unsafe impl<T: Send> Send for LateStaticRef<T> {} impl<T> LateStaticRef<T> { /// Constructs the `LateStaticRef` in an uninitialized state. /// /// # Example /// /// ``` /// use abi_stable::sabi_types::LateStaticRef; /// /// static LATE_REF: LateStaticRef<&String> = LateStaticRef::new(); /// /// ``` pub const fn new() -> Self { Self { lock: LOCK, pointer: AtomicPtr::new(ptr::null_mut()), _marker: PhantomData, } } } impl<T> LateStaticRef<&'static T> { /// Constructs `LateStaticRef`, initialized with `value`. /// /// # Example /// /// ``` /// use abi_stable::sabi_types::LateStaticRef; /// /// static LATE_REF: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!"); /// /// ``` pub const fn from_ref(value: &'static T) -> Self { Self { lock: LOCK, pointer: AtomicPtr::new(value as *const T as *mut ()), _marker: PhantomData, } } } impl<T> LateStaticRef<T> { /// Constructs `LateStaticRef` from a [`PrefixRef`]. /// /// # Example /// /// ``` /// use abi_stable::{ /// pointer_trait::ImmutableRef, /// prefix_type::{PrefixRefTrait, PrefixTypeTrait, WithMetadata}, /// sabi_types::LateStaticRef, /// StableAbi, /// }; /// /// fn main() { /// assert_eq!(LATE_REF.get().unwrap().get_number()(), 100); /// } /// /// pub static LATE_REF: LateStaticRef<PersonMod_Ref> = { /// // This is how you can construct a `LateStaticRef<Foo_Ref>`, /// // from a `Foo_Ref` at compile-time. /// // /// // If you don't need a `LateStaticRef` you can construct a `PersonMod_Ref` constant, /// // and use that. /// LateStaticRef::from_prefixref(MODULE.0) /// }; /// /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(kind(Prefix))] /// pub struct PersonMod { /// /// The `#[sabi(last_prefix_field)]` attribute here means that this is /// /// the last field in this struct that was defined in the /// /// first compatible version of the library. /// /// Moving this attribute is a braeking change. /// #[sabi(last_prefix_field)] /// pub get_number: extern "C" fn() -> u32, /// } /// /// const MODULE: PersonMod_Ref = { /// const S: &WithMetadata<PersonMod> = /// &WithMetadata::new(PersonMod { get_number }); /// /// PersonMod_Ref(S.static_as_prefix()) /// }; /// /// extern "C" fn get_number() -> u32 { /// 100 /// } /// ``` /// /// [`PrefixRef`]: ../prefix_type/struct.PrefixRef.html pub const fn from_prefixref(ptr: PrefixRef<T::PrefixFields>) -> Self where T: PrefixRefTrait + 'static, T::PrefixFields: 'static, { Self { lock: LOCK, pointer: AtomicPtr::new(ptr.to_raw_ptr() as *mut ()), _marker: PhantomData, } } } impl<T> LateStaticRef<T> { /// Constructs `LateStaticRef` from a `NonNull` pointer. /// /// # Safety /// /// The passed in pointer must be valid for passing to /// [`<T as ImmutableRef>::from_nonnull`], /// it must be a valid pointer to `U`, /// and be valid to dereference for the rest of the program's lifetime. /// /// [`<T as ImmutableRef>::from_nonnull`]: /// ../pointer_trait/trait.ImmutableRef.html#method.from_nonnull /// /// # Example /// /// ```rust /// use abi_stable::{ /// pointer_trait::{GetPointerKind, PK_Reference}, /// sabi_types::LateStaticRef, /// utils::ref_as_nonnull, /// StableAbi, /// }; /// /// use std::ptr::NonNull; /// /// #[derive(Copy, Clone)] /// struct Foo<'a>(&'a u64); /// /// impl<'a> Foo<'a> { /// const fn as_nonnull(self) -> NonNull<u64> { /// ref_as_nonnull(self.0) /// } /// } /// /// unsafe impl<'a> GetPointerKind for Foo<'a> { /// type PtrTarget = u64; /// type Kind = PK_Reference; /// } /// /// const MODULE: LateStaticRef<Foo<'static>> = { /// unsafe { /// LateStaticRef::from_custom(Foo(&100).as_nonnull()) /// } /// }; /// ``` pub const unsafe fn from_custom(ptr: NonNull<T::PtrTarget>) -> Self where T: GetPointerKind<Kind = PK_Reference> + 'static, T::PtrTarget: 'static, { Self { lock: LOCK, pointer: AtomicPtr::new(ptr.as_ptr() as *mut ()), _marker: PhantomData, } } } impl<T> LateStaticRef<T> where T: ImmutableRef + 'static, { /// Lazily initializes the `LateStaticRef` with `initializer`, /// returning the `T` if either it was already initialized,or /// if `initalizer` returned Ok(..). /// /// If `initializer` returns an `Err(...)` this returns the error and /// allows the `LateStaticRef` to be initializer later. /// /// If `initializer` panics,the panic is propagated, /// and the reference can be initalized later. /// /// # Example /// /// ``` /// use abi_stable::{sabi_types::LateStaticRef, utils::leak_value}; /// /// static LATE: LateStaticRef<&String> = LateStaticRef::new(); /// /// static EARLY: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!"); /// /// assert_eq!(LATE.try_init(|| Err("oh no!")), Err("oh no!")); /// assert_eq!( /// LATE.try_init(|| -> Result<&'static String, ()> { /// Ok(leak_value("Yay".to_string())) /// }) /// .map(|s| s.as_str()), /// Ok("Yay"), /// ); /// /// assert_eq!(EARLY.try_init(|| Err("oh no!")), Ok(&"Hello!")); /// /// /// ``` pub fn try_init<F, E>(&self, initializer: F) -> Result<T, E> where F: FnOnce() -> Result<T, E>, { if let Some(pointer) = self.get() { return Ok(pointer); } let guard_ = self.lock.lock(); if let Some(pointer) = self.get() { return Ok(pointer); } let pointer = initializer()?; self.pointer.store( pointer.to_raw_ptr() as *mut T::PtrTarget as *mut (), Ordering::Release, ); drop(guard_); Ok(pointer) } /// Lazily initializes the `LateStaticRef` with `initializer`, /// returning the `T` if either it was already initialized, /// or `initalizer` returns it without panicking. /// /// If `initializer` panics,the panic is propagated, /// and the reference can be initalized later. /// /// # Example /// /// ``` /// use abi_stable::{sabi_types::LateStaticRef, utils::leak_value}; /// /// static LATE: LateStaticRef<&String> = LateStaticRef::new(); /// /// static EARLY: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!"); /// /// let _ = std::panic::catch_unwind(|| { /// LATE.init(|| panic!()); /// }); /// /// assert_eq!(LATE.init(|| leak_value("Yay".to_string())), &"Yay"); /// /// assert_eq!(EARLY.init(|| panic!()), &"Hello!"); /// /// ``` #[inline] pub fn init<F>(&self, initializer: F) -> T where F: FnOnce() -> T, { self.try_init(|| -> Result<T, std::convert::Infallible> { Ok(initializer()) }) .expect("bug:LateStaticRef::try_init should only return an Err if `initializer` does") } /// Returns `Some(x:T)` if the `LateStaticRef` was initialized, otherwise returns `None`. /// /// # Example /// /// ``` /// use abi_stable::{sabi_types::LateStaticRef, utils::leak_value}; /// /// static LATE: LateStaticRef<&String> = LateStaticRef::new(); /// /// static EARLY: LateStaticRef<&&str> = LateStaticRef::from_ref(&"Hello!"); /// /// let _ = std::panic::catch_unwind(|| { /// LATE.init(|| panic!()); /// }); /// /// assert_eq!(LATE.get(), None); /// LATE.init(|| leak_value("Yay".to_string())); /// assert_eq!(LATE.get().map(|s| s.as_str()), Some("Yay")); /// /// assert_eq!(EARLY.get(), Some(&"Hello!")); /// /// ``` pub fn get(&self) -> Option<T> { unsafe { T::from_raw_ptr(self.pointer.load(Ordering::Acquire) as *const T::PtrTarget) } } } use ::std::panic::{RefUnwindSafe, UnwindSafe}; impl<T> UnwindSafe for LateStaticRef<T> {} impl<T> RefUnwindSafe for LateStaticRef<T> {} ////////////////////////////////////////////////////// //#[cfg(test)] #[cfg(all(test, not(feature = "only_new_tests")))] mod tests { use super::*; use std::panic::catch_unwind; static N_100: u32 = 100; static N_277: u32 = 277; #[test] fn test_init() { let ptr = LateStaticRef::<&u32>::new(); assert_eq!(None, ptr.get()); let caught = catch_unwind(|| { ptr.init(|| panic!()); }); assert!(caught.is_err()); assert_eq!(None, ptr.get()); assert_eq!(100, *ptr.init(|| &N_100)); assert_eq!(100, *ptr.init(|| panic!("this should not run"))); assert_eq!((&N_100) as *const u32, ptr.get().unwrap() as *const u32); } #[test] fn test_try_init() { let ptr = LateStaticRef::<&u32>::new(); assert_eq!(None, ptr.get()); let caught = catch_unwind(|| { let _ = ptr.try_init(|| -> Result<_, i32> { panic!() }); }); assert!(caught.is_err()); assert_eq!(None, ptr.get()); assert_eq!(Err(10), ptr.try_init(|| -> Result<_, i32> { Err(10) })); assert_eq!(Err(17), ptr.try_init(|| -> Result<_, i32> { Err(17) })); assert_eq!(Ok(&277), ptr.try_init(|| -> Result<_, i32> { Ok(&N_277) })); assert_eq!( Ok(&277), ptr.try_init(|| -> Result<_, i32> { panic!("this should not run") }) ); assert_eq!((&N_277) as *const u32, ptr.get().unwrap() as *const u32); } } ////////////////////////////////////////////////////////////////////////////////
use std::fs::File; use std::io::BufReader; use std::io::Read; use std::collections::HashSet; use regex::Regex; use petgraph::graphmap::DiGraphMap; use petgraph::Incoming; //use petgraph::dot::{Dot, Config}; fn part1(g : &DiGraphMap<&str, i64>) -> i64 { let mut count : i64 = 0; let mut to_visit : Vec<&str> = g.neighbors("shiny gold").collect(); let mut visited : HashSet<&str> = HashSet::new(); while !to_visit.is_empty() { let elem : &str = match to_visit.pop() { Some(inner) => inner, None => break, }; if visited.contains(elem) { // Really wanted to be sure continue; } visited.insert(elem); count += 1; for n in g.neighbors(elem) { if !visited.contains(n) { to_visit.push(n); } } } count } fn part2(g : &DiGraphMap<&str, i64>, colour : &str) -> i64 { let mut content : i64 = 0; let to_visit : Vec<&str> = g.neighbors_directed(colour, Incoming) .collect(); if to_visit.is_empty() { return content; } for node in to_visit { let weight = match g.edge_weight(node, colour) { Some(inner) => inner, None => continue, }; content += weight + weight * part2(g, node); } content } fn main() { let file = File::open("input").expect("Failed to read file input"); let mut buf_reader = BufReader::new(file); let mut contents = String::new(); buf_reader.read_to_string(&mut contents) .expect("Failed to bufferize file input"); let lines = contents.lines(); let re_container = Regex::new(r"^(.*?) bags contain (\d .*).") .unwrap(); let re_content = Regex::new(r"^(\d+) (.*?) bag") .unwrap(); let mut g = DiGraphMap::<&str, i64>::new(); for line in lines { let caps = match re_container.captures(line) { Some(inner) => inner, None => continue, }; let container = caps.get(1).unwrap().as_str(); let content : Vec<&str> = caps .get(2).unwrap().as_str().split(',').collect(); for elem in content { let caps_content = match re_content.captures(elem.trim()) { Some(inner) => inner, None => continue, }; let num : i64 = match caps_content.get(1) .unwrap().as_str().trim().parse() { Ok(num) => num, Err(_) => continue, }; let colour = caps_content.get(2).unwrap().as_str(); g.add_edge(colour, container, num); } //add_edge(&mut g, container, content); } println!("Count: {}", part1(&g)); println!("Count: {}", part2(&g, "shiny gold")); //println!("{:?}", Dot::with_config(&g, &[Config::EdgeNoLabel])); }
#[macro_use] extern crate serde_derive; extern crate bincode; pub mod model; pub mod protocol; #[cfg(test)] mod tests { #[test] fn it_works() { let x = super::protocol::Packet::Join{nickname: "hi"}; let encoded: Vec<u8> = super::protocol::serialize(&x).unwrap(); let decoded: super::protocol::Packet = super::protocol::deserialize(&encoded).unwrap(); assert_eq!(x, decoded); } }
// 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::{ capability::*, model::{addable_directory::AddableDirectory, *}, }, directory_broker, fidl::endpoints::{ClientEnd, ServerEnd}, fidl_fuchsia_io::DirectoryMarker, fuchsia_async as fasync, fuchsia_vfs_pseudo_fs::directory, fuchsia_vfs_pseudo_fs::directory::entry::DirectoryEntry, fuchsia_zircon as zx, futures::{executor::block_on, future::BoxFuture, lock::Mutex, prelude::*}, std::{cmp::Eq, collections::HashMap, fmt, ops::Deref, pin::Pin, sync::Arc}, }; struct ComponentInstance { pub abs_moniker: AbsoluteMoniker, pub children: Mutex<Vec<Arc<ComponentInstance>>>, } impl Clone for ComponentInstance { // This is used by TestHook. ComponentInstance is immutable so when a change // needs to be made, TestHook clones ComponentInstance and makes the change // in the new copy. fn clone(&self) -> Self { let children = block_on(self.children.lock()); return ComponentInstance { abs_moniker: self.abs_moniker.clone(), children: Mutex::new(children.clone()), }; } } impl PartialEq for ComponentInstance { fn eq(&self, other: &Self) -> bool { self.abs_moniker == other.abs_moniker } } impl Eq for ComponentInstance {} impl ComponentInstance { pub async fn print(&self) -> String { let mut s: String = self.abs_moniker.leaf().map_or(String::new(), |m| format!("{}", m.to_partial())); let mut children = self.children.lock().await; if children.is_empty() { return s; } // The position of a child in the children vector is a function of timing. // In order to produce stable topology strings across runs, we sort the set // of children here by moniker. children.sort_by(|a, b| a.abs_moniker.cmp(&b.abs_moniker)); s.push('('); let mut count = 0; for child in children.iter() { // If we've seen a previous child, then add a comma to separate children. if count > 0 { s.push(','); } s.push_str(&child.boxed_print().await); count += 1; } s.push(')'); s } fn boxed_print<'a>(&'a self) -> Pin<Box<dyn Future<Output = String> + 'a>> { Box::pin(self.print()) } } #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum Lifecycle { Bind(AbsoluteMoniker), Stop(AbsoluteMoniker), Destroy(AbsoluteMoniker), } impl fmt::Display for Lifecycle { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self { Lifecycle::Bind(m) => write!(f, "bind({})", m), Lifecycle::Stop(m) => write!(f, "stop({})", m), Lifecycle::Destroy(m) => write!(f, "destroy({})", m), } } } #[derive(Clone)] pub struct TestHook { inner: Arc<TestHookInner>, } pub struct TestHookInner { instances: Mutex<HashMap<AbsoluteMoniker, Arc<ComponentInstance>>>, lifecycle_events: Mutex<Vec<Lifecycle>>, } impl fmt::Display for TestHook { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "{}", self.inner.print())?; Ok(()) } } impl TestHook { pub fn new() -> TestHook { TestHook { inner: Arc::new(TestHookInner::new()) } } /// Returns the set of hooks into the component manager that TestHook is interested in. pub fn hooks(&self) -> Vec<HookRegistration> { vec![ HookRegistration { event_type: EventType::AddDynamicChild, callback: self.inner.clone(), }, HookRegistration { event_type: EventType::PreDestroyInstance, callback: self.inner.clone(), }, HookRegistration { event_type: EventType::BindInstance, callback: self.inner.clone() }, HookRegistration { event_type: EventType::StopInstance, callback: self.inner.clone() }, HookRegistration { event_type: EventType::PostDestroyInstance, callback: self.inner.clone(), }, ] } /// Recursively traverse the Instance tree to generate a string representing the component /// topology. pub fn print(&self) -> String { self.inner.print() } pub fn lifecycle(&self) -> Vec<Lifecycle> { self.inner.lifecycle() } } /// TestHook is a Hook that generates a strings representing the component /// topology. impl TestHookInner { pub fn new() -> TestHookInner { let abs_moniker = AbsoluteMoniker::root(); let instance = ComponentInstance { abs_moniker: abs_moniker.clone(), children: Mutex::new(vec![]) }; let mut instances = HashMap::new(); instances.insert(abs_moniker, Arc::new(instance)); TestHookInner { instances: Mutex::new(instances), lifecycle_events: Mutex::new(vec![]) } } /// Recursively traverse the Instance tree to generate a string representing the component /// topology. pub fn print(&self) -> String { let instances = block_on(self.instances.lock()); let abs_moniker = AbsoluteMoniker::root(); let root_instance = instances.get(&abs_moniker).map(|x| x.clone()).expect("Unable to find root instance."); block_on(root_instance.print()) } /// Return the sequence of lifecycle events. pub fn lifecycle(&self) -> Vec<Lifecycle> { block_on(self.lifecycle_events.lock()).clone() } pub async fn on_bind_instance_async<'a>( &'a self, realm: Arc<Realm>, live_child_realms: &'a Vec<Arc<Realm>>, ) -> Result<(), ModelError> { self.create_instance_if_necessary(realm.abs_moniker.clone()).await?; for child_realm in live_child_realms { self.create_instance_if_necessary(child_realm.abs_moniker.clone()).await?; } let mut events = self.lifecycle_events.lock().await; events.push(Lifecycle::Bind(realm.abs_moniker.clone())); Ok(()) } pub async fn on_stop_instance_async<'a>(&'a self, realm: Arc<Realm>) -> Result<(), ModelError> { let mut events = self.lifecycle_events.lock().await; events.push(Lifecycle::Stop(realm.abs_moniker.clone())); Ok(()) } pub async fn on_destroy_instance_async<'a>( &'a self, realm: Arc<Realm>, ) -> Result<(), ModelError> { let mut events = self.lifecycle_events.lock().await; events.push(Lifecycle::Destroy(realm.abs_moniker.clone())); Ok(()) } pub async fn create_instance_if_necessary( &self, abs_moniker: AbsoluteMoniker, ) -> Result<(), ModelError> { let mut instances = self.instances.lock().await; if let Some(parent_moniker) = abs_moniker.parent() { // If the parent isn't available yet then opt_parent_instance will have a value // of None. let opt_parent_instance = instances.get(&parent_moniker).map(|x| x.clone()); let new_instance = match instances.get(&abs_moniker) { Some(old_instance) => Arc::new((old_instance.deref()).clone()), None => Arc::new(ComponentInstance { abs_moniker: abs_moniker.clone(), children: Mutex::new(vec![]), }), }; instances.insert(abs_moniker.clone(), new_instance.clone()); // If the parent is available then add this instance as a child to it. if let Some(parent_instance) = opt_parent_instance { let mut children = parent_instance.children.lock().await; let opt_index = children.iter().position(|c| c.abs_moniker == new_instance.abs_moniker); if let Some(index) = opt_index { children.remove(index); } children.push(new_instance.clone()); } } Ok(()) } pub async fn remove_instance(&self, abs_moniker: AbsoluteMoniker) -> Result<(), ModelError> { let mut instances = self.instances.lock().await; if let Some(parent_moniker) = abs_moniker.parent() { instances.remove(&abs_moniker); let parent_instance = instances .get(&parent_moniker) .expect(&format!("parent instance {} not found", parent_moniker)); let mut children = parent_instance.children.lock().await; let opt_index = children.iter().position(|c| c.abs_moniker == abs_moniker); if let Some(index) = opt_index { children.remove(index); } } Ok(()) } } impl Hook for TestHookInner { fn on<'a>(self: Arc<Self>, event: &'a Event) -> BoxFuture<'a, Result<(), ModelError>> { Box::pin(async move { match event { Event::BindInstance { realm, component_decl: _, live_child_realms, routing_facade: _, } => { self.on_bind_instance_async(realm.clone(), live_child_realms).await?; } Event::AddDynamicChild { realm } => { self.create_instance_if_necessary(realm.abs_moniker.clone()).await?; } Event::PreDestroyInstance { realm } => { // This action only applies to dynamic children if let Some(child_moniker) = realm.abs_moniker.leaf() { if child_moniker.collection().is_some() { self.remove_instance(realm.abs_moniker.clone()).await?; } } } Event::StopInstance { realm } => { self.on_stop_instance_async(realm.clone()).await?; } Event::PostDestroyInstance { realm } => { self.on_destroy_instance_async(realm.clone()).await?; } _ => (), }; Ok(()) }) } } pub struct HubInjectionTestHook {} impl HubInjectionTestHook { pub fn new() -> Self { HubInjectionTestHook {} } pub async fn on_route_framework_capability_async<'a>( &'a self, realm: Arc<Realm>, capability: &'a ComponentManagerCapability, mut capability_provider: Option<Box<dyn ComponentManagerCapabilityProvider>>, ) -> Result<Option<Box<dyn ComponentManagerCapabilityProvider>>, ModelError> { // This Hook is about injecting itself between the Hub and the Model. // If the Hub hasn't been installed, then there's nothing to do here. let mut relative_path = match (&capability_provider, capability) { (Some(_), ComponentManagerCapability::Directory(source_path)) => source_path.split(), _ => return Ok(capability_provider), }; if relative_path.is_empty() || relative_path.remove(0) != "hub" { return Ok(capability_provider); } Ok(Some(Box::new(HubInjectionCapabilityProvider::new( realm.abs_moniker.clone(), relative_path, capability_provider.take().expect("Unable to take original capability."), )))) } } impl Hook for HubInjectionTestHook { fn on<'a>(self: Arc<Self>, event: &'a Event) -> BoxFuture<'a, Result<(), ModelError>> { Box::pin(async move { if let Event::RouteFrameworkCapability { realm, capability, capability_provider } = event { let mut capability_provider = capability_provider.lock().await; *capability_provider = self .on_route_framework_capability_async( realm.clone(), capability, capability_provider.take(), ) .await?; } Ok(()) }) } } struct HubInjectionCapabilityProvider { abs_moniker: AbsoluteMoniker, relative_path: Vec<String>, intercepted_capability: Box<dyn ComponentManagerCapabilityProvider>, } impl HubInjectionCapabilityProvider { pub fn new( abs_moniker: AbsoluteMoniker, relative_path: Vec<String>, intercepted_capability: Box<dyn ComponentManagerCapabilityProvider>, ) -> Self { HubInjectionCapabilityProvider { abs_moniker, relative_path, intercepted_capability } } pub async fn open_async( &self, flags: u32, open_mode: u32, relative_path: String, server_end: zx::Channel, ) -> Result<(), ModelError> { let mut dir_path = self.relative_path.clone(); dir_path.append( &mut relative_path .split("/") .map(|s| s.to_string()) .filter(|s| !s.is_empty()) .collect::<Vec<String>>(), ); let (client_chan, server_chan) = zx::Channel::create().unwrap(); self.intercepted_capability.open(flags, open_mode, String::new(), server_chan).await?; let hub_proxy = ClientEnd::<DirectoryMarker>::new(client_chan) .into_proxy() .expect("failed to create directory proxy"); let mut dir = directory::simple::empty(); dir.add_node( "old_hub", directory_broker::DirectoryBroker::from_directory_proxy(hub_proxy), &self.abs_moniker, )?; dir.open( flags, open_mode, &mut dir_path.iter().map(|s| s.as_str()), ServerEnd::new(server_end), ); fasync::spawn(async move { let _ = dir.await; }); Ok(()) } } impl ComponentManagerCapabilityProvider for HubInjectionCapabilityProvider { fn open( &self, flags: u32, open_mode: u32, relative_path: String, server_chan: zx::Channel, ) -> BoxFuture<Result<(), ModelError>> { Box::pin(self.open_async(flags, open_mode, relative_path, server_chan)) } } #[cfg(test)] mod tests { use super::*; #[fuchsia_async::run_singlethreaded(test)] async fn test_hook_test() { let a: AbsoluteMoniker = vec!["a:0"].into(); let ab: AbsoluteMoniker = vec!["a:0", "b:0"].into(); let ac: AbsoluteMoniker = vec!["a:0", "c:0"].into(); let abd: AbsoluteMoniker = vec!["a:0", "b:0", "d:0"].into(); let abe: AbsoluteMoniker = vec!["a:0", "b:0", "e:0"].into(); let acf: AbsoluteMoniker = vec!["a:0", "c:0", "f:0"].into(); // Try adding parent followed by children then verify the topology string // is correct. { let test_hook = TestHookInner::new(); assert!(test_hook.create_instance_if_necessary(a.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(ab.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(ac.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(abd.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(abe.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(acf.clone()).await.is_ok()); assert_eq!("(a(b(d,e),c(f)))", test_hook.print()); } // Changing the order of monikers should not affect the output string. { let test_hook = TestHookInner::new(); assert!(test_hook.create_instance_if_necessary(a.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(ac.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(ab.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(abd.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(abe.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(acf.clone()).await.is_ok()); assert_eq!("(a(b(d,e),c(f)))", test_hook.print()); } // Submitting children before parents should still succeed. { let test_hook = TestHookInner::new(); assert!(test_hook.create_instance_if_necessary(acf.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(abe.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(abd.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(ab.clone()).await.is_ok()); // Model will call create_instance_if_necessary for ab's children again // after the call to bind_instance for ab. assert!(test_hook.create_instance_if_necessary(abe.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(abd.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(ac.clone()).await.is_ok()); // Model will call create_instance_if_necessary for ac's children again // after the call to bind_instance for ac. assert!(test_hook.create_instance_if_necessary(acf.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(a.clone()).await.is_ok()); // Model will call create_instance_if_necessary for a's children again // after the call to bind_instance for a. assert!(test_hook.create_instance_if_necessary(ab.clone()).await.is_ok()); assert!(test_hook.create_instance_if_necessary(ac.clone()).await.is_ok()); assert_eq!("(a(b(d,e),c(f)))", test_hook.print()); } } }
pub mod any_all; pub mod by_ref; pub mod chain; pub mod consumer; pub mod cycle; pub mod filter_map_flat_map; pub mod find; pub mod fold; pub mod iterator; pub mod iterator_ii; pub mod map_filter; pub mod nth_last; pub mod peekable; pub mod position; pub mod scan; pub mod skip_take; pub mod zip;
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use std::convert::TryInto; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; use crate::erlang::unique_integer::{unique_integer, Options}; #[native_implemented::function(erlang:unique_integer/1)] pub fn result(process: &Process, options: Term) -> exception::Result<Term> { let options_options: Options = options.try_into()?; Ok(unique_integer(process, options_options)) }
use crate::game; pub struct Engine { pub game: game::Game, } impl Engine { pub fn init(&mut self) { } pub fn start(&mut self) { self.game.welcome(); loop { self.game.play(); if !self.game.playing() { break } } self.game.gameover(); } pub fn recycle(&self) { } }
use crate::flat; use crate::flat::PrimitiveSubtype::*; use crate::raw::Spanned; use serde::{Deserialize, Serialize}; use std::cmp; use std::convert::TryFrom; pub fn typeshape(ty: &Type, wire_format: WireFormat) -> TypeShape { let unalined_size = unaligned_size(ty, wire_format); let alignment = alignment(ty, false, wire_format); TypeShape { inline_size: align_to(unalined_size, alignment), alignment: alignment, depth: depth(ty, wire_format), max_handles: max_handles(ty, wire_format), max_out_of_line: max_out_of_line(ty, wire_format), has_padding: has_padding(ty, false, wire_format), has_flexible_envelope: has_flexible_envelope(ty, wire_format), contains_union: contains_union(ty, wire_format), } } #[derive(Debug, Copy, Clone)] pub enum WireFormat { V1, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct TypeShape { /// The inline size of this type, including padding for the type's minimum alignment. For /// example, "struct S { uint32 a; uint16 b; };" will have an inline_size of 8, not 6: the /// "packed" size of the struct is 6, but the alignment of its largest member is 4, so 6 is /// rounded up to 8. inline_size: u32, /// The minimum alignment required by this type. alignment: u32, /// These values are calculated incorporating both the current TypeShape, and recursively over /// all child fields. A value of std::numeric_limits<uint32_t>::max() means that the value is /// potentially unbounded, which can happen for self-recursive aggregate objects. For flexible /// types, these values is calculated based on the currently-defined members, and does _not_ /// take potential future members into account. depth: u32, max_handles: u32, max_out_of_line: u32, /// `has_padding` is true if this type has _either_ inline or out-of-line padding. For flexible /// types, `has_padding` is calculated based on the currently-defined members, and does _not_ /// take potential future members into account. (If it did, `has_padding` would have to be true /// for all flexible types, which doesn't make it very useful.) has_padding: bool, has_flexible_envelope: bool, /// Whether this type transitively contains a union. If this is false, union/xunion /// transformations can be avoided contains_union: bool, } /// `FieldShape` describes the offset and padding information for members that are contained within /// an aggregate type (e.g. struct/union). TODO(fxb/36337): We can update `FieldShape` to be a /// simple offset+padding struct, and remove the getter/setter methods since they're purely for /// backward-compatibility with existing code. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct FieldShape { offset: u32, padding: u32, } #[derive(Debug, Clone)] pub enum Type { /// The type that contains all of its elements. Second parameter indicates /// whether this is a flexible envelope Product(Vec<Box<Type>>, bool), /// The type that may contain any one of its elements Sum(Vec<Box<Type>>), /// An Array is just a Product with the same type multiple times Array(Box<Type>, u64), /// A 64bit pointer that MAY point to out of line content Ptr(Box<Type>), /// A 64bit pointer that MUST point to out of line content Boxed(Box<Type>), /// A 32 bit handle Handle, /// A primitive type Primitive(flat::PrimitiveSubtype), } // TODO: this should probably take a Spanned<Box<Type>> pub fn desugar(ty: &flat::Type, scope: &flat::Libraries, nullable: bool) -> Type { match ty { flat::Type::Struct(val) => { let result = Type::Product( val.members .iter() .map(|sp| Box::new(desugar(&*sp.value.ty.value, scope, false))) .collect(), false, ); if nullable { Type::Ptr(Box::new(result)) } else { result } } flat::Type::Bits(val) => desugar(val.get_type(), scope, false), flat::Type::Enum(val) => desugar(val.get_type(), scope, false), flat::Type::Table(table) => { let member_types = table .members .iter() .filter_map(|member| match &member.value.inner { flat::TableMemberInner::Reserved => None, flat::TableMemberInner::Used { ty, .. } => Some(Box::new(envelope( desugar(&*ty.value, scope, false), table.strictness().is_flexible(), ))), }) .collect(); Type::Product( vec![ Box::new(Type::Primitive(UInt64)), // num elements Box::new(Type::Boxed(Box::new(Type::Product(member_types, false)))), ], false, ) } flat::Type::Union(union) => { let variants = union .members .iter() .filter_map(|member| match &member.value.inner { flat::UnionMemberInner::Reserved => None, flat::UnionMemberInner::Used { ty, .. } => { Some(Box::new(desugar(&*ty.value, scope, false))) } }) .collect(); let inner = if nullable { envelope(Type::Sum(variants), union.strictness().is_flexible()) } else { nn_envelope(Type::Sum(variants), union.strictness().is_flexible()) }; Type::Product( vec![ Box::new(Type::Primitive(UInt64)), // ordinal Box::new(inner), ], false, ) } flat::Type::Identifier(name) => desugar( &scope.get_type(flat::dummy_span(name)).unwrap().value, scope, nullable, ), flat::Type::Ptr(val) => desugar(&*val.value, scope, true), flat::Type::Array(flat::Array { element_type, size }) => Type::Array( Box::new(desugar( &*element_type.as_ref().unwrap().value, scope, false, )), eval_size(size, scope), ), flat::Type::Vector(flat::Vector { element_type, bounds, }) => { let ty = Box::new(desugar( &*element_type.as_ref().unwrap().value, scope, false, )); let size = eval_size(bounds, scope); if nullable { vector(ty, size) } else { nn_vector(ty, size) } } flat::Type::Str(flat::Str { bounds }) => { let ty = Box::new(Type::Primitive(UInt8)); let size = eval_size(bounds, scope); if nullable { vector(ty, size) } else { nn_vector(ty, size) } } flat::Type::Handle(_) | flat::Type::ClientEnd(_) | flat::Type::ServerEnd(_) => Type::Handle, flat::Type::Primitive(subtype) => Type::Primitive(*subtype), flat::Type::TypeSubstitution(_) => desugar( &flat::eval_type(flat::dummy_span(ty), scope).unwrap().value, scope, nullable, ), // should panic or return error flat::Type::Any | flat::Type::Int => unimplemented!(), } } fn nn_envelope(ty: Type, is_flexible: bool) -> Type { Type::Product( vec![ Box::new(Type::Primitive(UInt32)), Box::new(Type::Primitive(UInt32)), Box::new(Type::Boxed(Box::new(ty))), ], is_flexible, ) } fn envelope(ty: Type, is_flexible: bool) -> Type { Type::Product( vec![ Box::new(Type::Primitive(UInt32)), Box::new(Type::Primitive(UInt32)), Box::new(Type::Ptr(Box::new(ty))), ], is_flexible, ) } fn nn_vector(element_type: Box<Type>, bounds: u64) -> Type { Type::Product( vec![ Box::new(Type::Primitive(UInt64)), // num elements Box::new(Type::Boxed(Box::new(Type::Array(element_type, bounds)))), ], false, ) } fn vector(element_type: Box<Type>, bounds: u64) -> Type { Type::Product( vec![ Box::new(Type::Primitive(UInt64)), // num elements Box::new(Type::Ptr(Box::new(Type::Array(element_type, bounds)))), ], false, ) } fn eval_size(term: &Option<Spanned<Box<flat::Term>>>, scope: &flat::Libraries) -> u64 { term.as_ref().map_or(std::u64::MAX, |term| { let result = flat::eval_term(term.into(), scope).unwrap(); if let flat::Term::Int(val) = result.value { u64::try_from(*val).unwrap() } else { panic!("you dun goofed") } }) } fn unaligned_size(ty: &Type, wire_format: WireFormat) -> u32 { use Type::*; match ty { Product(members, _) => { if members.is_empty() { return 1; } members .iter() .map(|member| unaligned_size(&*member, wire_format)) .sum() } Sum(members) => members .iter() .map(|member| unaligned_size(&*member, wire_format)) .max() .unwrap_or(1), Array(ty, size) => unaligned_size(&*ty, wire_format).saturating_mul(*size as u32), Ptr(_) | Boxed(_) => 8, Handle => 4, Primitive(subtype) => match subtype { Bool | Int8 | UInt8 => 1, Int16 | UInt16 => 2, Int32 | UInt32 | Float32 => 4, Int64 | UInt64 | Float64 => 8, }, } } fn alignment(ty: &Type, ool: bool, wire_format: WireFormat) -> u32 { use Type::*; match ty { Sum(members) | Product(members, _) => members .iter() .map(|member| alignment(&*member, ool, wire_format)) .max() .unwrap_or(1), Array(ty, _) => alignment(&*ty, ool, wire_format), Ptr(_) | Boxed(_) => 8, Handle | Primitive(_) => { let min = if ool { 8 } else { 0 }; cmp::max(min, unaligned_size(ty, wire_format)) } } } fn depth(ty: &Type, wire_format: WireFormat) -> u32 { use Type::*; match ty { Sum(members) | Product(members, _) => members .iter() .map(|member| depth(&*member, wire_format)) .max() .unwrap_or(0), Array(ty, _) => depth(&*ty, wire_format), Ptr(ty) | Boxed(ty) => 1 + depth(&*ty, wire_format), Handle | Primitive(_) => 0, } } fn max_handles(ty: &Type, wire_format: WireFormat) -> u32 { use Type::*; match ty { Sum(members) | Product(members, _) => members .iter() .map(|member| max_handles(&*member, wire_format)) .sum::<u32>(), Array(ty, size) => max_handles(&*ty, wire_format).saturating_mul(*size as u32), Ptr(ty) | Boxed(ty) => max_handles(&*ty, wire_format), Handle => 1, Primitive(_) => 0, } } fn max_out_of_line(ty: &Type, wire_format: WireFormat) -> u32 { use Type::*; match ty { Product(members, _) => { // can't just use .sum() here because we want to .saturating_add let mut result: u32 = 0; for member in members { result = result.saturating_add(max_out_of_line(&*member, wire_format)); } result } Sum(members) => members .iter() .map(|member| max_out_of_line(&*member, wire_format)) .max() .unwrap_or(0), Array(ty, size) => max_out_of_line(&*ty, wire_format).saturating_mul(*size as u32), Ptr(ty) | Boxed(ty) => { unaligned_size(&*ty, wire_format).saturating_add(max_out_of_line(&*ty, wire_format)) } Handle | Primitive(_) => 0, } } // TODO fn has_padding(ty: &Type, ool: bool, wire_format: WireFormat) -> bool { use Type::*; match ty { Product(members, _) => { let fieldshapes = fieldshapes(ty, ool, wire_format).unwrap(); let inline_padding = fieldshapes.iter().any(|shape| shape.padding > 0); let inherent_padding = members .iter() .any(|member| has_padding(member, ool, wire_format)); inline_padding || inherent_padding } // TODO(fxb/36331) Sum(_) => true, Array(ty, _) => { let alignment = alignment(&*ty, ool, wire_format); let has_trailing_padding = unaligned_size(&*ty, wire_format) % alignment != 0; has_padding(&*ty, ool, wire_format) || has_trailing_padding } Ptr(ty) | Boxed(ty) => has_padding(&*ty, true, wire_format), Handle | Primitive(_) => false, } } fn has_flexible_envelope(ty: &Type, wire_format: WireFormat) -> bool { use Type::*; match ty { Product(_, true) => true, Sum(members) | Product(members, _) => members .iter() .any(|member| has_flexible_envelope(&*member, wire_format)), Boxed(ty) | Array(ty, _) | Ptr(ty) => has_flexible_envelope(&*ty, wire_format), Handle | Primitive(_) => false, } } fn contains_union(ty: &Type, wire_format: WireFormat) -> bool { use Type::*; match ty { Product(members, _) => members .iter() .any(|member| contains_union(&*member, wire_format)), // currently only a union can desugar to a sum Sum(_) => true, Array(ty, _) | Ptr(ty) | Boxed(ty) => contains_union(&*ty, wire_format), Handle | Primitive(_) => false, } } pub fn fieldshapes(ty: &Type, ool: bool, wire_format: WireFormat) -> Option<Vec<FieldShape>> { use Type::*; match ty { Product(members, _) => { // alignments[i] is the alignment that member[i] needs to pad to; // for all members it's the alignment of the next member except for // the last member, where it's the alignment of the object let mut alignments: Vec<u32> = members .iter() .skip(1) .map(|member| alignment(member, ool, wire_format)) .collect(); alignments.push(alignment(ty, ool, wire_format)); let mut offset = 0; Some( members .iter() .enumerate() .map(|(i, member)| { let size = unaligned_size(&*member, wire_format); let padding = padding(offset + size, alignments[i]); let ret = FieldShape { offset, padding }; offset += size + padding; ret }) .collect(), ) } _ => None, } } fn padding(offset: u32, alignment: u32) -> u32 { (!offset + 1) & (alignment - 1) } // Some things are probably incorrect because the alignment of OOL objects and how it // works is not clear to me // fn object_align(size: u32) -> u32 { // align_to(size, 8) // } fn align_to(size: u32, alignment: u32) -> u32 { (size + (alignment - 1)) & !(alignment - 1) }
use std::fmt; #[derive(Clone, Copy, PartialEq, Eq)] pub struct TextRange { start: u32, end: u32, } impl fmt::Debug for TextRange { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "[{}; {})", self.start(), self.end()) } } impl TextRange { pub fn from_to(start: u32, end: u32) -> TextRange { assert!(start <= end, "Invalid range, start: {} end: {}", start, end); TextRange { start: start, end: end } } pub fn start(&self) -> u32 { self.start } pub fn end(&self) -> u32 { self.end } pub fn empty() -> TextRange { TextRange::from_to(0, 0) } pub fn is_subrange_of(self, other: TextRange) -> bool { other.start() <= self.start() && self.end() <= other.end() } pub fn is_empty(&self) -> bool { self.start() == self.end() } pub fn glue(&self, right: TextRange) -> TextRange { assert_eq!(self.end(), right.start()); TextRange::from_to(self.start(), right.end()) } } #[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)] pub struct TextOffset(u32); impl TextOffset { pub fn in_range(range: TextRange, off: usize) -> Option<TextOffset> { let off = TextOffset(off as u32); if is_offset_in_range(off, range) { Some(off) } else { None } } } impl fmt::Debug for TextOffset { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { self.0.fmt(f) } } pub fn is_offset_in_range(offset: TextOffset, range: TextRange) -> bool { return range.start <= offset.0 && offset.0 <= range.end } impl ::std::ops::Index<TextRange> for str { type Output = str; fn index(&self, index: TextRange) -> &str { &self[index.start() as usize..index.end() as usize] } } impl ::std::ops::Index<TextRange> for String { type Output = str; fn index(&self, index: TextRange) -> &str { &self[index.start() as usize..index.end() as usize] } }
// #[derive(Debug)] // struct Country { // pop: usize, // capital: String, // leader_name: String, // } // fn main() { // let pop = 500; // let capital = "Dora".to_string(); // let leader_name = "Caleb".to_string(); // let ella = Country { // pop, // captial, // leader_name, // }; // // } // use std::fmt::Debug; // fn return_num<T: Debug>(number: T) { // println!("Number: {:?}", number); // } // fn main() { // let number = return_num(5); // } // Traits // struct Animal { // name: String // } // trait Dog { // fn bark(&self) { // println!("Woof"); // } // fn run(&self) { // println!("RUN"); // } // } // impl Dog for Animal {} // fn main() { // let rover = Animal {name: "Rover".to_string()}; // rover.bark(); // rover.run(); // } // use std::collections::HashMap; // let mut modes = HashMap::new();
// Implement repeating-key XOR // Here is the opening stanza of an important work of the English language: // Burning 'em, if you ain't quick and nimble // I go crazy when I hear a cymbal // Encrypt it, under the key "ICE", using repeating-key XOR. // In repeating-key XOR, you'll sequentially apply each byte of the key; the first byte of plaintext will be XOR'd against I, the next C, the next E, then I again for the 4th byte, and so on. // It should come out to: // 0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272 // a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f // Encrypt a bunch of stuff using your repeating-key XOR function. Encrypt your mail. Encrypt your password file. Your .sig file. Get a feel for it. I promise, we aren't wasting your time with this. mod hex; mod byte_array; fn xor(input: &str, bytes: &str) -> String { let input_bytes = byte_array::ByteArray::from_bytes(input); let mut bytes_array = vec!(); for character in bytes.chars() { bytes_array.push(character as u8); } input_bytes.xor(&bytes_array).to_byte_string() } fn main() { let input = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"; let output = xor(input, "ICE"); println!("result = {}", output); assert_eq!(output, "0b3637272a2b2e63622c2e69692a23693a2a3c6324202d623d63343c2a26226324272765272a282b2f20430a652e2c652a3124333a653e2b2027630c692b20283165286326302e27282f"); }
//! CBOR Value object representation //! //! While it is handy to be able to construct into the intermediate value //! type it is also not recommended to use it as an intermediate type //! before deserialising concrete type: //! //! - it is slow and bloated; //! - it takes a lot dynamic memory and may not be compatible with the targeted environment; //! //! This is why all the objects here are marked as deprecated use de::*; use error::Error; use len::Len; use result::Result; use se::*; use types::{Special, Type}; use std::{ collections::BTreeMap, io::{BufRead, Write}, }; #[cfg(test)] use quickcheck::{Arbitrary, Gen}; /// CBOR Object key, represents the possible supported values for /// a CBOR key in a CBOR Map. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub enum ObjectKey { Integer(u64), Bytes(Vec<u8>), Text(String), } impl ObjectKey { /// convert the given `ObjectKey` into a CBOR [`Value`](./struct.Value.html) pub fn value(self) -> Value { match self { ObjectKey::Integer(v) => Value::U64(v), ObjectKey::Bytes(v) => Value::Bytes(v), ObjectKey::Text(v) => Value::Text(v), } } } impl Serialize for ObjectKey { fn serialize<'se, W: Write + Sized>( &self, serializer: &'se mut Serializer<W>, ) -> Result<&'se mut Serializer<W>> { match self { ObjectKey::Integer(ref v) => serializer.write_unsigned_integer(*v), ObjectKey::Bytes(ref v) => serializer.write_bytes(v), ObjectKey::Text(ref v) => serializer.write_text(v), } } } impl Deserialize for ObjectKey { fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> { match raw.cbor_type()? { Type::UnsignedInteger => Ok(ObjectKey::Integer(raw.unsigned_integer()?)), Type::Bytes => Ok(ObjectKey::Bytes(raw.bytes()?)), Type::Text => Ok(ObjectKey::Text(raw.text()?)), t => Err(Error::CustomError(format!( "Type `{:?}' is not a support type for CBOR Map's key", t ))), } } } /// All possible CBOR supported values. /// /// We advise not to use these objects as an intermediary representation before /// retrieving custom types as it is a slow and not memory efficient way to do /// so. However it is handy for debugging or reverse a given protocol. /// #[derive(Debug, Clone, PartialEq, PartialOrd)] pub enum Value { U64(u64), I64(i64), Bytes(Vec<u8>), Text(String), Array(Vec<Value>), IArray(Vec<Value>), Object(BTreeMap<ObjectKey, Value>), IObject(BTreeMap<ObjectKey, Value>), Tag(u64, Box<Value>), Special(Special), } impl Serialize for Value { fn serialize<'se, W: Write + Sized>( &self, serializer: &'se mut Serializer<W>, ) -> Result<&'se mut Serializer<W>> { match self { Value::U64(ref v) => serializer.write_unsigned_integer(*v), Value::I64(ref v) => serializer.write_negative_integer(*v), Value::Bytes(ref v) => serializer.write_bytes(v), Value::Text(ref v) => serializer.write_text(v), Value::Array(ref v) => { serializer.write_array(Len::Len(v.len() as u64))?; for element in v { serializer.serialize(element)?; } Ok(serializer) } Value::IArray(ref v) => { serializer.write_array(Len::Indefinite)?; for element in v { serializer.serialize(element)?; } serializer.write_special(Special::Break) } Value::Object(ref v) => { serializer.write_map(Len::Len(v.len() as u64))?; for element in v { serializer.serialize(element.0)?.serialize(element.1)?; } Ok(serializer) } Value::IObject(ref v) => { serializer.write_map(Len::Indefinite)?; for element in v { serializer.serialize(element.0)?.serialize(element.1)?; } serializer.write_special(Special::Break) } Value::Tag(ref tag, ref v) => serializer.write_tag(*tag)?.serialize(v.as_ref()), Value::Special(ref v) => serializer.write_special(*v), } } } impl Deserialize for Value { fn deserialize<R: BufRead>(raw: &mut Deserializer<R>) -> Result<Self> { match raw.cbor_type()? { Type::UnsignedInteger => Ok(Value::U64(raw.unsigned_integer()?)), Type::NegativeInteger => Ok(Value::I64(raw.negative_integer()?)), Type::Bytes => Ok(Value::Bytes(raw.bytes()?)), Type::Text => Ok(Value::Text(raw.text()?)), Type::Array => { let len = raw.array()?; let mut vec = Vec::new(); match len { Len::Indefinite => { while { let t = raw.cbor_type()?; if t == Type::Special { let special = raw.special()?; assert_eq!(special, Special::Break); false } else { vec.push(Deserialize::deserialize(raw)?); true } } {} Ok(Value::IArray(vec)) } Len::Len(len) => { for _ in 0..len { vec.push(Deserialize::deserialize(raw)?); } Ok(Value::Array(vec)) } } } Type::Map => { let len = raw.map()?; let mut vec = BTreeMap::new(); match len { Len::Indefinite => { while { let t = raw.cbor_type()?; if t == Type::Special { let special = raw.special()?; assert_eq!(special, Special::Break); false } else { let k = Deserialize::deserialize(raw)?; let v = Deserialize::deserialize(raw)?; vec.insert(k, v); true } } {} Ok(Value::IObject(vec)) } Len::Len(len) => { for _ in 0..len { let k = Deserialize::deserialize(raw)?; let v = Deserialize::deserialize(raw)?; vec.insert(k, v); } Ok(Value::Object(vec)) } } } Type::Tag => { let tag = raw.tag()?; Ok(Value::Tag(tag, Box::new(Deserialize::deserialize(raw)?))) } Type::Special => Ok(Value::Special(raw.special()?)), } } } #[cfg(test)] impl Arbitrary for ObjectKey { fn arbitrary<G: Gen>(g: &mut G) -> Self { match u8::arbitrary(g) % 3 { 0 => ObjectKey::Integer(Arbitrary::arbitrary(g)), 1 => ObjectKey::Bytes(Arbitrary::arbitrary(g)), 2 => ObjectKey::Text(Arbitrary::arbitrary(g)), _ => unreachable!(), } } } #[cfg(test)] fn arbitrary_value_finite<G: Gen>(g: &mut G) -> Value { match u8::arbitrary(g) % 5 { 0 => Value::U64(Arbitrary::arbitrary(g)), 1 => Value::I64(Arbitrary::arbitrary(g)), 2 => Value::Bytes(Arbitrary::arbitrary(g)), 3 => Value::Text(Arbitrary::arbitrary(g)), 4 => Value::Special(Arbitrary::arbitrary(g)), _ => unreachable!(), } } #[cfg(test)] fn arbitrary_value_indefinite<G: Gen>(counter: usize, g: &mut G) -> Value { use std::iter::repeat_with; if counter == 0 { arbitrary_value_finite(g) } else { match u8::arbitrary(g) % 5 { 0 => Value::U64(u64::arbitrary(g)), 1 => Value::I64(i64::arbitrary(g)), 2 => Value::Bytes(Arbitrary::arbitrary(g)), 3 => Value::Text(Arbitrary::arbitrary(g)), 4 => { let size = usize::arbitrary(g); Value::Array( repeat_with(|| arbitrary_value_indefinite(counter - 1, g)) .take(size) .collect(), ) } 5 => { let size = usize::arbitrary(g); Value::IArray( repeat_with(|| arbitrary_value_indefinite(counter - 1, g)) .take(size) .collect(), ) } 6 => { let size = usize::arbitrary(g); Value::Object( repeat_with(|| { ( ObjectKey::arbitrary(g), arbitrary_value_indefinite(counter - 1, g), ) }) .take(size) .collect(), ) } 7 => { let size = usize::arbitrary(g); Value::IObject( repeat_with(|| { ( ObjectKey::arbitrary(g), arbitrary_value_indefinite(counter - 1, g), ) }) .take(size) .collect(), ) } 8 => Value::Tag( u64::arbitrary(g), arbitrary_value_indefinite(counter - 1, g).into(), ), 9 => Value::Special(Arbitrary::arbitrary(g)), _ => unreachable!(), } } } #[cfg(test)] impl Arbitrary for Value { fn arbitrary<G: Gen>(g: &mut G) -> Self { arbitrary_value_indefinite(3, g) } } #[cfg(test)] mod test { use super::super::test_encode_decode; use super::*; #[test] fn u64() { assert!(test_encode_decode(&Value::U64(0)).unwrap()); assert!(test_encode_decode(&Value::U64(23)).unwrap()); assert!(test_encode_decode(&Value::U64(0xff)).unwrap()); assert!(test_encode_decode(&Value::U64(0x100)).unwrap()); assert!(test_encode_decode(&Value::U64(0xffff)).unwrap()); assert!(test_encode_decode(&Value::U64(0x10000)).unwrap()); assert!(test_encode_decode(&Value::U64(0xffffffff)).unwrap()); assert!(test_encode_decode(&Value::U64(0x100000000)).unwrap()); assert!(test_encode_decode(&Value::U64(0xffffffffffffffff)).unwrap()); } #[test] fn i64() { assert!(test_encode_decode(&Value::I64(0)).unwrap()); assert!(test_encode_decode(&Value::I64(23)).unwrap()); assert!(test_encode_decode(&Value::I64(-99)).unwrap()); assert!(test_encode_decode(&Value::I64(99999)).unwrap()); assert!(test_encode_decode(&Value::I64(-9999999)).unwrap()); assert!(test_encode_decode(&Value::I64(-283749237289)).unwrap()); assert!(test_encode_decode(&Value::I64(93892929229)).unwrap()); } #[test] fn bytes() { assert!(test_encode_decode(&Value::Bytes(vec![])).unwrap()); assert!(test_encode_decode(&Value::Bytes(vec![0; 23])).unwrap()); assert!(test_encode_decode(&Value::Bytes(vec![0; 24])).unwrap()); assert!(test_encode_decode(&Value::Bytes(vec![0; 256])).unwrap()); assert!(test_encode_decode(&Value::Bytes(vec![0; 10293])).unwrap()); assert!(test_encode_decode(&Value::Bytes(vec![0; 99999000])).unwrap()); } #[test] fn text() { assert!(test_encode_decode(&Value::Text("".to_owned())).unwrap()); assert!(test_encode_decode(&Value::Text("hellow world".to_owned())).unwrap()); assert!(test_encode_decode(&Value::Text("some sentence, some sentence... some sentence...some sentence, some sentence... some sentence...".to_owned())).unwrap()); } #[test] fn array() { assert!(test_encode_decode(&Value::Array(vec![])).unwrap()); assert!(test_encode_decode(&Value::Array(vec![ Value::U64(0), Value::Text("some text".to_owned()) ])) .unwrap()); } #[test] fn iarray() { assert!(test_encode_decode(&Value::IArray(vec![])).unwrap()); assert!(test_encode_decode(&Value::IArray(vec![ Value::U64(0), Value::Text("some text".to_owned()) ])) .unwrap()); } #[test] fn tag() { assert!(test_encode_decode(&Value::Tag(23, Box::new(Value::U64(0)))).unwrap()); assert!(test_encode_decode(&Value::Tag(24, Box::new(Value::Bytes(vec![0; 32])))).unwrap()); assert!( test_encode_decode(&Value::Tag(0x1ff, Box::new(Value::Bytes(vec![0; 624])))).unwrap() ); } quickcheck! { fn property_encode_decode(value: Value) -> bool { test_encode_decode(&value).unwrap() } } }
use super::RECURSIVE_INDICATOR; use crate::{ abi_stability::stable_abi_trait::get_type_layout, sabi_types::Constructor, std_types::RSlice, test_utils::AlwaysDisplay, type_layout::TypeLayout, StableAbi, }; mod display { use super::*; #[repr(C)] #[derive(StableAbi)] #[sabi(phantom_const_param = STRUCT_0_LAYS)] pub(super) struct Struct0; #[repr(C)] #[derive(StableAbi)] #[sabi(phantom_const_param = STRUCT_1_LAYS)] pub(super) struct Struct1; #[repr(C)] #[derive(StableAbi)] #[sabi(phantom_const_param = STRUCT_2_LAYS)] pub(super) struct Struct2; const STRUCT_0_LAYS: RSlice<'static, AlwaysDisplay<Constructor<&'static TypeLayout>>> = rslice![]; const STRUCT_1_LAYS: RSlice<'static, AlwaysDisplay<Constructor<&'static TypeLayout>>> = rslice![AlwaysDisplay(Constructor(get_type_layout::<Struct1>)),]; const STRUCT_2_LAYS: RSlice<'static, AlwaysDisplay<Constructor<&'static TypeLayout>>> = rslice![ AlwaysDisplay(Constructor(get_type_layout::<Struct2>)), AlwaysDisplay(Constructor(get_type_layout::<Struct2>)), ]; } #[test] fn recursive_display() { let list = vec![ <display::Struct0 as StableAbi>::LAYOUT, <display::Struct1 as StableAbi>::LAYOUT, <display::Struct2 as StableAbi>::LAYOUT, ]; for (i, layout) in list.into_iter().enumerate() { let matches = layout.to_string().matches(RECURSIVE_INDICATOR).count(); assert_eq!(matches, i); { let full_type = layout.full_type(); let matches = full_type.to_string().matches(RECURSIVE_INDICATOR).count(); assert_eq!(matches, i, "\n{}\n", full_type); let name_matches = full_type.to_string().matches("align").count(); assert_eq!(name_matches, i, "\n{}\n", full_type); } } } mod debug { use super::*; #[repr(C)] #[derive(StableAbi)] #[sabi(phantom_const_param = STRUCT_0_LAYS)] pub(super) struct Struct0; #[repr(C)] #[derive(StableAbi)] #[sabi(phantom_const_param = STRUCT_1_LAYS)] pub(super) struct Struct1; #[repr(C)] #[derive(StableAbi)] #[sabi(phantom_const_param = STRUCT_2_LAYS)] pub(super) struct Struct2; const STRUCT_0_LAYS: RSlice<'static, Constructor<&'static TypeLayout>> = rslice![]; const STRUCT_1_LAYS: RSlice<'static, Constructor<&'static TypeLayout>> = rslice![Constructor(get_type_layout::<Struct1>),]; const STRUCT_2_LAYS: RSlice<'static, Constructor<&'static TypeLayout>> = rslice![ Constructor(get_type_layout::<Struct2>), Constructor(get_type_layout::<Struct2>), ]; } #[test] fn recursive_debug() { let list = vec![ <debug::Struct0 as StableAbi>::LAYOUT, <debug::Struct1 as StableAbi>::LAYOUT, <debug::Struct2 as StableAbi>::LAYOUT, ]; for (i, layout) in list.into_iter().enumerate() { { let formatted = format!("{:#?}", layout); let matches = formatted.matches(RECURSIVE_INDICATOR).count(); assert_eq!(matches, i * 2, "\n{}\n", formatted); } { let full_type = layout.full_type(); let formatted = format!("{:#?}", full_type); let matches = formatted.matches(RECURSIVE_INDICATOR).count(); assert_eq!(matches, i, "\n{}\n", formatted); let name_matches = formatted.to_string().matches("align").count(); assert_eq!(name_matches, i, "\n{}\n", formatted); } } }
#[macro_use(lazy_static)] extern crate lazy_static; extern crate serde; #[macro_use] extern crate specs_derive; use std::fmt::Display; use rltk::console; use specs::prelude::*; use specs::saveload::{SimpleMarker, SimpleMarkerAllocator}; use specs::WorldExt; pub use components::*; pub use context::*; pub use game_log::*; pub use gui::*; pub use map::*; pub use player::*; pub use random::*; pub use save_load_system::*; pub use spawner::*; pub use state::*; pub use systems::*; pub use turn_decider::*; rltk::add_wasm_support!(); mod systems; mod map; mod player; mod components; mod state; mod random; mod spawner; mod gui; mod game_log; mod context; mod turn_decider; mod save_load_system; pub const DEBUG: bool = true; pub const TITLE: &str = "Goblin War Party"; fn main() { const MAP_WIDTH: i32 = 80; const MAP_HEIGHT: i32 = 43; const WINDOW_WIDTH: i32 = 80; const WINDOW_HEIGHT: i32 = 50; let mut state = State { ecs: World::new(), systems: SysRunner::new() }; state.ecs.insert(RunStateHolder { run_state: RunState::PreRun }); state.ecs.insert(GameLog::new_with_first_log(format!("Welcome to {}", TITLE))); state.ecs.insert(ParticleBuilder::new()); state.ecs.register::<Position>(); state.ecs.register::<Renderable>(); state.ecs.register::<Player>(); state.ecs.register::<Viewshed>(); state.ecs.register::<Monster>(); state.ecs.register::<Name>(); state.ecs.register::<BlocksTile>(); state.ecs.register::<CombatStats>(); state.ecs.register::<WantsToMelee>(); state.ecs.register::<SuffersDamage>(); state.ecs.register::<Item>(); state.ecs.register::<InBackpack>(); state.ecs.register::<WantsToPickUp>(); state.ecs.register::<WantsToUseItem>(); state.ecs.register::<WantsToDrop>(); state.ecs.register::<Consumable>(); state.ecs.register::<ProvidesHealing>(); state.ecs.register::<Ranged>(); state.ecs.register::<InflictsDamage>(); state.ecs.register::<AreaOfEffect>(); state.ecs.register::<Confusion>(); state.ecs.register::<WantsToTakeTurn>(); state.ecs.register::<TakesTurn>(); state.ecs.register::<GlobalTurn>(); state.ecs.register::<WantsToMove>(); state.ecs.register::<WantsToWait>(); state.ecs.register::<IsVisible>(); state.ecs.register::<CanMove>(); state.ecs.register::<CanMelee>(); state.ecs.register::<ParticleLifetime>(); state.ecs.register::<RenderBackground>(); state.ecs.register::<RenderAura>(); state.ecs.register::<SimpleMarker<SerializeMe>>(); state.ecs.register::<SerializationHelper>(); state.ecs.insert(SimpleMarkerAllocator::<SerializeMe>::new()); let map = new_map_rooms_and_corridors(MAP_WIDTH, MAP_HEIGHT); spawner::spawn_global_turn(&mut state.ecs); spawner::spawn_map(&mut state.ecs, &map); state.ecs.insert(map); let context = build_context(WINDOW_WIDTH, WINDOW_HEIGHT, TITLE); rltk::main_loop(context, state); } pub fn console_log<S: Display>(message: S) { if DEBUG { console::log(message); } }
use actix_web::{error, http::StatusCode, HttpRequest, HttpResponse}; use thiserror::Error; use crate::models::ErrorResponse; #[derive(Error, Debug)] pub enum CustomError { #[error("A validation error has occurred.")] ValidationError, #[error("The specified resource cannot be found.")] NotFound, #[error("An invalid request has been detected.")] BadRequest, #[error("Attempted access to the specified resource is forbidden.")] Forbidden, #[error("A database error has occurred.")] DbError, #[error("An internal server error has occurred.")] Internal, } impl CustomError { pub fn name(&self) -> String { match self { Self::ValidationError => "Validation Error".to_string(), Self::NotFound => "Not Found".to_string(), Self::BadRequest => "Bad Request".to_string(), Self::Forbidden => "Forbidden Error".to_string(), Self::DbError => "Database Error".to_string(), Self::Internal => "Internal Server Error".to_string(), } } } impl error::ResponseError for CustomError { fn status_code(&self) -> StatusCode { match *self { Self::ValidationError => StatusCode::BAD_REQUEST, Self::NotFound => StatusCode::NOT_FOUND, Self::BadRequest => StatusCode::BAD_REQUEST, Self::Forbidden => StatusCode::FORBIDDEN, Self::DbError => StatusCode::INTERNAL_SERVER_ERROR, Self::Internal => StatusCode::INTERNAL_SERVER_ERROR, } } fn error_response(&self) -> HttpResponse { let status_code = self.status_code(); let error_response = ErrorResponse { code: status_code.as_u16(), message: self.to_string(), error: self.name(), }; HttpResponse::build(status_code).json(error_response) } } pub fn map_io_error(e: std::io::Error) -> CustomError { match e.kind() { std::io::ErrorKind::InvalidInput => CustomError::BadRequest, std::io::ErrorKind::PermissionDenied => CustomError::Forbidden, _ => CustomError::Internal, } } pub fn json_error_handler(err: error::JsonPayloadError, _req: &HttpRequest) -> error::Error { let status_code = StatusCode::BAD_REQUEST; let error_response = ErrorResponse { code: status_code.as_u16(), message: "A malformed JSON payload format has been detected.".to_string(), error: "Bad Request".to_string(), }; let res = HttpResponse::build(status_code).json(error_response); error::InternalError::from_response(err, res).into() } pub fn query_error_handler(err: error::QueryPayloadError, _req: &HttpRequest) -> error::Error { let status_code = StatusCode::BAD_REQUEST; let error_response = ErrorResponse { code: status_code.as_u16(), message: "A malformed query format has been detected.".to_string(), error: "Bad Request".to_string(), }; let res = HttpResponse::build(status_code).json(error_response); error::InternalError::from_response(err, res).into() } // Define unit tests for each error type. #[cfg(test)] mod tests { use actix_web::{http::StatusCode, ResponseError}; use super::CustomError; #[test] fn test_default_message_validation_error() { let validation_error: CustomError = CustomError::ValidationError; assert_eq!( validation_error.status_code(), StatusCode::BAD_REQUEST, "Default status code should be shown" ); assert_eq!( validation_error.name(), "Validation Error".to_string(), "Default name should be shown" ); assert_eq!( validation_error.to_string(), "A validation error has occurred.".to_string(), "Default message should be shown" ); } #[test] fn test_default_message_not_found() { let not_found: CustomError = CustomError::NotFound; assert_eq!( not_found.status_code(), StatusCode::NOT_FOUND, "Default status code should be shown" ); assert_eq!( not_found.name(), "Not Found".to_string(), "Default name should be shown" ); assert_eq!( not_found.to_string(), "The specified resource cannot be found.".to_string(), "Default message should be shown" ); } #[test] fn test_default_message_bad_request() { let bad_request: CustomError = CustomError::BadRequest; assert_eq!( bad_request.status_code(), StatusCode::BAD_REQUEST, "Default status code should be shown" ); assert_eq!( bad_request.name(), "Bad Request".to_string(), "Default name should be shown" ); assert_eq!( bad_request.to_string(), "An invalid request has been detected.".to_string(), "Default message should be shown" ); } #[test] fn test_default_message_forbidden() { let forbidden: CustomError = CustomError::Forbidden; assert_eq!( forbidden.status_code(), StatusCode::FORBIDDEN, "Default status code should be shown" ); assert_eq!( forbidden.name(), "Forbidden Error".to_string(), "Default name should be shown" ); assert_eq!( forbidden.to_string(), "Attempted access to the specified resource is forbidden.".to_string(), "Default message should be shown" ); } #[test] fn test_default_message_db_error() { let db_error: CustomError = CustomError::DbError; assert_eq!( db_error.status_code(), StatusCode::INTERNAL_SERVER_ERROR, "Default status code should be shown" ); assert_eq!( db_error.name(), "Database Error".to_string(), "Default name should be shown" ); assert_eq!( db_error.to_string(), "A database error has occurred.".to_string(), "Default message should be shown" ); } #[test] fn test_default_message_internal() { let internal: CustomError = CustomError::Internal; assert_eq!( internal.status_code(), StatusCode::INTERNAL_SERVER_ERROR, "Default status code should be shown" ); assert_eq!( internal.name(), "Internal Server Error".to_string(), "Default name should be shown" ); assert_eq!( internal.to_string(), "An internal server error has occurred.".to_string(), "Default message should be shown" ); } }
fn main(){ println!("Hello the world!"); }
pub struct IntBST { root: Option<Box<TreeNode>>, size: isize, } impl IntBST { pub fn new() -> IntBST { IntBST { root: None, size: 0, } } pub fn addR(&mut self, x:isize) { self.addH(x, &self.root); self.size += 1; } fn addH(&mut self, x:isize, rt:&Option<Box<TreeNode>>) -> &Option<Box<TreeNode>> { if let Some(node) = rt { if x <= (*node).val { (*node).left = *self.addH(x, &node.left); // Some(Box::new( // TreeNode { // val: x, // left: *self.addH(x, (*node).left), // right: node.right, // } // )) } else { (*node).right = *self.addH(x, &node.right); // Some(Box::new( // TreeNode { // val: x, // left: node.left, // right: *self.addH(x, (*node).right), // } // )) } &Some(*node) } else { &Some(Box::new(TreeNode::new(x))) } } pub fn addI(&mut self, x:isize) { let mut leader = &self.root; loop { if let Some(mut node) = leader { if x <= (*node).val { node.left = match &node.left { Some(val) => { leader = &val.left; Some(*val) }, None => Some(Box::new(TreeNode::new(x))), } } else { leader = &node.right; } } } self.size += 1; } pub fn inorder(&self) { self.inorderH(&self.root); println!(); } fn inorderH(&self, rt:&Option<Box<TreeNode>>) { if let Some(node) = rt { self.inorderH(&node.left); println!("{} ", node.val); self.inorderH(&node.right); } } pub fn preorder(&self) { self.preorderH(&self.root); println!(); } fn preorderH(&self, rt:&Option<Box<TreeNode>>) { if let Some(node) = rt { println!("{} ", node.val); self.inorderH(&node.left); self.inorderH(&node.right); } } pub fn postorder(&self) { self.postorderH(&self.root); println!(); } fn postorderH(&self, rt:&Option<Box<TreeNode>>) { if let Some(node) = rt { self.preorderH(&node.left); self.preorderH(&node.right); println!("{} ", node.val); } } fn remove(&mut self, val:isize) -> bool { match &mut self.root { Some(node) => { let tmp = &mut node; removeR(tmp, tmp, &TreeNode::new(val), true) }, None => false, } } } #[derive(Debug, Clone)] struct TreeNode { val: isize, left: Option<Box<TreeNode>>, right: Option<Box<TreeNode>>, } impl TreeNode { fn new(val:isize) -> TreeNode { TreeNode { val, left: None, right: None, } } pub fn isLeaf(&self) -> bool { match (&self.right, &self.left) { (None, None) => true, _ => false, } } } fn maxNode(rt:&TreeNode) -> &TreeNode { let mut ans = rt; loop { match &ans.right { Some(node) => ans = &*node, None => break, } } ans } fn minNode(rt:&TreeNode) -> &TreeNode { let mut ans = rt; loop { match &ans.left { Some(node) => ans = &*node, None => break, } } ans } fn remove(root:&TreeNode, target:&TreeNode) -> bool { let mut leader = root; let mut follower = root; let mut isRight = true; loop { if target.val > leader.val { match &leader.right { Some(boxed) => { follower = leader; leader = &*boxed; isRight = true; continue; }, None => return false, } } else if target.val < leader.val { match &leader.left { Some(boxed) => { follower = leader; leader = &*boxed; isRight = false; continue; }, None => return false, } } else { if isRight {follower.right = None; return true;} else {follower.left = None; return true;} } } } fn removeR(prev:&TreeNode, root:&TreeNode, target:&TreeNode, isRight:bool) -> bool { if target.val > root.val { match &root.right { Some(node) => removeR(&root, &*node, target, true), None => false, } } else if target.val < root.val { match &root.left { Some(node) => removeR(&root, &*node, target, false), None => false, } } else { if isRight {prev.right = None;} else {prev.left = None;} true } }
use crate::TimeTracker; use std::fs::OpenOptions; impl<'a> TimeTracker<'a> { pub fn clear(&self) { OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&self.config.raw_data_path) .unwrap(); OpenOptions::new() .write(true) .truncate(true) .create(true) .open(&self.config.processed_data_path) .unwrap(); } }
use crate::Region; use game_lib::{ bevy::{math::Vec2, reflect::Reflect}, derive_more::{Add, AddAssign, Display, From, Into, Sub, SubAssign}, serde::{Deserialize, Serialize}, }; use std::{ convert::{TryFrom, TryInto}, num::TryFromIntError, ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg}, }; macro_rules! pos_type { ( $(#[$pos_meta:meta])* $pos_name:ident, $(#[$rect_meta:meta])* $rect_name:ident, $(#[$coord_meta:meta])* $coord_name:ident = $coord_ty:ty, ($zero:expr, $one:expr), [$($impl:tt),*] ) => { $(#[$coord_meta])* pub type $coord_name = $coord_ty; #[derive( Clone, Copy, PartialEq, Debug, Display, Default, From, Into, Add, AddAssign, Sub, SubAssign, Reflect, Serialize, Deserialize, )] #[display(fmt = "({}, {})", x, y)] #[serde(crate = "game_lib::serde")] $(#[$pos_meta])* pub struct $pos_name { pub x: $coord_name, pub y: $coord_name, } impl $pos_name { pub const ZERO: Self = Self::new($zero, $zero); pub const ONE: Self = Self::new($one, $one); pub const X: Self = Self::new($one, $zero); pub const Y: Self = Self::new($zero, $one); pub const fn new(x: $coord_name, y: $coord_name) -> Self { $pos_name { x, y } } pub fn offset(mut self, x: $coord_name, y: $coord_name) -> Self { self.x += x; self.y += y; self } pub fn xx(self) -> Self { $pos_name::new(self.x, self.x) } pub fn yx(self) -> Self { $pos_name::new(self.y, self.x) } pub fn yy(self) -> Self { $pos_name::new(self.y, self.y) } } impl Mul<$coord_name> for $pos_name { type Output = Self; fn mul(mut self, value: $coord_name) -> Self { self.mul_assign(value); self } } impl MulAssign<$coord_name> for $pos_name { fn mul_assign(&mut self, value: $coord_name) { self.x *= value; self.y *= value; } } impl Mul<$pos_name> for $pos_name { type Output = Self; fn mul(mut self, value: $pos_name) -> Self { self.mul_assign(value); self } } impl MulAssign<$pos_name> for $pos_name { fn mul_assign(&mut self, value: $pos_name) { self.x *= value.x; self.y *= value.y; } } impl Div<$coord_name> for $pos_name { type Output = Self; fn div(mut self, value: $coord_name) -> Self { self.div_assign(value); self } } impl DivAssign<$coord_name> for $pos_name { fn div_assign(&mut self, value: $coord_name) { self.x /= value; self.y /= value; } } impl Div<$pos_name> for $pos_name { type Output = Self; fn div(mut self, value: $pos_name) -> Self { self.div_assign(value); self } } impl DivAssign<$pos_name> for $pos_name { fn div_assign(&mut self, value: $pos_name) { self.x /= value.x; self.y /= value.y; } } impl From<Vec2> for $pos_name { fn from(value: Vec2) -> Self { let x = value[0] as $coord_name; let y = value[1] as $coord_name; $pos_name::new(x, y) } } impl From<$pos_name> for Vec2 { fn from(position: $pos_name) -> Self { Vec2::new(position.x as f32, position.y as f32) } } #[derive(Clone, Copy, PartialEq, Debug, Default, Reflect, Serialize, Deserialize)] #[serde(crate = "game_lib::serde")] $(#[$rect_meta])* pub struct $rect_name { pub bottom_left: $pos_name, pub size: $pos_name, } impl $rect_name { pub const fn new(bottom_left: $pos_name, size: $pos_name) -> Self { $rect_name { bottom_left, size } } pub fn from_center(center: $pos_name, radius: $pos_name) -> Self { $rect_name::new(center - radius, radius + radius) } pub fn left(self) -> $coord_name { self.bottom_left.x } pub fn right(self) -> $coord_name { self.bottom_left.x + self.size.x } pub fn top(self) -> $coord_name { self.bottom_left.y + self.size.y } pub fn bottom(self) -> $coord_name { self.bottom_left.y } pub fn bottom_left(self) -> $pos_name { self.bottom_left } pub fn bottom_right(self) -> $pos_name { self.bottom_left + self.size * $pos_name::X } pub fn top_left(self) -> $pos_name { self.bottom_left + self.size * $pos_name::Y } pub fn top_right(self) -> $pos_name { self.bottom_left + self.size } pub fn size(self) -> $pos_name { self.size } pub fn width(self) -> $coord_name { self.size.x } pub fn height(self) -> $coord_name { self.size.y } pub fn expand(mut self, diameter: $coord_name) -> Self { self.bottom_left -= $pos_name::ONE * diameter; self.size += $pos_name::ONE * diameter * ($one + $one); self } pub fn offset(mut self, offset: $pos_name) -> Self { self.bottom_left += offset; self } } $(pos_type!(@impl $impl, $pos_name, $rect_name, $coord_name, ($zero, $one));)* }; (@impl step, $pos_name:ident, $rect_name:ident, $coord_name:ident, ($_zero:expr, $_one:expr)) => { impl $rect_name { pub fn iter_positions(self) -> impl Iterator<Item = $pos_name> + Clone { (self.bottom()..self.top()).flat_map(move |y| { (self.left()..self.right()).map(move |x| $pos_name::new(x, y)) }) } } }; (@impl signed, $pos_name:ident, $rect_name:ident, $coord_name:ident, ($_zero:expr, $_one:expr)) => { impl $pos_name { pub fn signum(mut self) -> Self { self.x = self.x.signum(); self.y = self.y.signum(); self } } impl Neg for $pos_name { type Output = Self; fn neg(mut self) -> Self { self.x = -self.x; self.y = -self.y; self } } }; (@impl float, $pos_name:ident, $rect_name:ident, $coord_name:ident, ($zero:expr, $one:expr)) => { impl $pos_name { pub fn is_finite(self) -> bool { self.x.is_finite() && self.y.is_finite() } pub fn floor(mut self) -> Self { self.x = self.x.floor(); self.y = self.y.floor(); self } pub fn ceil(mut self) -> Self { self.x = self.x.ceil(); self.y = self.y.ceil(); self } pub fn round(mut self) -> Self { self.x = self.x.round(); self.y = self.y.round(); self } } impl $rect_name { pub fn center(&self) -> $pos_name { self.bottom_left + self.size / ($one + $one) } } }; } pos_type!( /// A global position within the world. Given that the world is a grid of /// tiles, this is a position of a tile within that grid. #[derive(Eq, Hash)] TileWorldPosition, /// A rectangle within the world. #[derive(Eq, Hash)] TileWorldRect, /// A global coordinate within the world. TileWorldCoordinate = i32, (0, 1), [step, signed] ); pos_type!( /// A position within a region, relative to that region. #[derive(Eq, Hash)] TileRegionPosition, /// A rectangle within a region. #[derive(Eq, Hash)] TileRegionRect, /// A region-local coordinate. TileRegionCoordinate = u8, (0, 1), [step] ); pos_type!( /// A position of a region within the world. Given that the world is a grid /// of regions, this is a position of a region within that grid. #[derive(Eq, Hash)] RegionWorldPosition, /// A rectangle which selects region within the world. #[derive(Eq, Hash)] RegionWorldRect, /// A coordinate of a region within the world. This follows a different /// scale than [WorldCoordinate] by being a coordinate given the world is /// split into [Region::Width] by [Region::HEIGHT] squares of tiles. RegionWorldCoordinate = i32, (0, 1), [step, signed] ); pos_type!( /// A position of an entity within the world. EntityWorldPosition, /// A rectangle in the world using entity coordinates. EntityWorldRect, /// A coordinate of an entity within the world. EntityWorldCoordinate = f32, (0.0, 1.0), [signed, float] ); impl From<TileRegionPosition> for TileWorldPosition { fn from(value: TileRegionPosition) -> Self { TileWorldPosition::new(value.x.into(), value.y.into()) } } impl From<TileRegionRect> for TileWorldRect { fn from(value: TileRegionRect) -> Self { TileWorldRect::new(value.bottom_left.into(), value.size.into()) } } impl From<RegionWorldPosition> for TileWorldPosition { fn from(value: RegionWorldPosition) -> Self { TileWorldPosition::new( value.x * TileWorldCoordinate::from(Region::WIDTH), value.y * TileWorldCoordinate::from(Region::HEIGHT), ) } } impl From<RegionWorldRect> for TileWorldRect { fn from(value: RegionWorldRect) -> Self { TileWorldRect::new( value.bottom_left.into(), TileWorldPosition::new( value.size.x * TileWorldCoordinate::from(Region::WIDTH), value.size.y * TileWorldCoordinate::from(Region::HEIGHT), ), ) } } impl From<TileWorldPosition> for RegionWorldPosition { fn from(value: TileWorldPosition) -> Self { RegionWorldPosition::new( value.x.div_euclid(TileWorldCoordinate::from(Region::WIDTH)), value .y .div_euclid(TileWorldCoordinate::from(Region::HEIGHT)), ) } } impl From<TileWorldRect> for RegionWorldRect { fn from(value: TileWorldRect) -> Self { let offset = TileWorldPosition::new( TileWorldCoordinate::from(Region::WIDTH) - 1, TileWorldCoordinate::from(Region::HEIGHT) - 1, ); let bottom_left = value.bottom_left.into(); let top_right: RegionWorldPosition = (value.top_right() + offset).into(); let size = top_right - bottom_left; RegionWorldRect::new(bottom_left, size) } } impl TryFrom<TileWorldPosition> for TileRegionPosition { type Error = TryFromIntError; fn try_from(TileWorldPosition { x, y }: TileWorldPosition) -> Result<Self, Self::Error> { Ok(TileRegionPosition::new(x.try_into()?, y.try_into()?)) } } impl From<EntityWorldRect> for TileWorldRect { fn from(value: EntityWorldRect) -> Self { let bottom_left = value.bottom_left.floor(); let bottom_left = TileWorldPosition::new( bottom_left.x as TileWorldCoordinate, bottom_left.y as TileWorldCoordinate, ); let top_right = value.top_right().ceil(); let top_right = TileWorldPosition::new( top_right.x as TileWorldCoordinate, top_right.y as TileWorldCoordinate, ); TileWorldRect::new(bottom_left, top_right - bottom_left) } } impl Add<TileRegionPosition> for TileWorldPosition { type Output = Self; fn add(mut self, rhs: TileRegionPosition) -> Self::Output { self += rhs; self } } impl AddAssign<TileRegionPosition> for TileWorldPosition { fn add_assign(&mut self, rhs: TileRegionPosition) { self.x += i32::from(rhs.x); self.y += i32::from(rhs.y); } } #[cfg(test)] mod tests { use super::*; #[test] fn world_position_to_world_region_position() { fn check( expected_x: RegionWorldCoordinate, expected_y: RegionWorldCoordinate, world_x: TileWorldCoordinate, world_y: TileWorldCoordinate, ) { let world_position = TileWorldPosition::new(world_x, world_y); let expected = RegionWorldPosition::new(expected_x, expected_y); assert_eq!(expected, RegionWorldPosition::from(world_position)); } check(0, 0, 0, 0); check(0, 0, 1, 1); check(-1, -1, -1, -1); check(4, 3, (Region::WIDTH * 4).into(), (Region::WIDTH * 3).into()); check(-2, -1, -(TileWorldCoordinate::from(Region::WIDTH) + 1), -4); } #[test] fn world_rect_to_world_region_rect() { fn check(expected: RegionWorldRect, world_rect: TileWorldRect) { assert_eq!(expected, RegionWorldRect::from(world_rect)); } check( RegionWorldRect::new(RegionWorldPosition::ZERO, RegionWorldPosition::ONE), TileWorldRect::new(TileWorldPosition::ZERO, TileWorldPosition::ONE), ); check( RegionWorldRect::new(RegionWorldPosition::ZERO, RegionWorldPosition::ONE), TileWorldRect::new( TileWorldPosition::ZERO, TileWorldPosition::new(Region::WIDTH.into(), Region::HEIGHT.into()), ), ); check( RegionWorldRect::new( RegionWorldPosition::new(-2, -1), RegionWorldPosition::new(3, 3), ), TileWorldRect::new( TileWorldPosition::new(-(TileWorldCoordinate::from(Region::WIDTH) + 1), -1), TileWorldPosition::new( TileWorldCoordinate::from(Region::WIDTH) * 2, TileWorldCoordinate::from(Region::HEIGHT) * 2, ), ), ) } }
#[doc = "Reader of register MACHWF2R"] pub type R = crate::R<u32, super::MACHWF2R>; #[doc = "Reader of field `RXQCNT`"] pub type RXQCNT_R = crate::R<u8, u8>; #[doc = "Reader of field `TXQCNT`"] pub type TXQCNT_R = crate::R<u8, u8>; #[doc = "Reader of field `RXCHCNT`"] pub type RXCHCNT_R = crate::R<u8, u8>; #[doc = "Reader of field `TXCHCNT`"] pub type TXCHCNT_R = crate::R<u8, u8>; #[doc = "Reader of field `PPSOUTNUM`"] pub type PPSOUTNUM_R = crate::R<u8, u8>; #[doc = "Reader of field `AUXSNAPNUM`"] pub type AUXSNAPNUM_R = crate::R<u8, u8>; impl R { #[doc = "Bits 0:3 - Number of MTL Receive Queues"] #[inline(always)] pub fn rxqcnt(&self) -> RXQCNT_R { RXQCNT_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 6:9 - Number of MTL Transmit Queues"] #[inline(always)] pub fn txqcnt(&self) -> TXQCNT_R { TXQCNT_R::new(((self.bits >> 6) & 0x0f) as u8) } #[doc = "Bits 12:15 - Number of DMA Receive Channels"] #[inline(always)] pub fn rxchcnt(&self) -> RXCHCNT_R { RXCHCNT_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 18:21 - Number of DMA Transmit Channels"] #[inline(always)] pub fn txchcnt(&self) -> TXCHCNT_R { TXCHCNT_R::new(((self.bits >> 18) & 0x0f) as u8) } #[doc = "Bits 24:26 - Number of PPS Outputs"] #[inline(always)] pub fn ppsoutnum(&self) -> PPSOUTNUM_R { PPSOUTNUM_R::new(((self.bits >> 24) & 0x07) as u8) } #[doc = "Bits 28:30 - Number of Auxiliary Snapshot Inputs"] #[inline(always)] pub fn auxsnapnum(&self) -> AUXSNAPNUM_R { AUXSNAPNUM_R::new(((self.bits >> 28) & 0x07) as u8) } }
#[doc = "Reader of register CCSIDR"] pub type R = crate::R<u32, super::CCSIDR>; #[doc = "Reader of field `LineSize`"] pub type LINESIZE_R = crate::R<u8, u8>; #[doc = "Reader of field `Associativity`"] pub type ASSOCIATIVITY_R = crate::R<u16, u16>; #[doc = "Reader of field `NumSets`"] pub type NUMSETS_R = crate::R<u16, u16>; #[doc = "Reader of field `WA`"] pub type WA_R = crate::R<bool, bool>; #[doc = "Reader of field `RA`"] pub type RA_R = crate::R<bool, bool>; #[doc = "Reader of field `WB`"] pub type WB_R = crate::R<bool, bool>; #[doc = "Reader of field `WT`"] pub type WT_R = crate::R<bool, bool>; impl R { #[doc = "Bits 0:2 - LineSize"] #[inline(always)] pub fn line_size(&self) -> LINESIZE_R { LINESIZE_R::new((self.bits & 0x07) as u8) } #[doc = "Bits 3:12 - Associativity"] #[inline(always)] pub fn associativity(&self) -> ASSOCIATIVITY_R { ASSOCIATIVITY_R::new(((self.bits >> 3) & 0x03ff) as u16) } #[doc = "Bits 13:27 - NumSets"] #[inline(always)] pub fn num_sets(&self) -> NUMSETS_R { NUMSETS_R::new(((self.bits >> 13) & 0x7fff) as u16) } #[doc = "Bit 28 - WA"] #[inline(always)] pub fn wa(&self) -> WA_R { WA_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - RA"] #[inline(always)] pub fn ra(&self) -> RA_R { RA_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - WB"] #[inline(always)] pub fn wb(&self) -> WB_R { WB_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bit 31 - WT"] #[inline(always)] pub fn wt(&self) -> WT_R { WT_R::new(((self.bits >> 31) & 0x01) != 0) } }
use std::{ cmp::Reverse, collections::{BinaryHeap, HashSet}, }; use proconio::input; fn main() { input! { n: usize, mut k: usize, a: [u64; n], }; let mut heap = BinaryHeap::new(); let mut seen = HashSet::new(); for &x in &a { if seen.contains(&x) { continue; } seen.insert(x); heap.push(Reverse(x)); } while k >= 2 { let Reverse(s) = heap.pop().unwrap(); k -= 1; for &x in &a { let y = s + x; if seen.contains(&y) { continue; } seen.insert(y); heap.push(Reverse(y)); } } let Reverse(ans) = heap.peek().unwrap(); println!("{}", ans); }
use std::env; use std::io; #[derive(Debug, Clone)] enum LexItem { LParen, RParen, Op(char), Num(u64), } fn lex(line: &str) -> Result<Vec<LexItem>, String> { let mut result = vec![]; let mut number = String::new(); for c in line.chars() { match c { '0'..='9' => number.push(c), '+' | '-' | '*' | '/' => result.push(LexItem::Op(c)), '(' => result.push(LexItem::LParen), ')' => { if number.len() > 0 { result.push(LexItem::Num(number.parse::<u64>().unwrap())); number.clear(); } result.push(LexItem::RParen); } ' ' => { if number.len() > 0 { result.push(LexItem::Num(number.parse::<u64>().unwrap())); number.clear(); } } _ => return Err(format!("unexpected character {}", c)), } } if number.len() > 0 { result.push(LexItem::Num(number.parse::<u64>().unwrap())); number.clear(); } return Ok(result); } fn rpn(tokens: Vec<LexItem>, add_before_mul: bool) -> Vec<LexItem> { let mut output = vec![]; let mut operators = vec![]; for token in tokens { #[cfg(test)] println!("token: {:?}", token); match token { LexItem::Num(_) => output.push(token), LexItem::Op(op) => { loop { if let Some(LexItem::LParen) = operators.last() { break; } else if let None = operators.last() { break; } else if let Some(LexItem::Op(c)) = operators.last() { if add_before_mul && c == &'*' && op == '+' { break; } } output.push(operators.pop().unwrap()); } operators.push(token) } LexItem::LParen => operators.push(token), LexItem::RParen => { loop { if let Some(LexItem::LParen) = operators.last() { break; } else if let None = operators.last() { break; } output.push(operators.pop().unwrap()); } if let Some(LexItem::LParen) = operators.last() { operators.pop(); } } } #[cfg(test)] println!("\toutput:{:?}", output); #[cfg(test)] println!("\toperarots:{:?}", operators); } while let Some(_) = operators.last() { output.push(operators.pop().unwrap()); } return output; } fn solve_rpn(tokens: Vec<LexItem>) -> i64 { let mut stack = vec![]; for token in tokens { match token { LexItem::Num(n) => stack.push(n as i64), LexItem::Op(op) => { let a = stack.pop().unwrap(); let b = stack.pop().unwrap(); match op { '+' => stack.push(a + b), '-' => stack.push(a - b), '*' => stack.push(a * b), '/' => stack.push(a / b), _ => panic!("LexItem:op({}) invalid operator", op), } } _ => panic!("solve_rpn invalid token{:?}", token), } } return stack.pop().unwrap(); } fn part1(line: &str) -> i64 { let tokens = lex(line).unwrap(); let prep = rpn(tokens, false); return solve_rpn(prep); } fn part2(line: &str) -> i64 { let tokens = lex(line).unwrap(); #[cfg(test)] println!("tokens: {:?}", tokens); let prep = rpn(tokens, true); #[cfg(test)] println!("rpn: {:?}", prep); return solve_rpn(prep); } fn main() -> Result<(), io::Error> { let args: Vec<String> = env::args().collect(); let text = std::fs::read_to_string(&args[1]).expect("read_to_string failed"); let mut sum = 0; if &args[2] == "1" { for line in text.lines() { sum += part1(line); } } else if &args[2] == "2" { for line in text.lines() { sum += part2(line); } } println!("{}", sum); Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_part1() { assert_eq!(part1("1 + 2 * 3 + 4 * 5 + 6"), 71); assert_eq!(part1("1 + (2 * 3) + (4 * (5 + 6))"), 51); assert_eq!(part1("2 * 3 + (4 * 5)"), 26); assert_eq!(part1("5 + (8 * 3 + 9 + 3 * 4 * 3)"), 437); assert_eq!(part1("5 * 9 * (7 * 3 * 3 + 9 * 3 + (8 + 6 * 4))"), 12240); assert_eq!( part1("((2 + 4 * 9) * (6 + 9 * 8 + 6) + 6) + 2 + 4 * 2"), 13632 ); } #[test] fn text_part2() { assert_eq!(part2("1 + 2 * 3 + 4 * 5 + 6"), 231); } }
#[doc = "Reader of register IER"] pub type R = crate::R<u32, super::IER>; #[doc = "Writer for register IER"] pub type W = crate::W<u32, super::IER>; #[doc = "Register IER `reset()`'s with value 0"] impl crate::ResetValue for super::IER { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TAMP1IE`"] pub type TAMP1IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TAMP1IE`"] pub struct TAMP1IE_W<'a> { w: &'a mut W, } impl<'a> TAMP1IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01); self.w } } #[doc = "Reader of field `TAMP2IE`"] pub type TAMP2IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TAMP2IE`"] pub struct TAMP2IE_W<'a> { w: &'a mut W, } impl<'a> TAMP2IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1); self.w } } #[doc = "Reader of field `ITAMP1IE`"] pub type ITAMP1IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ITAMP1IE`"] pub struct ITAMP1IE_W<'a> { w: &'a mut W, } impl<'a> ITAMP1IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `ITAMP3IE`"] pub type ITAMP3IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ITAMP3IE`"] pub struct ITAMP3IE_W<'a> { w: &'a mut W, } impl<'a> ITAMP3IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `ITAMP4IE`"] pub type ITAMP4IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ITAMP4IE`"] pub struct ITAMP4IE_W<'a> { w: &'a mut W, } impl<'a> ITAMP4IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `ITAMP5IE`"] pub type ITAMP5IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ITAMP5IE`"] pub struct ITAMP5IE_W<'a> { w: &'a mut W, } impl<'a> ITAMP5IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } #[doc = "Reader of field `ITAMP6IE`"] pub type ITAMP6IE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `ITAMP6IE`"] pub struct ITAMP6IE_W<'a> { w: &'a mut W, } impl<'a> ITAMP6IE_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21); self.w } } impl R { #[doc = "Bit 0 - TAMP1IE"] #[inline(always)] pub fn tamp1ie(&self) -> TAMP1IE_R { TAMP1IE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - TAMP2IE"] #[inline(always)] pub fn tamp2ie(&self) -> TAMP2IE_R { TAMP2IE_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 16 - ITAMP1IE"] #[inline(always)] pub fn itamp1ie(&self) -> ITAMP1IE_R { ITAMP1IE_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 18 - ITAMP3IE"] #[inline(always)] pub fn itamp3ie(&self) -> ITAMP3IE_R { ITAMP3IE_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - ITAMP4IE"] #[inline(always)] pub fn itamp4ie(&self) -> ITAMP4IE_R { ITAMP4IE_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - ITAMP5IE"] #[inline(always)] pub fn itamp5ie(&self) -> ITAMP5IE_R { ITAMP5IE_R::new(((self.bits >> 20) & 0x01) != 0) } #[doc = "Bit 21 - ITAMP6IE"] #[inline(always)] pub fn itamp6ie(&self) -> ITAMP6IE_R { ITAMP6IE_R::new(((self.bits >> 21) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - TAMP1IE"] #[inline(always)] pub fn tamp1ie(&mut self) -> TAMP1IE_W { TAMP1IE_W { w: self } } #[doc = "Bit 1 - TAMP2IE"] #[inline(always)] pub fn tamp2ie(&mut self) -> TAMP2IE_W { TAMP2IE_W { w: self } } #[doc = "Bit 16 - ITAMP1IE"] #[inline(always)] pub fn itamp1ie(&mut self) -> ITAMP1IE_W { ITAMP1IE_W { w: self } } #[doc = "Bit 18 - ITAMP3IE"] #[inline(always)] pub fn itamp3ie(&mut self) -> ITAMP3IE_W { ITAMP3IE_W { w: self } } #[doc = "Bit 19 - ITAMP4IE"] #[inline(always)] pub fn itamp4ie(&mut self) -> ITAMP4IE_W { ITAMP4IE_W { w: self } } #[doc = "Bit 20 - ITAMP5IE"] #[inline(always)] pub fn itamp5ie(&mut self) -> ITAMP5IE_W { ITAMP5IE_W { w: self } } #[doc = "Bit 21 - ITAMP6IE"] #[inline(always)] pub fn itamp6ie(&mut self) -> ITAMP6IE_W { ITAMP6IE_W { w: self } } }
//! Variable mapping and metadata. use rustc_hash::FxHashSet as HashSet; use partial_ref::{partial, PartialRef}; use varisat_formula::{Lit, Var}; use varisat_internal_proof::ProofStep; use crate::{ context::{parts::*, set_var_count, Context}, decision, proof, }; pub mod data; pub mod var_map; use data::{SamplingMode, VarData}; use var_map::{VarBiMap, VarBiMapMut, VarMap}; /// Variable mapping and metadata. pub struct Variables { /// Bidirectional mapping from user variables to global variables. /// /// Initially this is the identity mapping. This ensures that in the non-assumptions setting the /// map from used user variables to global variables is the identity. This is a requirement for /// generating proofs in non-native formats. Those proofs are not aware of variable renaming, /// but are restricted to the non-incremental setting, so this works out. /// /// This is also requried for native proofs, as they assume that the mapping during the initial /// load is the identity. global_from_user: VarBiMap, /// Bidirectional mapping from global variables to user variables. /// /// This starts with the empty mapping, so only used variables are allocated. solver_from_global: VarBiMap, /// User variables that were explicitly hidden by the user. user_freelist: HashSet<Var>, /// Global variables that can be recycled without increasing the global_watermark. global_freelist: HashSet<Var>, /// Solver variables that are unused and can be recycled. solver_freelist: HashSet<Var>, /// Variable metadata. /// /// Indexed by global variable indices. var_data: Vec<VarData>, } impl Default for Variables { fn default() -> Variables { Variables { global_from_user: VarBiMap::default(), solver_from_global: VarBiMap::default(), user_freelist: Default::default(), global_freelist: Default::default(), solver_freelist: Default::default(), var_data: vec![], } } } impl Variables { /// Number of allocated solver variables. pub fn solver_watermark(&self) -> usize { self.global_from_solver().watermark() } /// Number of allocated global variables. pub fn global_watermark(&self) -> usize { self.var_data.len() } /// Number of allocated global variables. pub fn user_watermark(&self) -> usize { self.global_from_user().watermark() } /// Iterator over all user variables that are in use. pub fn user_var_iter<'a>(&'a self) -> impl Iterator<Item = Var> + 'a { let global_from_user = self.global_from_user.fwd(); (0..self.global_from_user().watermark()) .map(Var::from_index) .filter(move |&user_var| global_from_user.get(user_var).is_some()) } /// Iterator over all global variables that are in use. pub fn global_var_iter<'a>(&'a self) -> impl Iterator<Item = Var> + 'a { (0..self.global_watermark()) .map(Var::from_index) .filter(move |&global_var| !self.var_data[global_var.index()].deleted) } /// The user to global mapping. pub fn global_from_user(&self) -> &VarMap { &self.global_from_user.fwd() } /// Mutable user to global mapping. pub fn global_from_user_mut(&mut self) -> VarBiMapMut { self.global_from_user.fwd_mut() } /// The global to solver mapping. pub fn solver_from_global(&self) -> &VarMap { &self.solver_from_global.fwd() } /// Mutable global to solver mapping. pub fn solver_from_global_mut(&mut self) -> VarBiMapMut { self.solver_from_global.fwd_mut() } /// The global to user mapping. pub fn user_from_global(&self) -> &VarMap { &self.global_from_user.bwd() } /// Mutable global to user mapping. pub fn user_from_global_mut(&mut self) -> VarBiMapMut { self.global_from_user.bwd_mut() } /// The solver to global mapping. pub fn global_from_solver(&self) -> &VarMap { &self.solver_from_global.bwd() } /// Mutable solver to global mapping. pub fn global_from_solver_mut(&mut self) -> VarBiMapMut { self.solver_from_global.bwd_mut() } /// Get an existing solver var for a user var. pub fn existing_solver_from_user(&self, user: Var) -> Var { let global = self .global_from_user() .get(user) .expect("no existing global var for user var"); let solver = self .solver_from_global() .get(global) .expect("no existing solver var for global var"); solver } /// Get an existing user var from a solver var. pub fn existing_user_from_solver(&self, solver: Var) -> Var { let global = self .global_from_solver() .get(solver) .expect("no existing global var for solver var"); let user = self .user_from_global() .get(global) .expect("no existing user var for global var"); user } /// Mutable reference to the var data for a global variable. pub fn var_data_global_mut(&mut self, global: Var) -> &mut VarData { if self.var_data.len() <= global.index() { self.var_data.resize(global.index() + 1, VarData::default()); } &mut self.var_data[global.index()] } /// Mutable reference to the var data for a solver variable. pub fn var_data_solver_mut(&mut self, solver: Var) -> &mut VarData { let global = self .global_from_solver() .get(solver) .expect("no existing global var for solver var"); &mut self.var_data[global.index()] } /// Var data for a global variable. pub fn var_data_global(&self, global: Var) -> &VarData { &self.var_data[global.index()] } /// Check if a solver var is mapped to a global var pub fn solver_var_present(&self, solver: Var) -> bool { self.global_from_solver().get(solver).is_some() } /// Get an unmapped global variable. pub fn next_unmapped_global(&self) -> Var { self.global_freelist .iter() .next() .cloned() .unwrap_or_else(|| Var::from_index(self.global_watermark())) } /// Get an unmapped global variable. pub fn next_unmapped_solver(&self) -> Var { self.solver_freelist .iter() .next() .cloned() .unwrap_or_else(|| Var::from_index(self.solver_watermark())) } /// Get an unmapped user variable. pub fn next_unmapped_user(&self) -> Var { self.user_freelist .iter() .next() .cloned() .unwrap_or_else(|| Var::from_index(self.user_watermark())) } } /// Maps a user variable into a global variable. /// /// If no matching global variable exists a new global variable is allocated. pub fn global_from_user<'a>( mut ctx: partial!(Context<'a>, mut ProofP<'a>, mut SolverStateP, mut VariablesP), user: Var, require_sampling: bool, ) -> Var { let variables = ctx.part_mut(VariablesP); if user.index() > variables.user_watermark() { // TODO use a batch proof step for this? for index in variables.user_watermark()..user.index() { global_from_user(ctx.borrow(), Var::from_index(index), false); } } let variables = ctx.part_mut(VariablesP); match variables.global_from_user().get(user) { Some(global) => { if require_sampling && variables.var_data[global.index()].sampling_mode != SamplingMode::Sample { panic!("witness variables cannot be constrained"); } global } None => { // Can we add an identity mapping? let global = match variables.var_data.get(user.index()) { Some(var_data) if var_data.deleted => user, None => user, _ => variables.next_unmapped_global(), }; *variables.var_data_global_mut(global) = VarData::user_default(); variables.global_from_user_mut().insert(global, user); variables.global_freelist.remove(&global); variables.user_freelist.remove(&user); proof::add_step( ctx.borrow(), false, &ProofStep::UserVarName { global, user: Some(user), }, ); global } } } /// Maps an existing global variable to a solver variable. /// /// If no matching solver variable exists a new one is allocated. pub fn solver_from_global<'a>( mut ctx: partial!( Context<'a>, mut AnalyzeConflictP, mut AssignmentP, mut BinaryClausesP, mut ImplGraphP, mut ProofP<'a>, mut SolverStateP, mut TmpFlagsP, mut VariablesP, mut VsidsP, mut WatchlistsP, ), global: Var, ) -> Var { let variables = ctx.part_mut(VariablesP); debug_assert!(!variables.var_data[global.index()].deleted); match variables.solver_from_global().get(global) { Some(solver) => solver, None => { let solver = variables.next_unmapped_solver(); let old_watermark = variables.global_from_solver().watermark(); variables.solver_from_global_mut().insert(solver, global); variables.solver_freelist.remove(&solver); let new_watermark = variables.global_from_solver().watermark(); if new_watermark > old_watermark { set_var_count(ctx.borrow(), new_watermark); } initialize_solver_var(ctx.borrow(), solver, global); proof::add_step( ctx.borrow(), false, &ProofStep::SolverVarName { global, solver: Some(solver), }, ); solver } } } /// Maps a user variable to a solver variable. /// /// Allocates global and solver variables as requried. pub fn solver_from_user<'a>( mut ctx: partial!( Context<'a>, mut AnalyzeConflictP, mut AssignmentP, mut BinaryClausesP, mut ImplGraphP, mut ProofP<'a>, mut SolverStateP, mut TmpFlagsP, mut VariablesP, mut VsidsP, mut WatchlistsP, ), user: Var, require_sampling: bool, ) -> Var { let global = global_from_user(ctx.borrow(), user, require_sampling); solver_from_global(ctx.borrow(), global) } /// Allocates a currently unused user variable. /// /// This is either a user variable above any user variable used so far, or a user variable that was /// previously hidden by the user. pub fn new_user_var<'a>( mut ctx: partial!(Context<'a>, mut ProofP<'a>, mut SolverStateP, mut VariablesP), ) -> Var { let variables = ctx.part_mut(VariablesP); let user_var = variables.next_unmapped_user(); global_from_user(ctx.borrow(), user_var, false); user_var } /// Maps a slice of user lits to solver lits using [`solver_from_user`]. pub fn solver_from_user_lits<'a>( mut ctx: partial!( Context<'a>, mut AnalyzeConflictP, mut AssignmentP, mut BinaryClausesP, mut ImplGraphP, mut ProofP<'a>, mut SolverStateP, mut TmpFlagsP, mut VariablesP, mut VsidsP, mut WatchlistsP, ), solver_lits: &mut Vec<Lit>, user_lits: &[Lit], require_sampling: bool, ) { solver_lits.clear(); solver_lits.extend(user_lits.iter().map(|user_lit| { user_lit.map_var(|user_var| solver_from_user(ctx.borrow(), user_var, require_sampling)) })) } /// Changes the sampling mode of a global variable. /// /// If the mode is changed to hidden, an existing user mapping is automatically removed. /// /// If the mode is changed from hidden, a new user mapping is allocated and the user variable is /// returned. pub fn set_sampling_mode<'a>( mut ctx: partial!(Context<'a>, mut ProofP<'a>, mut SolverStateP, mut VariablesP), global: Var, mode: SamplingMode, ) -> Option<Var> { let variables = ctx.part_mut(VariablesP); let var_data = &mut variables.var_data[global.index()]; assert!(!var_data.deleted); if var_data.assumed { panic!("cannot change sampling mode of assumption variable") } let previous_mode = var_data.sampling_mode; if previous_mode == mode { return None; } var_data.sampling_mode = mode; let mut result = None; if mode != SamplingMode::Hide { proof::add_step( ctx.borrow(), false, &ProofStep::ChangeSamplingMode { var: global, sample: mode == SamplingMode::Sample, }, ); } let variables = ctx.part_mut(VariablesP); if previous_mode == SamplingMode::Hide { let user = variables.next_unmapped_user(); variables.user_from_global_mut().insert(user, global); variables.user_freelist.remove(&user); proof::add_step( ctx.borrow(), false, &ProofStep::UserVarName { global, user: Some(user), }, ); result = Some(user); } else if mode == SamplingMode::Hide { if let Some(user) = variables.user_from_global_mut().remove(global) { variables.user_freelist.insert(user); } proof::add_step( ctx.borrow(), false, &ProofStep::UserVarName { global, user: None }, ); delete_global_if_unused(ctx.borrow(), global); } result } /// Turns all hidden vars into witness vars and returns them. pub fn observe_internal_vars<'a>( mut ctx: partial!(Context<'a>, mut ProofP<'a>, mut SolverStateP, mut VariablesP), ) -> Vec<Var> { let mut result = vec![]; let mut variables = ctx.part_mut(VariablesP); for global_index in 0..variables.global_watermark() { let global = Var::from_index(global_index); let var_data = &variables.var_data[global.index()]; if !var_data.deleted && var_data.sampling_mode == SamplingMode::Hide { let user = set_sampling_mode(ctx.borrow(), global, SamplingMode::Witness).unwrap(); result.push(user); variables = ctx.part_mut(VariablesP); } } result } /// Initialize a newly allocated solver variable pub fn initialize_solver_var( mut ctx: partial!( Context, mut AssignmentP, mut ImplGraphP, mut VsidsP, VariablesP ), solver: Var, global: Var, ) { let (variables, mut ctx) = ctx.split_part(VariablesP); let data = &variables.var_data[global.index()]; // This recovers the state of a variable that has a known value and was already propagated. This // is important so that when new clauses containing this variable are added, load_clause knows // to reenqueue the assignment. ctx.part_mut(AssignmentP).set_var(solver, data.unit); if data.unit.is_some() { ctx.part_mut(ImplGraphP).update_removed_unit(solver); } decision::initialize_var(ctx.borrow(), solver, data.unit.is_none()); // TODO unhiding beyond unit clauses } /// Remove a solver var. /// /// If the variable is isolated and hidden, the global variable is also removed. pub fn remove_solver_var<'a>( mut ctx: partial!(Context<'a>, mut ProofP<'a>, mut SolverStateP, mut VariablesP, mut VsidsP), solver: Var, ) { decision::remove_var(ctx.borrow(), solver); let variables = ctx.part_mut(VariablesP); let global = variables .global_from_solver_mut() .remove(solver) .expect("no existing global var for solver var"); variables.solver_freelist.insert(solver); proof::add_step( ctx.borrow(), false, &ProofStep::SolverVarName { global, solver: None, }, ); delete_global_if_unused(ctx.borrow(), global); } /// Delete a global variable if it is unused fn delete_global_if_unused<'a>( mut ctx: partial!(Context<'a>, mut ProofP<'a>, mut SolverStateP, mut VariablesP), global: Var, ) { let variables = ctx.part_mut(VariablesP); if variables.user_from_global().get(global).is_some() { return; } if variables.solver_from_global().get(global).is_some() { return; } let data = &mut variables.var_data[global.index()]; assert!(data.sampling_mode == SamplingMode::Hide); if !data.isolated { return; } data.deleted = true; proof::add_step(ctx.borrow(), false, &ProofStep::DeleteVar { var: global }); // TODO deletion of unit clauses isn't supported by most DRAT checkers, needs an extra // variable mapping instead. ctx.part_mut(VariablesP).global_freelist.insert(global); } #[cfg(test)] mod tests { use proptest::{collection, prelude::*}; use varisat_formula::{ test::{sat_formula, sgen_unsat_formula}, ExtendFormula, Var, }; use crate::solver::Solver; #[test] #[should_panic(expected = "cannot change sampling mode of assumption variable")] fn cannot_hide_assumed_vars() { let mut solver = Solver::new(); let (x, y, z) = solver.new_lits(); solver.assume(&[x, y, z]); solver.hide_var(x.var()); } #[test] #[should_panic(expected = "cannot change sampling mode of assumption variable")] fn cannot_witness_assumed_vars() { let mut solver = Solver::new(); let (x, y, z) = solver.new_lits(); solver.assume(&[x, y, z]); solver.witness_var(x.var()); } proptest! { #[test] fn sgen_unsat_hidden_with_sat( unsat_formula in sgen_unsat_formula(1..7usize), sat_formula in sat_formula(4..20usize, 10..100usize, 0.05..0.2, 0.9..1.0), ) { use std::cmp::max; let mut solver = Solver::new(); solver.enable_self_checking(); let cond = Var::from_index(max(unsat_formula.var_count(), sat_formula.var_count())); let mut tmp = vec![]; for clause in unsat_formula.iter() { tmp.clear(); tmp.extend_from_slice(&clause); tmp.push(cond.negative()); solver.add_clause(&tmp); } for i in 0..unsat_formula.var_count() { solver.hide_var(Var::from_index(i)); } solver.add_formula(&sat_formula); prop_assert_eq!(solver.solve().ok(), Some(true)); solver.add_clause(&[cond.positive()]); prop_assert_eq!(solver.solve().ok(), Some(false)); } #[test] fn sgen_sat_many_hidden_observe_internal( sat_formulas in collection::vec( sat_formula(4..20usize, 10..100usize, 0.05..0.2, 0.9..1.0), 1..10, ) ) { let mut solver = Solver::new(); solver.enable_self_checking(); for formula in sat_formulas { solver.add_formula(&formula); let new_vars = solver.observe_internal_vars(); for i in 0..formula.var_count() { solver.hide_var(Var::from_index(i)); } for var in new_vars { solver.hide_var(var); } } prop_assert_eq!(solver.solve().ok(), Some(true)); } } }
use crate::protocol::parts::type_id::TypeId; use std::sync::Arc; use vec_map::VecMap; // The structure is a bit weird; reason is that we want to retain the transfer format // which seeks to avoid String duplication /// Metadata of a field in a `ResultSet`. #[derive(Clone, Debug)] pub struct FieldMetadata { inner: InnerFieldMetadata, names: Arc<VecMap<String>>, } /// Describes a single field (column) in a result set. #[derive(Clone, Copy, Debug)] pub(crate) struct InnerFieldMetadata { schemaname_idx: u32, tablename_idx: u32, columnname_idx: u32, displayname_idx: u32, // Column_options. // Bit pattern: // 0 = Mandatory // 1 = Optional // 2 = Default // 3 = Escape_char // 4 = Readonly // 5 = Autoincrement // 6 = ArrayType column_options: u8, type_id: TypeId, // scale scale: i16, // Precision precision: i16, } impl InnerFieldMetadata { #[allow(clippy::too_many_arguments)] pub fn new( schemaname_idx: u32, tablename_idx: u32, columnname_idx: u32, displayname_idx: u32, column_options: u8, type_id: TypeId, scale: i16, precision: i16, ) -> Self { Self { schemaname_idx, tablename_idx, columnname_idx, displayname_idx, column_options, type_id, scale, precision, } } } impl FieldMetadata { pub(crate) fn new(inner: InnerFieldMetadata, names: Arc<VecMap<String>>) -> Self { Self { inner, names } } /// Database schema of the field. pub fn schemaname(&self) -> &str { self.names .get(self.inner.schemaname_idx as usize) .map_or("", String::as_str) } /// Database table. pub fn tablename(&self) -> &str { self.names .get(self.inner.tablename_idx as usize) .map_or("", String::as_str) } /// Column name. pub fn columnname(&self) -> &str { self.names .get(self.inner.columnname_idx as usize) .map_or("", String::as_str) } /// Display name of the column. pub fn displayname(&self) -> &str { self.names .get(self.inner.displayname_idx as usize) .map_or("", String::as_str) } /// Returns the id of the value type. pub fn type_id(&self) -> TypeId { self.inner.type_id } // Returns true for BLOB, CLOB, and NCLOB, and false otherwise. pub(crate) fn is_lob(&self) -> bool { matches!( self.inner.type_id, TypeId::BLOB | TypeId::CLOB | TypeId::NCLOB ) } /// True if column can contain NULL values. pub fn is_nullable(&self) -> bool { (self.inner.column_options & 0b_0000_0010_u8) != 0 } /// The length or the precision of the value. /// /// Is `-1` for LOB types. pub fn precision(&self) -> i16 { self.inner.precision } /// The scale of the value. /// /// Is `0` for all types where a scale does not make sense. pub fn scale(&self) -> i16 { self.inner.scale } /// Returns true if the column has a default value. pub fn has_default(&self) -> bool { (self.inner.column_options & 0b_0000_0100_u8) != 0 } /// Returns true if the column is read-only. pub fn is_read_only(&self) -> bool { (self.inner.column_options & 0b_0100_0000_u8) != 0 } /// Returns true if the column is auto-incremented. pub fn is_auto_incremented(&self) -> bool { (self.inner.column_options & 0b_0010_0000_u8) != 0 } /// Returns true if the column is of array type. pub fn is_array_type(&self) -> bool { (self.inner.column_options & 0b_0100_0000_u8) != 0 } }
use openexr_sys as sys; use crate::core::error::Error; type Result<T, E = Error> = std::result::Result<T, E>; /// A KeyCode object uniquely identifies a motion picture film frame. /// The following fields specifiy film manufacturer, film type, film /// roll and the frame's position within the roll. /// /// # Fields /// /// * `film_mfc_code` - Film manufacturer code. /// Range: `[0, 99]` /// * `filmType` - Film type code. /// Range: `[0, 99]` /// * `prefix` - Prefix to identify film roll. /// Range: `[0, 999999]` /// * `count` - Count, increments once every perfs_per_count perforations. /// Range: `[0, 9999]` /// * `perf_offset` - Offset of frame, in perforations from zero-frame reference mark /// Range: `[0, 119]` /// * `perfs_per_frame` - Number of perforations per frame. Typical values are 1 for 16mm film; 3, 4 or 8 for 35mm film; 5, 8 or 15 for 65mm film. /// Range: `[1, 15]` /// * `perfs_per_count` - Number of perforations per count. Typical values are 20 for 16mm film, 64 for 35mm film, 80 or 120 for 65mm film. /// Range: `[20, 120]` /// /// # Further Reading /// For more information about the interpretation of those fields see /// the following standards and recommended practice publications: /// * SMPTE 254 Motion-Picture Film (35-mm) - Manufacturer-Printed /// Latent Image Identification Information /// * SMPTE 268M File Format for Digital Moving-Picture Exchange (DPX) /// (section 6.1) /// * SMPTE 270 Motion-Picture Film (65-mm) - Manufacturer- Printed /// Latent Image Identification Information /// * SMPTE 271 Motion-Picture Film (16-mm) - Manufacturer- Printed /// Latent Image Identification Information /// #[repr(transparent)] pub struct KeyCode(sys::Imf_KeyCode_t); impl KeyCode { /// Get the film manufacturer code. Valid range `[0, 99]` /// pub fn film_mfc_code(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmMfcCode(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmMfcCode"); } v } /// Set the film manufacturer code. Valid range `[0, 99]` /// /// # Errors /// * [`Error::InvalidArgument`] - If `code` is not in the range `[0, 99]` /// /// TODO: Do we want to implement a bounded integer here to specify the range? pub fn set_film_mfc_code(&mut self, code: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setFilmMfcCode(&mut self.0, code).into_result()?; } Ok(()) } /// Get the film type code. Valid range `[0, 99]` /// pub fn film_type(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the film type code. Valid range `[0, 99]` /// /// # Errors /// * [`Error::InvalidArgument`] - If `code` is not in the range `[0, 99]` /// pub fn set_film_type(&mut self, code: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setFilmType(&mut self.0, code).into_result()?; } Ok(()) } /// Get the prefix code which identifies the film roll. /// Valid range `[0, 999999]` /// pub fn prefix(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the prefix code which identifies the film roll. /// Valid range `[0, 999999]` /// /// # Errors /// * [`Error::InvalidArgument`] - If `code` is not in the range `[0, 999999]` /// pub fn set_prefix(&mut self, v: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setPrefix(&mut self.0, v).into_result()?; } Ok(()) } /// Get the count, which increments every `perfs_per_count` perforations. /// Valid range [0, 9999] /// pub fn count(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the count, which increments every `perfs_per_count` perforations. /// Valid range [0, 9999] /// /// # Errors /// * [`Error::InvalidArgument`] - If `count` is not in the range `[0, 9999]` /// pub fn set_count(&mut self, count: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setCount(&mut self.0, count).into_result()?; } Ok(()) } /// Get the offset of the frame in perforations from the zero-frame reference mark. /// Valid range [0, 119] /// pub fn perf_offset(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the offset of the frame in perforations from the zero-frame reference mark. /// Valid range [0, 119] /// /// # Errors /// * [`Error::InvalidArgument`] - If `offset` is not in the range `[0, 119]` /// pub fn set_perf_offset(&mut self, offset: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setPerfOffset(&mut self.0, offset) .into_result()?; } Ok(()) } /// Get the number of perforations per frame. /// Valid range [1, 15] /// /// Typical values: /// * 1 for 16mm film /// * 3, 4 or 8 for 35mm film /// * 5, 8, or 15 for 65mm film /// pub fn perfs_per_frame(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the number of perforations per frame. /// Valid range [1, 15] /// /// Typical values: /// * 1 for 16mm film /// * 3, 4 or 8 for 35mm film /// * 5, 8, or 15 for 65mm film /// /// # Errors /// * [`Error::InvalidArgument`] - If `perfs` is not in the range `[1, 15]` /// pub fn set_perfs_per_frame(&mut self, perfs: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setPerfsPerFrame(&mut self.0, perfs) .into_result()?; } Ok(()) } /// Get the number of perforations per count. /// Valid range [2, 120] /// /// Typical values: /// * 20 for 16mm film /// * 64 for 35mm film /// * 80 or 120 for 65mm film /// pub fn perfs_per_count(&self) -> i32 { let mut v = 0i32; unsafe { sys::Imf_KeyCode_filmType(&self.0, &mut v) .into_result() .expect("Unexpected exception from Imf_KeyCode_filmType"); } v } /// Set the number of perforations per count. /// Valid range [2, 120] /// /// Typical values: /// * 20 for 16mm film /// * 64 for 35mm film /// * 80 or 120 for 65mm film /// /// # Errors /// * [`Error::InvalidArgument`] - If `perfs` is not in the range `[2, 120]` /// pub fn set_perfs_per_count(&mut self, perfs: i32) -> Result<()> { unsafe { sys::Imf_KeyCode_setPerfsPerCount(&mut self.0, perfs) .into_result()?; } Ok(()) } } impl Default for KeyCode { fn default() -> Self { let mut inner = sys::Imf_KeyCode_t::default(); unsafe { sys::Imf_KeyCode_ctor(&mut inner, 0, 0, 0, 0, 0, 4, 64) .into_result() .expect("Unexpected exception from Imf_KeyCode_ctor"); } KeyCode(inner) } } #[cfg(test)] #[test] fn test_keycode() { let mut k = KeyCode::default(); assert!(k.set_film_mfc_code(-1).is_err()); assert!(k.set_film_mfc_code(1).is_ok()); assert_eq!(k.film_mfc_code(), 1); }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEAdvertisement(pub ::windows::core::IInspectable); impl BluetoothLEAdvertisement { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisement, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn Flags(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<BluetoothLEAdvertisementFlags>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<BluetoothLEAdvertisementFlags>>(result__) } } #[cfg(feature = "Foundation")] pub fn SetFlags<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::IReference<BluetoothLEAdvertisementFlags>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn LocalName(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetLocalName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn ServiceUuids(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<::windows::core::GUID>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<::windows::core::GUID>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn ManufacturerData(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<BluetoothLEManufacturerData>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<BluetoothLEManufacturerData>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn DataSections(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<BluetoothLEAdvertisementDataSection>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<BluetoothLEAdvertisementDataSection>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn GetManufacturerDataByCompanyId(&self, companyid: u16) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<BluetoothLEManufacturerData>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), companyid, &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<BluetoothLEManufacturerData>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn GetSectionsByType(&self, r#type: u8) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<BluetoothLEAdvertisementDataSection>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), r#type, &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<BluetoothLEAdvertisementDataSection>>(result__) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisement { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisement;{066fb2b7-33d1-4e7d-8367-cf81d0f79653})"); } unsafe impl ::windows::core::Interface for BluetoothLEAdvertisement { type Vtable = IBluetoothLEAdvertisement_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x066fb2b7_33d1_4e7d_8367_cf81d0f79653); } impl ::windows::core::RuntimeName for BluetoothLEAdvertisement { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisement"; } impl ::core::convert::From<BluetoothLEAdvertisement> for ::windows::core::IUnknown { fn from(value: BluetoothLEAdvertisement) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEAdvertisement> for ::windows::core::IUnknown { fn from(value: &BluetoothLEAdvertisement) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEAdvertisement { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEAdvertisement { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEAdvertisement> for ::windows::core::IInspectable { fn from(value: BluetoothLEAdvertisement) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEAdvertisement> for ::windows::core::IInspectable { fn from(value: &BluetoothLEAdvertisement) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEAdvertisement { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEAdvertisement { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEAdvertisement {} unsafe impl ::core::marker::Sync for BluetoothLEAdvertisement {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEAdvertisementBytePattern(pub ::windows::core::IInspectable); impl BluetoothLEAdvertisementBytePattern { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementBytePattern, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn DataType(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn SetDataType(&self, value: u8) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn Offset(&self) -> ::windows::core::Result<i16> { let this = self; unsafe { let mut result__: i16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i16>(result__) } } pub fn SetOffset(&self, value: i16) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Storage_Streams")] pub fn Data(&self) -> ::windows::core::Result<super::super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Storage::Streams::IBuffer>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn SetData<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IBuffer>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Storage_Streams")] pub fn Create<'a, Param2: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IBuffer>>(datatype: u8, offset: i16, data: Param2) -> ::windows::core::Result<BluetoothLEAdvertisementBytePattern> { Self::IBluetoothLEAdvertisementBytePatternFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), datatype, offset, data.into_param().abi(), &mut result__).from_abi::<BluetoothLEAdvertisementBytePattern>(result__) }) } pub fn IBluetoothLEAdvertisementBytePatternFactory<R, F: FnOnce(&IBluetoothLEAdvertisementBytePatternFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementBytePattern, IBluetoothLEAdvertisementBytePatternFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementBytePattern { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementBytePattern;{fbfad7f2-b9c5-4a08-bc51-502f8ef68a79})"); } unsafe impl ::windows::core::Interface for BluetoothLEAdvertisementBytePattern { type Vtable = IBluetoothLEAdvertisementBytePattern_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfbfad7f2_b9c5_4a08_bc51_502f8ef68a79); } impl ::windows::core::RuntimeName for BluetoothLEAdvertisementBytePattern { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementBytePattern"; } impl ::core::convert::From<BluetoothLEAdvertisementBytePattern> for ::windows::core::IUnknown { fn from(value: BluetoothLEAdvertisementBytePattern) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEAdvertisementBytePattern> for ::windows::core::IUnknown { fn from(value: &BluetoothLEAdvertisementBytePattern) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEAdvertisementBytePattern { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEAdvertisementBytePattern { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEAdvertisementBytePattern> for ::windows::core::IInspectable { fn from(value: BluetoothLEAdvertisementBytePattern) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEAdvertisementBytePattern> for ::windows::core::IInspectable { fn from(value: &BluetoothLEAdvertisementBytePattern) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEAdvertisementBytePattern { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEAdvertisementBytePattern { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEAdvertisementBytePattern {} unsafe impl ::core::marker::Sync for BluetoothLEAdvertisementBytePattern {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEAdvertisementDataSection(pub ::windows::core::IInspectable); impl BluetoothLEAdvertisementDataSection { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementDataSection, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn DataType(&self) -> ::windows::core::Result<u8> { let this = self; unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) } } pub fn SetDataType(&self, value: u8) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Storage_Streams")] pub fn Data(&self) -> ::windows::core::Result<super::super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Storage::Streams::IBuffer>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn SetData<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IBuffer>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Storage_Streams")] pub fn Create<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IBuffer>>(datatype: u8, data: Param1) -> ::windows::core::Result<BluetoothLEAdvertisementDataSection> { Self::IBluetoothLEAdvertisementDataSectionFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), datatype, data.into_param().abi(), &mut result__).from_abi::<BluetoothLEAdvertisementDataSection>(result__) }) } pub fn IBluetoothLEAdvertisementDataSectionFactory<R, F: FnOnce(&IBluetoothLEAdvertisementDataSectionFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementDataSection, IBluetoothLEAdvertisementDataSectionFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementDataSection { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementDataSection;{d7213314-3a43-40f9-b6f0-92bfefc34ae3})"); } unsafe impl ::windows::core::Interface for BluetoothLEAdvertisementDataSection { type Vtable = IBluetoothLEAdvertisementDataSection_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd7213314_3a43_40f9_b6f0_92bfefc34ae3); } impl ::windows::core::RuntimeName for BluetoothLEAdvertisementDataSection { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementDataSection"; } impl ::core::convert::From<BluetoothLEAdvertisementDataSection> for ::windows::core::IUnknown { fn from(value: BluetoothLEAdvertisementDataSection) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEAdvertisementDataSection> for ::windows::core::IUnknown { fn from(value: &BluetoothLEAdvertisementDataSection) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEAdvertisementDataSection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEAdvertisementDataSection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEAdvertisementDataSection> for ::windows::core::IInspectable { fn from(value: BluetoothLEAdvertisementDataSection) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEAdvertisementDataSection> for ::windows::core::IInspectable { fn from(value: &BluetoothLEAdvertisementDataSection) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEAdvertisementDataSection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEAdvertisementDataSection { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEAdvertisementDataSection {} unsafe impl ::core::marker::Sync for BluetoothLEAdvertisementDataSection {} pub struct BluetoothLEAdvertisementDataTypes {} impl BluetoothLEAdvertisementDataTypes { pub fn Flags() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn IncompleteService16BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn CompleteService16BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn IncompleteService32BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn CompleteService32BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn IncompleteService128BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn CompleteService128BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn ShortenedLocalName() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn CompleteLocalName() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn TxPowerLevel() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn SlaveConnectionIntervalRange() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn ServiceSolicitation16BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn ServiceSolicitation32BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn ServiceSolicitation128BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn ServiceData16BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn ServiceData32BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn ServiceData128BitUuids() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn PublicTargetAddress() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn RandomTargetAddress() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn Appearance() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn AdvertisingInterval() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn ManufacturerSpecificData() -> ::windows::core::Result<u8> { Self::IBluetoothLEAdvertisementDataTypesStatics(|this| unsafe { let mut result__: u8 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u8>(result__) }) } pub fn IBluetoothLEAdvertisementDataTypesStatics<R, F: FnOnce(&IBluetoothLEAdvertisementDataTypesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementDataTypes, IBluetoothLEAdvertisementDataTypesStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for BluetoothLEAdvertisementDataTypes { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementDataTypes"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEAdvertisementFilter(pub ::windows::core::IInspectable); impl BluetoothLEAdvertisementFilter { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementFilter, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn Advertisement(&self) -> ::windows::core::Result<BluetoothLEAdvertisement> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BluetoothLEAdvertisement>(result__) } } pub fn SetAdvertisement<'a, Param0: ::windows::core::IntoParam<'a, BluetoothLEAdvertisement>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Foundation_Collections")] pub fn BytePatterns(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVector<BluetoothLEAdvertisementBytePattern>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVector<BluetoothLEAdvertisementBytePattern>>(result__) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementFilter { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementFilter;{131eb0d3-d04e-47b1-837e-49405bf6f80f})"); } unsafe impl ::windows::core::Interface for BluetoothLEAdvertisementFilter { type Vtable = IBluetoothLEAdvertisementFilter_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x131eb0d3_d04e_47b1_837e_49405bf6f80f); } impl ::windows::core::RuntimeName for BluetoothLEAdvertisementFilter { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementFilter"; } impl ::core::convert::From<BluetoothLEAdvertisementFilter> for ::windows::core::IUnknown { fn from(value: BluetoothLEAdvertisementFilter) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEAdvertisementFilter> for ::windows::core::IUnknown { fn from(value: &BluetoothLEAdvertisementFilter) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEAdvertisementFilter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEAdvertisementFilter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEAdvertisementFilter> for ::windows::core::IInspectable { fn from(value: BluetoothLEAdvertisementFilter) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEAdvertisementFilter> for ::windows::core::IInspectable { fn from(value: &BluetoothLEAdvertisementFilter) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEAdvertisementFilter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEAdvertisementFilter { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEAdvertisementFilter {} unsafe impl ::core::marker::Sync for BluetoothLEAdvertisementFilter {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct BluetoothLEAdvertisementFlags(pub u32); impl BluetoothLEAdvertisementFlags { pub const None: BluetoothLEAdvertisementFlags = BluetoothLEAdvertisementFlags(0u32); pub const LimitedDiscoverableMode: BluetoothLEAdvertisementFlags = BluetoothLEAdvertisementFlags(1u32); pub const GeneralDiscoverableMode: BluetoothLEAdvertisementFlags = BluetoothLEAdvertisementFlags(2u32); pub const ClassicNotSupported: BluetoothLEAdvertisementFlags = BluetoothLEAdvertisementFlags(4u32); pub const DualModeControllerCapable: BluetoothLEAdvertisementFlags = BluetoothLEAdvertisementFlags(8u32); pub const DualModeHostCapable: BluetoothLEAdvertisementFlags = BluetoothLEAdvertisementFlags(16u32); } impl ::core::convert::From<u32> for BluetoothLEAdvertisementFlags { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for BluetoothLEAdvertisementFlags { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementFlags { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementFlags;u4)"); } impl ::windows::core::DefaultType for BluetoothLEAdvertisementFlags { type DefaultType = Self; } impl ::core::ops::BitOr for BluetoothLEAdvertisementFlags { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for BluetoothLEAdvertisementFlags { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for BluetoothLEAdvertisementFlags { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for BluetoothLEAdvertisementFlags { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for BluetoothLEAdvertisementFlags { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEAdvertisementPublisher(pub ::windows::core::IInspectable); impl BluetoothLEAdvertisementPublisher { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementPublisher, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn Status(&self) -> ::windows::core::Result<BluetoothLEAdvertisementPublisherStatus> { let this = self; unsafe { let mut result__: BluetoothLEAdvertisementPublisherStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BluetoothLEAdvertisementPublisherStatus>(result__) } } pub fn Advertisement(&self) -> ::windows::core::Result<BluetoothLEAdvertisement> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BluetoothLEAdvertisement>(result__) } } pub fn Start(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() } } pub fn Stop(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "Foundation")] pub fn StatusChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<BluetoothLEAdvertisementPublisher, BluetoothLEAdvertisementPublisherStatusChangedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveStatusChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, BluetoothLEAdvertisement>>(advertisement: Param0) -> ::windows::core::Result<BluetoothLEAdvertisementPublisher> { Self::IBluetoothLEAdvertisementPublisherFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), advertisement.into_param().abi(), &mut result__).from_abi::<BluetoothLEAdvertisementPublisher>(result__) }) } #[cfg(feature = "Foundation")] pub fn PreferredTransmitPowerLevelInDBm(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<i16>> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementPublisher2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<i16>>(result__) } } #[cfg(feature = "Foundation")] pub fn SetPreferredTransmitPowerLevelInDBm<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::IReference<i16>>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementPublisher2>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn UseExtendedAdvertisement(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementPublisher2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetUseExtendedAdvertisement(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementPublisher2>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() } } pub fn IsAnonymous(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementPublisher2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIsAnonymous(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementPublisher2>(self)?; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } pub fn IncludeTransmitPowerLevel(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementPublisher2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetIncludeTransmitPowerLevel(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementPublisher2>(self)?; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() } } pub fn IBluetoothLEAdvertisementPublisherFactory<R, F: FnOnce(&IBluetoothLEAdvertisementPublisherFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementPublisher, IBluetoothLEAdvertisementPublisherFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementPublisher { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementPublisher;{cde820f9-d9fa-43d6-a264-ddd8b7da8b78})"); } unsafe impl ::windows::core::Interface for BluetoothLEAdvertisementPublisher { type Vtable = IBluetoothLEAdvertisementPublisher_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcde820f9_d9fa_43d6_a264_ddd8b7da8b78); } impl ::windows::core::RuntimeName for BluetoothLEAdvertisementPublisher { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementPublisher"; } impl ::core::convert::From<BluetoothLEAdvertisementPublisher> for ::windows::core::IUnknown { fn from(value: BluetoothLEAdvertisementPublisher) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEAdvertisementPublisher> for ::windows::core::IUnknown { fn from(value: &BluetoothLEAdvertisementPublisher) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEAdvertisementPublisher { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEAdvertisementPublisher { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEAdvertisementPublisher> for ::windows::core::IInspectable { fn from(value: BluetoothLEAdvertisementPublisher) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEAdvertisementPublisher> for ::windows::core::IInspectable { fn from(value: &BluetoothLEAdvertisementPublisher) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEAdvertisementPublisher { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEAdvertisementPublisher { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEAdvertisementPublisher {} unsafe impl ::core::marker::Sync for BluetoothLEAdvertisementPublisher {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct BluetoothLEAdvertisementPublisherStatus(pub i32); impl BluetoothLEAdvertisementPublisherStatus { pub const Created: BluetoothLEAdvertisementPublisherStatus = BluetoothLEAdvertisementPublisherStatus(0i32); pub const Waiting: BluetoothLEAdvertisementPublisherStatus = BluetoothLEAdvertisementPublisherStatus(1i32); pub const Started: BluetoothLEAdvertisementPublisherStatus = BluetoothLEAdvertisementPublisherStatus(2i32); pub const Stopping: BluetoothLEAdvertisementPublisherStatus = BluetoothLEAdvertisementPublisherStatus(3i32); pub const Stopped: BluetoothLEAdvertisementPublisherStatus = BluetoothLEAdvertisementPublisherStatus(4i32); pub const Aborted: BluetoothLEAdvertisementPublisherStatus = BluetoothLEAdvertisementPublisherStatus(5i32); } impl ::core::convert::From<i32> for BluetoothLEAdvertisementPublisherStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for BluetoothLEAdvertisementPublisherStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementPublisherStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementPublisherStatus;i4)"); } impl ::windows::core::DefaultType for BluetoothLEAdvertisementPublisherStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEAdvertisementPublisherStatusChangedEventArgs(pub ::windows::core::IInspectable); impl BluetoothLEAdvertisementPublisherStatusChangedEventArgs { pub fn Status(&self) -> ::windows::core::Result<BluetoothLEAdvertisementPublisherStatus> { let this = self; unsafe { let mut result__: BluetoothLEAdvertisementPublisherStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BluetoothLEAdvertisementPublisherStatus>(result__) } } pub fn Error(&self) -> ::windows::core::Result<super::BluetoothError> { let this = self; unsafe { let mut result__: super::BluetoothError = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::BluetoothError>(result__) } } #[cfg(feature = "Foundation")] pub fn SelectedTransmitPowerLevelInDBm(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<i16>> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementPublisherStatusChangedEventArgs2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<i16>>(result__) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementPublisherStatusChangedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementPublisherStatusChangedEventArgs;{09c2bd9f-2dff-4b23-86ee-0d14fb94aeae})"); } unsafe impl ::windows::core::Interface for BluetoothLEAdvertisementPublisherStatusChangedEventArgs { type Vtable = IBluetoothLEAdvertisementPublisherStatusChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x09c2bd9f_2dff_4b23_86ee_0d14fb94aeae); } impl ::windows::core::RuntimeName for BluetoothLEAdvertisementPublisherStatusChangedEventArgs { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementPublisherStatusChangedEventArgs"; } impl ::core::convert::From<BluetoothLEAdvertisementPublisherStatusChangedEventArgs> for ::windows::core::IUnknown { fn from(value: BluetoothLEAdvertisementPublisherStatusChangedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEAdvertisementPublisherStatusChangedEventArgs> for ::windows::core::IUnknown { fn from(value: &BluetoothLEAdvertisementPublisherStatusChangedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEAdvertisementPublisherStatusChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEAdvertisementPublisherStatusChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEAdvertisementPublisherStatusChangedEventArgs> for ::windows::core::IInspectable { fn from(value: BluetoothLEAdvertisementPublisherStatusChangedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEAdvertisementPublisherStatusChangedEventArgs> for ::windows::core::IInspectable { fn from(value: &BluetoothLEAdvertisementPublisherStatusChangedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEAdvertisementPublisherStatusChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEAdvertisementPublisherStatusChangedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEAdvertisementPublisherStatusChangedEventArgs {} unsafe impl ::core::marker::Sync for BluetoothLEAdvertisementPublisherStatusChangedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEAdvertisementReceivedEventArgs(pub ::windows::core::IInspectable); impl BluetoothLEAdvertisementReceivedEventArgs { pub fn RawSignalStrengthInDBm(&self) -> ::windows::core::Result<i16> { let this = self; unsafe { let mut result__: i16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i16>(result__) } } pub fn BluetoothAddress(&self) -> ::windows::core::Result<u64> { let this = self; unsafe { let mut result__: u64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u64>(result__) } } pub fn AdvertisementType(&self) -> ::windows::core::Result<BluetoothLEAdvertisementType> { let this = self; unsafe { let mut result__: BluetoothLEAdvertisementType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BluetoothLEAdvertisementType>(result__) } } #[cfg(feature = "Foundation")] pub fn Timestamp(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__) } } pub fn Advertisement(&self) -> ::windows::core::Result<BluetoothLEAdvertisement> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BluetoothLEAdvertisement>(result__) } } pub fn BluetoothAddressType(&self) -> ::windows::core::Result<super::BluetoothAddressType> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementReceivedEventArgs2>(self)?; unsafe { let mut result__: super::BluetoothAddressType = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::BluetoothAddressType>(result__) } } #[cfg(feature = "Foundation")] pub fn TransmitPowerLevelInDBm(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<i16>> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementReceivedEventArgs2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<i16>>(result__) } } pub fn IsAnonymous(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementReceivedEventArgs2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsConnectable(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementReceivedEventArgs2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsScannable(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementReceivedEventArgs2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsDirected(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementReceivedEventArgs2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn IsScanResponse(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementReceivedEventArgs2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementReceivedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementReceivedEventArgs;{27987ddf-e596-41be-8d43-9e6731d4a913})"); } unsafe impl ::windows::core::Interface for BluetoothLEAdvertisementReceivedEventArgs { type Vtable = IBluetoothLEAdvertisementReceivedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x27987ddf_e596_41be_8d43_9e6731d4a913); } impl ::windows::core::RuntimeName for BluetoothLEAdvertisementReceivedEventArgs { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementReceivedEventArgs"; } impl ::core::convert::From<BluetoothLEAdvertisementReceivedEventArgs> for ::windows::core::IUnknown { fn from(value: BluetoothLEAdvertisementReceivedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEAdvertisementReceivedEventArgs> for ::windows::core::IUnknown { fn from(value: &BluetoothLEAdvertisementReceivedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEAdvertisementReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEAdvertisementReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEAdvertisementReceivedEventArgs> for ::windows::core::IInspectable { fn from(value: BluetoothLEAdvertisementReceivedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEAdvertisementReceivedEventArgs> for ::windows::core::IInspectable { fn from(value: &BluetoothLEAdvertisementReceivedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEAdvertisementReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEAdvertisementReceivedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEAdvertisementReceivedEventArgs {} unsafe impl ::core::marker::Sync for BluetoothLEAdvertisementReceivedEventArgs {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct BluetoothLEAdvertisementType(pub i32); impl BluetoothLEAdvertisementType { pub const ConnectableUndirected: BluetoothLEAdvertisementType = BluetoothLEAdvertisementType(0i32); pub const ConnectableDirected: BluetoothLEAdvertisementType = BluetoothLEAdvertisementType(1i32); pub const ScannableUndirected: BluetoothLEAdvertisementType = BluetoothLEAdvertisementType(2i32); pub const NonConnectableUndirected: BluetoothLEAdvertisementType = BluetoothLEAdvertisementType(3i32); pub const ScanResponse: BluetoothLEAdvertisementType = BluetoothLEAdvertisementType(4i32); pub const Extended: BluetoothLEAdvertisementType = BluetoothLEAdvertisementType(5i32); } impl ::core::convert::From<i32> for BluetoothLEAdvertisementType { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for BluetoothLEAdvertisementType { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementType { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementType;i4)"); } impl ::windows::core::DefaultType for BluetoothLEAdvertisementType { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEAdvertisementWatcher(pub ::windows::core::IInspectable); impl BluetoothLEAdvertisementWatcher { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementWatcher, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "Foundation")] pub fn MinSamplingInterval(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn MaxSamplingInterval(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn MinOutOfRangeTimeout(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__) } } #[cfg(feature = "Foundation")] pub fn MaxOutOfRangeTimeout(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__) } } pub fn Status(&self) -> ::windows::core::Result<BluetoothLEAdvertisementWatcherStatus> { let this = self; unsafe { let mut result__: BluetoothLEAdvertisementWatcherStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BluetoothLEAdvertisementWatcherStatus>(result__) } } pub fn ScanningMode(&self) -> ::windows::core::Result<BluetoothLEScanningMode> { let this = self; unsafe { let mut result__: BluetoothLEScanningMode = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BluetoothLEScanningMode>(result__) } } pub fn SetScanningMode(&self, value: BluetoothLEScanningMode) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() } } pub fn SignalStrengthFilter(&self) -> ::windows::core::Result<super::BluetoothSignalStrengthFilter> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::BluetoothSignalStrengthFilter>(result__) } } pub fn SetSignalStrengthFilter<'a, Param0: ::windows::core::IntoParam<'a, super::BluetoothSignalStrengthFilter>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn AdvertisementFilter(&self) -> ::windows::core::Result<BluetoothLEAdvertisementFilter> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BluetoothLEAdvertisementFilter>(result__) } } pub fn SetAdvertisementFilter<'a, Param0: ::windows::core::IntoParam<'a, BluetoothLEAdvertisementFilter>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn Start(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this)).ok() } } pub fn Stop(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this)).ok() } } #[cfg(feature = "Foundation")] pub fn Received<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<BluetoothLEAdvertisementWatcher, BluetoothLEAdvertisementReceivedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveReceived<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn Stopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<BluetoothLEAdvertisementWatcher, BluetoothLEAdvertisementWatcherStoppedEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> { let this = self; unsafe { let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveStopped<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, BluetoothLEAdvertisementFilter>>(advertisementfilter: Param0) -> ::windows::core::Result<BluetoothLEAdvertisementWatcher> { Self::IBluetoothLEAdvertisementWatcherFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), advertisementfilter.into_param().abi(), &mut result__).from_abi::<BluetoothLEAdvertisementWatcher>(result__) }) } pub fn AllowExtendedAdvertisements(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementWatcher2>(self)?; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetAllowExtendedAdvertisements(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBluetoothLEAdvertisementWatcher2>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn IBluetoothLEAdvertisementWatcherFactory<R, F: FnOnce(&IBluetoothLEAdvertisementWatcherFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEAdvertisementWatcher, IBluetoothLEAdvertisementWatcherFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementWatcher { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher;{a6ac336f-f3d3-4297-8d6c-c81ea6623f40})"); } unsafe impl ::windows::core::Interface for BluetoothLEAdvertisementWatcher { type Vtable = IBluetoothLEAdvertisementWatcher_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa6ac336f_f3d3_4297_8d6c_c81ea6623f40); } impl ::windows::core::RuntimeName for BluetoothLEAdvertisementWatcher { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcher"; } impl ::core::convert::From<BluetoothLEAdvertisementWatcher> for ::windows::core::IUnknown { fn from(value: BluetoothLEAdvertisementWatcher) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEAdvertisementWatcher> for ::windows::core::IUnknown { fn from(value: &BluetoothLEAdvertisementWatcher) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEAdvertisementWatcher { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEAdvertisementWatcher { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEAdvertisementWatcher> for ::windows::core::IInspectable { fn from(value: BluetoothLEAdvertisementWatcher) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEAdvertisementWatcher> for ::windows::core::IInspectable { fn from(value: &BluetoothLEAdvertisementWatcher) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEAdvertisementWatcher { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEAdvertisementWatcher { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEAdvertisementWatcher {} unsafe impl ::core::marker::Sync for BluetoothLEAdvertisementWatcher {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct BluetoothLEAdvertisementWatcherStatus(pub i32); impl BluetoothLEAdvertisementWatcherStatus { pub const Created: BluetoothLEAdvertisementWatcherStatus = BluetoothLEAdvertisementWatcherStatus(0i32); pub const Started: BluetoothLEAdvertisementWatcherStatus = BluetoothLEAdvertisementWatcherStatus(1i32); pub const Stopping: BluetoothLEAdvertisementWatcherStatus = BluetoothLEAdvertisementWatcherStatus(2i32); pub const Stopped: BluetoothLEAdvertisementWatcherStatus = BluetoothLEAdvertisementWatcherStatus(3i32); pub const Aborted: BluetoothLEAdvertisementWatcherStatus = BluetoothLEAdvertisementWatcherStatus(4i32); } impl ::core::convert::From<i32> for BluetoothLEAdvertisementWatcherStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for BluetoothLEAdvertisementWatcherStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementWatcherStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcherStatus;i4)"); } impl ::windows::core::DefaultType for BluetoothLEAdvertisementWatcherStatus { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEAdvertisementWatcherStoppedEventArgs(pub ::windows::core::IInspectable); impl BluetoothLEAdvertisementWatcherStoppedEventArgs { pub fn Error(&self) -> ::windows::core::Result<super::BluetoothError> { let this = self; unsafe { let mut result__: super::BluetoothError = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::BluetoothError>(result__) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEAdvertisementWatcherStoppedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcherStoppedEventArgs;{dd40f84d-e7b9-43e3-9c04-0685d085fd8c})"); } unsafe impl ::windows::core::Interface for BluetoothLEAdvertisementWatcherStoppedEventArgs { type Vtable = IBluetoothLEAdvertisementWatcherStoppedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdd40f84d_e7b9_43e3_9c04_0685d085fd8c); } impl ::windows::core::RuntimeName for BluetoothLEAdvertisementWatcherStoppedEventArgs { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEAdvertisementWatcherStoppedEventArgs"; } impl ::core::convert::From<BluetoothLEAdvertisementWatcherStoppedEventArgs> for ::windows::core::IUnknown { fn from(value: BluetoothLEAdvertisementWatcherStoppedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEAdvertisementWatcherStoppedEventArgs> for ::windows::core::IUnknown { fn from(value: &BluetoothLEAdvertisementWatcherStoppedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEAdvertisementWatcherStoppedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEAdvertisementWatcherStoppedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEAdvertisementWatcherStoppedEventArgs> for ::windows::core::IInspectable { fn from(value: BluetoothLEAdvertisementWatcherStoppedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEAdvertisementWatcherStoppedEventArgs> for ::windows::core::IInspectable { fn from(value: &BluetoothLEAdvertisementWatcherStoppedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEAdvertisementWatcherStoppedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEAdvertisementWatcherStoppedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEAdvertisementWatcherStoppedEventArgs {} unsafe impl ::core::marker::Sync for BluetoothLEAdvertisementWatcherStoppedEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BluetoothLEManufacturerData(pub ::windows::core::IInspectable); impl BluetoothLEManufacturerData { pub fn new() -> ::windows::core::Result<Self> { Self::IActivationFactory(|f| f.activate_instance::<Self>()) } fn IActivationFactory<R, F: FnOnce(&::windows::core::IActivationFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEManufacturerData, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn CompanyId(&self) -> ::windows::core::Result<u16> { let this = self; unsafe { let mut result__: u16 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u16>(result__) } } pub fn SetCompanyId(&self, value: u16) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Storage_Streams")] pub fn Data(&self) -> ::windows::core::Result<super::super::super::Storage::Streams::IBuffer> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Storage::Streams::IBuffer>(result__) } } #[cfg(feature = "Storage_Streams")] pub fn SetData<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IBuffer>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "Storage_Streams")] pub fn Create<'a, Param1: ::windows::core::IntoParam<'a, super::super::super::Storage::Streams::IBuffer>>(companyid: u16, data: Param1) -> ::windows::core::Result<BluetoothLEManufacturerData> { Self::IBluetoothLEManufacturerDataFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), companyid, data.into_param().abi(), &mut result__).from_abi::<BluetoothLEManufacturerData>(result__) }) } pub fn IBluetoothLEManufacturerDataFactory<R, F: FnOnce(&IBluetoothLEManufacturerDataFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BluetoothLEManufacturerData, IBluetoothLEManufacturerDataFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for BluetoothLEManufacturerData { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Bluetooth.Advertisement.BluetoothLEManufacturerData;{912dba18-6963-4533-b061-4694dafb34e5})"); } unsafe impl ::windows::core::Interface for BluetoothLEManufacturerData { type Vtable = IBluetoothLEManufacturerData_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x912dba18_6963_4533_b061_4694dafb34e5); } impl ::windows::core::RuntimeName for BluetoothLEManufacturerData { const NAME: &'static str = "Windows.Devices.Bluetooth.Advertisement.BluetoothLEManufacturerData"; } impl ::core::convert::From<BluetoothLEManufacturerData> for ::windows::core::IUnknown { fn from(value: BluetoothLEManufacturerData) -> Self { value.0 .0 } } impl ::core::convert::From<&BluetoothLEManufacturerData> for ::windows::core::IUnknown { fn from(value: &BluetoothLEManufacturerData) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BluetoothLEManufacturerData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Owned(self.0 .0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a BluetoothLEManufacturerData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BluetoothLEManufacturerData> for ::windows::core::IInspectable { fn from(value: BluetoothLEManufacturerData) -> Self { value.0 } } impl ::core::convert::From<&BluetoothLEManufacturerData> for ::windows::core::IInspectable { fn from(value: &BluetoothLEManufacturerData) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BluetoothLEManufacturerData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Owned(self.0) } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a BluetoothLEManufacturerData { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BluetoothLEManufacturerData {} unsafe impl ::core::marker::Sync for BluetoothLEManufacturerData {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct BluetoothLEScanningMode(pub i32); impl BluetoothLEScanningMode { pub const Passive: BluetoothLEScanningMode = BluetoothLEScanningMode(0i32); pub const Active: BluetoothLEScanningMode = BluetoothLEScanningMode(1i32); pub const None: BluetoothLEScanningMode = BluetoothLEScanningMode(2i32); } impl ::core::convert::From<i32> for BluetoothLEScanningMode { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for BluetoothLEScanningMode { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BluetoothLEScanningMode { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Devices.Bluetooth.Advertisement.BluetoothLEScanningMode;i4)"); } impl ::windows::core::DefaultType for BluetoothLEScanningMode { type DefaultType = Self; } #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisement(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisement { type Vtable = IBluetoothLEAdvertisement_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x066fb2b7_33d1_4e7d_8367_cf81d0f79653); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisement_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, companyid: u16, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, r#type: u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementBytePattern(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementBytePattern { type Vtable = IBluetoothLEAdvertisementBytePattern_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfbfad7f2_b9c5_4a08_bc51_502f8ef68a79); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementBytePattern_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i16) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementBytePatternFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementBytePatternFactory { type Vtable = IBluetoothLEAdvertisementBytePatternFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc2e24d73_fd5c_4ec3_be2a_9ca6fa11b7bd); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementBytePatternFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, datatype: u8, offset: i16, data: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementDataSection(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementDataSection { type Vtable = IBluetoothLEAdvertisementDataSection_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd7213314_3a43_40f9_b6f0_92bfefc34ae3); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementDataSection_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u8) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementDataSectionFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementDataSectionFactory { type Vtable = IBluetoothLEAdvertisementDataSectionFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe7a40942_a845_4045_bf7e_3e9971db8a6b); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementDataSectionFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, datatype: u8, data: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementDataTypesStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementDataTypesStatics { type Vtable = IBluetoothLEAdvertisementDataTypesStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3bb6472f_0606_434b_a76e_74159f0684d3); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementDataTypesStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u8) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementFilter(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementFilter { type Vtable = IBluetoothLEAdvertisementFilter_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x131eb0d3_d04e_47b1_837e_49405bf6f80f); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementFilter_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation_Collections"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisher(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementPublisher { type Vtable = IBluetoothLEAdvertisementPublisher_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcde820f9_d9fa_43d6_a264_ddd8b7da8b78); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisher_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BluetoothLEAdvertisementPublisherStatus) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisher2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementPublisher2 { type Vtable = IBluetoothLEAdvertisementPublisher2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfbdb545e_56f1_510f_a434_217fbd9e7bd2); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisher2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisherFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementPublisherFactory { type Vtable = IBluetoothLEAdvertisementPublisherFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5c5f065e_b863_4981_a1af_1c544d8b0c0d); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisherFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, advertisement: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisherStatusChangedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementPublisherStatusChangedEventArgs { type Vtable = IBluetoothLEAdvertisementPublisherStatusChangedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x09c2bd9f_2dff_4b23_86ee_0d14fb94aeae); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisherStatusChangedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BluetoothLEAdvertisementPublisherStatus) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::BluetoothError) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisherStatusChangedEventArgs2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementPublisherStatusChangedEventArgs2 { type Vtable = IBluetoothLEAdvertisementPublisherStatusChangedEventArgs2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8f62790e_dc88_5c8b_b34e_10b321850f88); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementPublisherStatusChangedEventArgs2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementReceivedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementReceivedEventArgs { type Vtable = IBluetoothLEAdvertisementReceivedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x27987ddf_e596_41be_8d43_9e6731d4a913); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementReceivedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BluetoothLEAdvertisementType) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementReceivedEventArgs2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementReceivedEventArgs2 { type Vtable = IBluetoothLEAdvertisementReceivedEventArgs2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x12d9c87b_0399_5f0e_a348_53b02b6b162e); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementReceivedEventArgs2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::BluetoothAddressType) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementWatcher(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementWatcher { type Vtable = IBluetoothLEAdvertisementWatcher_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa6ac336f_f3d3_4297_8d6c_c81ea6623f40); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementWatcher_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BluetoothLEAdvertisementWatcherStatus) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BluetoothLEScanningMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: BluetoothLEScanningMode) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::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 = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementWatcher2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementWatcher2 { type Vtable = IBluetoothLEAdvertisementWatcher2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x01bf26bc_b164_5805_90a3_e8a7997ff225); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementWatcher2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementWatcherFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementWatcherFactory { type Vtable = IBluetoothLEAdvertisementWatcherFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9aaf2d56_39ac_453e_b32a_85c657e017f1); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementWatcherFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, advertisementfilter: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementWatcherStoppedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEAdvertisementWatcherStoppedEventArgs { type Vtable = IBluetoothLEAdvertisementWatcherStoppedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xdd40f84d_e7b9_43e3_9c04_0685d085fd8c); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEAdvertisementWatcherStoppedEventArgs_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::BluetoothError) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEManufacturerData(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEManufacturerData { type Vtable = IBluetoothLEManufacturerData_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x912dba18_6963_4533_b061_4694dafb34e5); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEManufacturerData_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u16) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u16) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBluetoothLEManufacturerDataFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBluetoothLEManufacturerDataFactory { type Vtable = IBluetoothLEManufacturerDataFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc09b39f8_319a_441e_8de5_66a81e877a6c); } #[repr(C)] #[doc(hidden)] pub struct IBluetoothLEManufacturerDataFactory_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, companyid: u16, data: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, );
extern crate piston; extern crate graphics; extern crate glutin_window; extern crate opengl_graphics; extern crate rand; use std::collections::LinkedList; use piston::window::WindowSettings; use piston::event_loop::*; use piston::input::*; use glutin_window::GlutinWindow as Window; use opengl_graphics::{ GlGraphics, OpenGL }; use rand::prelude::*; const UNIT: u32 = 30; //单位方块大小 const WIDTH: u32 = UNIT * 30; const HEIGHT: u32 = UNIT * 20; const THICKNESS: u32 = UNIT; //墙的厚度,不要改 const BASESPEED: u64 = 2; //最低速度 const TITLE: &str = "SnakeGame Press Home to start, end to stop"; #[derive(Debug, Clone, Eq, PartialEq)] struct Point{ x: u32, y: u32, } #[derive(PartialEq, Eq)] enum Direction{ Up, Down, Left, Right, } #[derive(PartialEq, Eq)] enum State { Started, Stopped, Paused, } pub struct Game { gl: GlGraphics, // OpenGL drawing backend. dir: Direction, body: LinkedList<Point>, state: State, score: u32, goal: bool, food: Point, lv: u32, can_turn: bool, inited: bool, //wall: [Point; 4] } impl Game { fn render(&mut self, args: &RenderArgs) { use graphics::*; let body = &mut self.body; let food = &self.food; self.gl.draw(args.viewport(), |c, gl| { body.iter().for_each(|p: &Point| { // println!("{:?}", p); let body_square = rectangle::square(p.x as f64, p.y as f64, UNIT as f64); if p == body.front().unwrap(){ // snake head pure black rectangle(color::BLACK, body_square, c.transform, gl); } else { // snake body light gray rectangle(color::hex("555555"), body_square, c.transform, gl); } let food_square = rectangle::square(food.x as f64, food.y as f64, UNIT as f64); // let food to be red, why not? rectangle(color::hex("FF0000"), food_square, c.transform, gl); }); }); } fn update(&mut self, _args: &UpdateArgs) { if self.state == State::Started { self.inited = false; let body = &mut self.body; let dir = &self.dir; let mut last = Point{x:0, y:0}; if body.len() == 1 { // not possible if !self.goal{ last = body.pop_back().unwrap(); } else { last = body.front().unwrap().clone(); } } else if body.len() > 1{ if !self.goal{ body.pop_back(); } self.goal = false; last = (*body.front().unwrap()).clone(); } let p = match *dir { Direction::Up => Point{x: last.x, y: last.y - UNIT}, Direction::Down => Point{x: last.x, y: last.y + UNIT}, Direction::Left => Point{x: last.x - UNIT, y: last.y}, Direction::Right => Point{x: last.x + UNIT, y: last.y}, }; body.push_front(p); } } fn draw_wall(&mut self, args: &RenderArgs){ use graphics::*; let gl: &mut GlGraphics = &mut self.gl; //const BLACK: [f32; 4] = [ 0f32, 0f32, 0f32, 1f32 ]; // let l_wall = rectangle::Rectangle{color: BLACK, shape: rectangle::Shape::Square, border: BLACK}; let wall = Rectangle::new(color::BLACK); gl.draw(args.viewport(), |c, gl| { // Clear the screen clear(color::WHITE, gl); wall.draw([0 as f64,0 as f64,WIDTH as f64, THICKNESS as f64], &c.draw_state, c.transform, gl); wall.draw([0 as f64,(HEIGHT - THICKNESS) as f64,WIDTH as f64, THICKNESS as f64], &c.draw_state, c.transform, gl); wall.draw([0 as f64,0 as f64,THICKNESS as f64, HEIGHT as f64], &c.draw_state, c.transform, gl); wall.draw([(WIDTH - THICKNESS) as f64,0 as f64,THICKNESS as f64, HEIGHT as f64], &c.draw_state, c.transform, gl); }); } fn generate_food(&mut self){ // generate new food position // need random crate let mut rng = thread_rng(); let body = &self.body; loop { let x = rng.gen_range(1, 29); let y = rng.gen_range(1, 19); self.food = Point{x: x * UNIT, y: y * UNIT}; if !body.contains(&self.food){ break; } } } fn hit(&mut self) -> bool{ // self. 碰撞检测!! let head = self.body.front().unwrap(); let body = &self.body; if head.x < THICKNESS || head.x > WIDTH - (THICKNESS+UNIT) || head.y < THICKNESS || head.y > HEIGHT - (THICKNESS+UNIT) { // hit the wall true } else if body.iter().filter_map(|b| { if b.x == head.x && b.y == head.y { Some(b) } else{ None } }).collect::<LinkedList<&Point>>().len() > 1 { // println!("{:?}", body.iter().filter_map(|b| { // if b.x == head.x && b.y == head.y { // Some(b) // } // else{ // None // } // }).collect::<LinkedList<&Point>>()); // hit itself true } else { // didnot hit anything false } } fn eat(&mut self)-> bool{ // if ate a food, just set goal to true; update func will handle it let head = self.body.front().unwrap(); let food = &self.food; if head.x == food.x && head.y == food.y{ // println!("ate!"); true } else { false } } fn level_up(&mut self) { if self.lv < 8 { self.lv += 1; } } #[allow(non_snake_case)] fn button_pressed(&mut self, args: Key){ let can_turn = &mut self.can_turn; match args{ // Snake control Key::Up => { if self.dir != Direction::Down && *can_turn == true { self.dir = Direction::Up; *can_turn = false; } }, Key::Down => { if self.dir != Direction::Up && *can_turn == true { self.dir = Direction::Down; *can_turn = false } }, Key::Left => { if self.dir != Direction::Right && *can_turn == true { self.dir = Direction::Left; *can_turn = false } }, Key::Right => { if self.dir != Direction::Left && *can_turn == true { self.dir = Direction::Right; *can_turn = false } }, // Game control Key::Home => { //Start and Pause the game if self.state == State::Paused || self.state == State::Stopped{ self.state = State::Started; } else { self.state = State::Paused; } }, Key::End => { //Stop the game and reset game self.state = State::Stopped; }, _ => () } () } fn init(&mut self) { // reinit the game! self.state = State::Stopped; self.body.clear(); self.body.push_back(Point{x:UNIT*5, y:UNIT*5}); self.body.push_back(Point{x:UNIT*4, y:UNIT*5}); self.body.push_back(Point{x:UNIT*3, y:UNIT*5}); // test hit itself // self.body.push_back(Point{x:UNIT*2, y:UNIT*5}); // self.body.push_back(Point{x:UNIT*1, y:UNIT*5}); self.dir = Direction::Right; self.can_turn = true; self.score = 0; self.goal = false; self.generate_food(); self.lv = 1; self.inited = true; } } fn main() { // Change this to OpenGL::V2_1 if not working. let opengl = OpenGL::V4_3; // Create an Glutin window. let mut window: Window = WindowSettings::new( TITLE, [WIDTH, HEIGHT] ) .opengl(opengl) .resizable(false) .exit_on_esc(true) .build() .unwrap(); // Create a new game and run it. let mut game = Game { gl: GlGraphics::new(opengl), dir: Direction::Right, body: LinkedList::<Point>::new(), state: State::Stopped, score: 0u32, goal: false, food: Point{x: 0, y: 0}, lv: 1, can_turn: true, inited: true, }; game.init(); window.window.set_title((TITLE.to_owned() + " Current Score: " + &game.score.to_string() + " Lv: " + &game.lv.to_string()).as_str()); let mut events = Events::new(EventSettings::new()).ups(BASESPEED); while let Some(e) = events.next(&mut window) { if let Some(r) = e.render_args() { // println!("{:?}", game.can_turn); game.draw_wall(&r); game.render(&r); } if let Some(u) = e.update_args() { game.update(&u); game.can_turn = true; if game.hit(){ game.init(); window.window.set_title((TITLE.to_owned() + " Current Score: " + &game.score.to_string() + " Lv: " + &game.lv.to_string()).as_str()); } if game.state == State::Stopped && game.inited == false{ game.init(); window.window.set_title((TITLE.to_owned() + " Current Score: " + &game.score.to_string() + " Lv: " + &game.lv.to_string()).as_str()); // println!("{:?}", (TITLE.to_owned() + " Current Score: " + &game.score.to_string()).as_str()); // println!("inited") } // if snake does eat a food, just set goal to true, update func will handle it if game.eat(){ game.goal = true; game.score = game.score + 1; game.generate_food(); window.window.set_title((TITLE.to_owned() + " Current Score: " + &game.score.to_string() + " Lv: " + &game.lv.to_string()).as_str()); } if game.score % 5 == 0 && game.score != 0 && game.goal{ game.level_up(); window.window.set_title((TITLE.to_owned() + " Current Score: " + &game.score.to_string() + " Lv: " + &game.lv.to_string()).as_str()); } match game.lv{ 1 => events.set_ups(BASESPEED + 0), 2 => events.set_ups(BASESPEED + 1), 3 => events.set_ups(BASESPEED + 2), 4 => events.set_ups(BASESPEED + 4), 5 => events.set_ups(BASESPEED + 6), 6 => events.set_ups(BASESPEED + 8), 7 => events.set_ups(BASESPEED + 10), 8 => events.set_ups(BASESPEED + 12), _ => () } } if let Some(Button::Keyboard(key)) = e.press_args(){ game.button_pressed(key) } } }
use gitter::{self, Gitter}; use gtk; use gtk::{ContainerExt, EntryExt, LabelExt, WidgetExt}; use relm::Update; use relm::{Relm, Widget}; use std::time::Duration; use std::env; use core::msg::{AppState, Msg}; use core::model::Model; use futures_glib; pub struct Win { model: Model, window: gtk::ApplicationWindow, api: Gitter<'static>, } impl Win { fn create_msg_label(text: &str) -> gtk::Label { let label = gtk::Label::new(Some(text)); label.set_selectable(true); label.set_line_wrap(true); label.set_margin_top(5); label.set_margin_bottom(5); label.set_margin_left(5); label.set_justify(gtk::Justification::Fill); label.set_halign(gtk::Align::Start); label } fn update_impl(&mut self) { let rooms = self.api.get_rooms().unwrap(); for room in self.model.room_list_box.get_children() { self.model.room_list_box.remove(&room); } for room in rooms { let unread = room.unread_items; let text = if unread > 0 { format!("({}) {}", unread, room.name) } else { room.name }; let text: &str = &text; let label = gtk::Label::new(Some(text)); let row = gtk::ListBoxRow::new(); row.add(&label); self.model.room_list_box.add(&row); self.model.rooms.insert(row, room.id); } self.model.room_list_box.show_all(); self.model.set_state(AppState::Chat); for message in self.model.messages_box.get_children() { self.model.messages_box.remove(&message); } let room_id = self.model.current_room.clone(); self.model.current_room = room_id.clone(); let pagination = gitter::Pagination { skip: 0, before_id: None, after_id: None, limit: 15, query: None, }; if let Ok(messages) = self.api.get_messages(&room_id, Some(pagination)) { let message_ids: Vec<_> = messages.iter().map(|m| m.id.clone()).collect(); let user_id = self.api.get_user().unwrap().id; let _ = self.api .mark_messages_as_read(&user_id, &room_id, &message_ids); for message in messages { let text: &str = &format!("{}: {}", message.from.username, message.text); let label = Self::create_msg_label(text); self.model.messages_box.add(&label); } self.model.messages_box.show_all(); } else { // self.model.set_state(AppState::Loading); println!("Could not get messages"); } } } impl Update for Win { type Model = Model; type ModelParam = (); type Msg = Msg; fn model(relm: &Relm<Self>, _: Self::ModelParam) -> Self::Model { Model::new(relm) } fn update(&mut self, event: Self::Msg) { match event { Msg::Send(ref msg) => { self.api .send_message(&self.model.current_room, msg) .unwrap(); self.model.message_text.get_text().unwrap_or_default(); } Msg::Update(()) => { self.update_impl(); } Msg::SelectRoom(Some(ref row)) => { let needs_update = { let room_id = &self.model.rooms[row]; let needs_update = self.model.current_room == room_id.as_str(); self.model.current_room = room_id.clone(); needs_update }; if needs_update { self.update_impl(); } } Msg::Quit => { gtk::main_quit(); } _ => {} } } // TODO: Rewrite. fn subscriptions(&mut self, relm: &Relm<Self>) { let update_stream = futures_glib::Interval::new(Duration::from_secs(3)); relm.connect_exec_ignore_err(update_stream, Msg::Update); } } impl Widget for Win { type Root = gtk::ApplicationWindow; fn root(&self) -> Self::Root { self.window.clone() } fn view(_: &Relm<Self>, model: Self::Model) -> Self { let token = env::var("GITTER_API_TOKEN").expect("Needs GITTER_API_TOKEN env var"); let api = Gitter::new(token).unwrap(); let window = model.gtk_app.clone(); window.show_all(); Win { api, model, window } } }
use proc_macro; use proc_macro::TokenStream; use std::str::FromStr; #[cfg(feature = "enabled")] #[proc_macro_attribute] pub fn const_if_feature_enabled(_: TokenStream, item: TokenStream) -> TokenStream { let string = item.to_string(); let fn_index = string.find("fn").unwrap(); let res = format!("{}{} {}", &string[0..fn_index], "const", &string[fn_index..]); TokenStream::from_str(&res).unwrap() } #[cfg(not(feature = "enabled"))] #[proc_macro_attribute] pub fn const_if_feature_enabled(_: TokenStream, item: TokenStream) -> TokenStream { item }
pub trait Solution { fn check_it(x: i32) -> i32; } pub struct Solution1; pub struct Solution2; impl Solution for Solution1 { fn check_it(x: i32) -> i32 { x } } impl Solution for Solution2 { fn check_it(x: i32) -> i32 { x + 1 } }
//! # msfs-rs //! //! These bindings include: //! //! - MSFS Gauge API //! - SimConnect API //! - NanoVG API //! //! ## Building //! //! Tools such as `cargo-wasi` may not work. When in doubt, try invoking //! `cargo build --target wasm32-wasi` directly. //! //! If your MSFS SDK is not installed to `C:\MSFS SDK` you will need to set the //! `MSFS_SDK` env variable to the correct path. //! //! ## Known Issues and Work-Arounds //! //! ### Missing various exports //! Add a local `.cargo/config.toml` file with the following settings: //! ```toml //! [target.wasm32-wasi] //! rustflags = [ //! "-Clink-arg=--export-table", //! "-Clink-arg=--export=malloc", //! "-Clink-arg=--export=free", //! ] //! ``` mod msfs; pub mod sim_connect; pub mod sys; pub use msfs::*; #[cfg(any(target_arch = "wasm32", doc))] pub mod legacy; #[cfg(any(target_arch = "wasm32", doc))] pub mod nvg; #[doc(hidden)] pub mod executor;
pub(crate) mod calculator;
//! Unix domain sockets for Windows #[cfg(windows)] extern crate winapi; #[cfg(windows)] extern crate tempfile; #[cfg(windows)] mod stdnet; #[cfg(windows)] pub use crate::stdnet::{ from_path, AcceptAddrs, AcceptAddrsBuf, SocketAddr, UnixListener, UnixListenerExt, UnixStream, UnixStreamExt, };
// 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. //! # Implementation of `ucal.h`. //! //! As a general piece of advice, since a lot of documentation is currently elided, //! see the unit tests for example uses of each of the wrapper functions. use { log::trace, rust_icu_common as common, rust_icu_sys as sys, rust_icu_sys::versioned_function, rust_icu_sys::*, rust_icu_ustring as ustring, std::convert::TryFrom, std::ffi, }; /// Implements the UCalendar type from `ucal.h`. /// /// The naming `rust_icu_ucal::UCalendar` is a bit repetetetitive, but makes it /// a bit more obvious what ICU type it is wrapping. #[derive(Debug)] pub struct UCalendar { // Internal representation of the UCalendar, a pointer to a C type from ICU. // // The representation is owned by this type, and must be deallocated by calling // `sys::ucal_close`. rep: *mut sys::UCalendar, } impl Drop for UCalendar { /// Deallocates the internal representation of UCalendar. /// /// Implements `ucal_close`. fn drop(&mut self) { unsafe { versioned_function!(ucal_close)(self.rep); }; } } impl UCalendar { /// Creates a new UCalendar from a `UChar` zone ID. /// /// Use `new` to construct this from rust types only. fn new_from_uchar( zone_id: &ustring::UChar, locale: &str, cal_type: sys::UCalendarType, ) -> Result<UCalendar, common::Error> { let mut status = common::Error::OK_CODE; let asciiz_locale = ffi::CString::new(locale).map_err(|_| common::Error::string_with_interior_nul())?; // Requires that zone_id contains a valid Unicode character representation with known // beginning and length. asciiz_locale must be a pointer to a valid C string. The first // condition is assumed to be satisfied by ustring::UChar, and the second should be // satisfied by construction of asciiz_locale just above. let raw_ucal = unsafe { versioned_function!(ucal_open)( zone_id.as_c_ptr(), zone_id.len() as i32, asciiz_locale.as_ptr(), cal_type, &mut status, ) as *mut sys::UCalendar }; common::Error::ok_or_warning(status)?; Ok(UCalendar { rep: raw_ucal }) } /// Creates a new UCalendar. /// /// Implements `ucal_open`. pub fn new( zone_id: &str, locale: &str, cal_type: sys::UCalendarType, ) -> Result<UCalendar, common::Error> { let zone_id_uchar = ustring::UChar::try_from(zone_id)?; Self::new_from_uchar(&zone_id_uchar, locale, cal_type) } /// Returns this UCalendar's internal C representation. Use only for interfacing with the C /// low-level API. pub fn as_c_calendar(&self) -> *const sys::UCalendar { self.rep } } /// Implements `ucal_setDefaultTimeZone` pub fn set_default_time_zone(zone_id: &str) -> Result<(), common::Error> { let mut status = common::Error::OK_CODE; let mut zone_id_uchar = ustring::UChar::try_from(zone_id)?; zone_id_uchar.make_z(); // Requires zone_id_uchar to be a valid pointer until the function returns. unsafe { assert!(common::Error::is_ok(status)); versioned_function!(ucal_setDefaultTimeZone)(zone_id_uchar.as_c_ptr(), &mut status); }; common::Error::ok_or_warning(status) } /// Implements `ucal_getDefaultTimeZone` pub fn get_default_time_zone() -> Result<String, common::Error> { let mut status = common::Error::OK_CODE; // Preflight the time zone first. let time_zone_length = unsafe { assert!(common::Error::is_ok(status)); versioned_function!(ucal_getDefaultTimeZone)(0 as *mut sys::UChar, 0, &mut status) } as usize; common::Error::ok_preflight(status)?; // Should this capacity include the terminating \u{0}? let mut status = common::Error::OK_CODE; let mut uchar = ustring::UChar::new_with_capacity(time_zone_length); trace!("length: {}", time_zone_length); // Requires that uchar is a valid buffer. Should be guaranteed by the constructor above. unsafe { assert!(common::Error::is_ok(status)); versioned_function!(ucal_getDefaultTimeZone)( uchar.as_mut_c_ptr(), time_zone_length as i32, &mut status, ) }; common::Error::ok_or_warning(status)?; trace!("result: {:?}", uchar); String::try_from(&uchar) } /// Gets the current date and time, in milliseconds since the Epoch. /// /// Implements `ucal_getNow`. pub fn get_now() -> f64 { unsafe { versioned_function!(ucal_getNow)() as f64 } } #[cfg(test)] mod tests { use super::*; use rust_icu_uenum as uenum; #[test] fn test_open_time_zones() { let tz_iter = uenum::open_time_zones().expect("time zones opened"); assert_eq!( tz_iter.map(|r| { r.expect("timezone is available") }).take(3).collect::<Vec<String>>(), vec!["ACT", "AET", "AGT"] ); } #[test] fn test_open_time_zone_id_enumeration() { let tz_iter = uenum::open_time_zone_id_enumeration( sys::USystemTimeZoneType::UCAL_ZONE_TYPE_CANONICAL, "us", None, ) .expect("time zones available"); assert_eq!( tz_iter.map(|r| { r.expect("timezone is available") }).take(3).collect::<Vec<String>>(), vec!["America/Adak", "America/Anchorage", "America/Boise"] ); } #[test] fn test_open_country_time_zones() { let tz_iter = uenum::open_country_time_zones("us").expect("time zones available"); assert_eq!( tz_iter.map(|r| { r.expect("timezone is available") }).take(3).collect::<Vec<String>>(), vec!["AST", "America/Adak", "America/Anchorage"] ); } #[test] fn test_default_time_zone() { super::set_default_time_zone("America/Adak").expect("time zone set with success"); assert_eq!(super::get_default_time_zone().expect("time zone obtained"), "America/Adak",); } }
/* An experiment to use a greedy optimizer for landing a spaceship on the Moon from the Earth. Hopefully, without crashing. :) This is example is currently working, but is far from realistic. TODO: - [x] Add rigid body physics - [ ] Add gravity - [ ] Add force control of spaceship (instead of acceleration) - [ ] Add realistic scales to planets (mass, radius, distances) - [ ] Add Moon orbit (the Moon is moving relative to the Earth) - [ ] Add Earth atmosphere (air drag) - [ ] Add realistic spaceship control scales - [ ] Add spaceport source GPS coordinates - [ ] Add moonbase target GPS coordinates - [ ] Add spaceship geometry - [ ] Add Moon landscape geometry - [ ] Add more realistic spaceship thrusters (off-center) - [ ] Add rocket fuel physics - [ ] Add rocket stage separation carrying spaceship (change of mass) */ use max_tree::prelude::*; use rigid_body::{RigidBody, Attitude}; /// Stores information about a planet. pub struct Planet { /// Name of planet. pub name: String, /// Position. pub pos: [f64; 3], /// Mass. pub mass: f64, /// Radius. pub radius: f64, } impl Planet { /// Calculates distance to the planet's surface. /// /// If negative, the position is below the surface. pub fn distance(&self, pos: [f64; 3]) -> f64 { use vecmath::vec3_len as len; use vecmath::vec3_sub as sub; len(sub(self.pos, pos)) - self.radius } } /// Used as node data. #[derive(Clone, Debug)] pub struct Spaceship { /// Rigid body physics. pub rigid_body: RigidBody<f64>, /// Mass. pub mass: f64, } impl Spaceship { /// Calculates the speed. pub fn speed(&self) -> f64 { use vecmath::vec3_len as len; len(self.rigid_body.vel) } } /// Represents objects in space. pub struct Space { /// Fixed timestep. pub dt: f64, /// List of planets. pub planets: Vec<Planet>, /// State of spaceship. pub spaceship: Spaceship, /// The planet of destination. pub target_planet: usize, /// The target orientation. pub target_orientation: Attitude<f64>, } /// Calculates the angle between vectors. pub fn angle_between_vectors(a: [f64; 3], b: [f64; 3]) -> f64 { use vecmath::vec3_dot as dot; use vecmath::vec3_len as len; (dot(a, b) / (len(a) * len(b))).acos() } impl Space { /// Calculates utility for getting close to the surface of a planet. pub fn utility_get_close_to_surface(&self, planet: usize) -> f64 { -self.planets[planet].distance(self.spaceship.rigid_body.pos).abs() } /// Calculates utility for stopping spaceship. pub fn utility_full_stop(&self) -> f64 { -self.spaceship.speed() } /// Calculates utility for spaceship orientation. pub fn utility_orientation(&self) -> f64 { let spaceship_angle = self.spaceship.rigid_body.ori.0; let target_angle = self.target_orientation.0; let spaceship_dir = [spaceship_angle.cos(), spaceship_angle.sin(), 0.0]; let target_dir = [target_angle.cos(), target_angle.sin(), 0.0]; let utility_angle = -angle_between_vectors(target_dir, spaceship_dir).abs(); let spaceship_axis = self.spaceship.rigid_body.ori.1; let target_axis = self.target_orientation.1; let utility_axis = -angle_between_vectors(target_axis, spaceship_axis).abs(); utility_angle + utility_axis } } #[derive(Debug, Clone)] pub enum Action { /// Acceleration. Acc([f64; 3]), /// Wrench. Wre(Attitude<f64>), } pub const EARTH: usize = 0; pub const MOON: usize = 1; fn main() { let mut space = Space { planets: vec![ Planet { pos: [0.0, 0.0, 0.0], mass: 1.0, radius: 1.0, name: "Earth".into(), }, Planet { pos: [3.0, 0.0, 0.0], mass: 1.0, radius: 1.0, name: "Moon".into(), }, ], spaceship: Spaceship { rigid_body: RigidBody { pos: [0.0, 0.0, 0.0], vel: [0.0, 0.0, 0.0], acc: [0.0, 0.0, 0.0], ori: (0.0, [1.0, 0.0, 0.0]), tor: (0.0, [1.0, 0.0, 0.0]), wre: (0.0, [1.0, 0.0, 0.0]), }, mass: 1.0, }, dt: 0.5, target_planet: MOON, target_orientation: (1.0, [1.0, 0.0, 0.0]), }; let max_depth = 10; let eps_depth = 0.0; let mut settings = AiSettings::new(max_depth, eps_depth); settings.analysis = true; settings.max_mib = Some(10.0); let mut ai = Ai { actions: actions_x, execute: execute, settings: settings, undo: undo, utility: utility2, analysis: AiAnalysis::new(), }; let mut root = Node::root(space.spaceship.clone()); ai.greedy(&mut root, 0, &mut space); let mut wrench_count = 0; let mut node = &root; loop { let utility = (ai.utility)(&node.data, &space); let rigid_body = &space.spaceship.rigid_body; println!( "Pos: {:?}\nVel: {:?}\nOri: {:?}\nTor: {:?}\nUtility: {}\n", rigid_body.pos, rigid_body.vel, rigid_body.ori, rigid_body.tor, utility ); if let Some(i) = ai.update(node, &mut space) { let action = &node.children[i].0; if let Action::Wre(_) = action { wrench_count += 1; } println!("Action: {:?}", node.children[i].0); node = &node.children[i].1; } else { break; } } println!("Wrench count: {}", wrench_count); let analysis = &ai.analysis; println!("GiB: {}", analysis.gib(ai.node_size())); println!("MiB: {}", analysis.mib(ai.node_size())); println!("KiB: {}", analysis.kib(ai.node_size())); } pub fn acc_xyz(v: f64, arr: &mut Vec<Action>) { arr.push(Action::Acc([v, 0.0, 0.0])); arr.push(Action::Acc([-v, 0.0, 0.0])); arr.push(Action::Acc([0.0, v, 0.0])); arr.push(Action::Acc([0.0, -v, 0.0])); arr.push(Action::Acc([0.0, 0.0, v])); arr.push(Action::Acc([0.0, 0.0, -v])); } pub fn acc_x(v: f64, arr: &mut Vec<Action>) { arr.push(Action::Acc([v, 0.0, 0.0])); arr.push(Action::Acc([-v, 0.0, 0.0])); } pub fn wre_x(v: f64, arr: &mut Vec<Action>) { arr.push(Action::Wre((v, [1.0, 0.0, 0.0]))); arr.push(Action::Wre((-v, [1.0, 0.0, 0.0]))); } pub fn actions_x(_: &Spaceship, _: &Space) -> Vec<Action> { let mut arr = vec![]; acc_x(0.1, &mut arr); acc_x(0.2, &mut arr); acc_x(0.3, &mut arr); acc_x(0.5, &mut arr); acc_x(0.6, &mut arr); acc_x(1.0, &mut arr); acc_x(1.2, &mut arr); acc_x(1.3, &mut arr); wre_x(0.1, &mut arr); arr } pub fn actions_xyz(_: &Spaceship, _: &Space) -> Vec<Action> { let mut arr = vec![]; acc_xyz(0.1, &mut arr); acc_xyz(0.2, &mut arr); acc_xyz(0.3, &mut arr); acc_xyz(0.5, &mut arr); acc_xyz(0.6, &mut arr); acc_xyz(1.0, &mut arr); acc_xyz(1.2, &mut arr); acc_xyz(1.3, &mut arr); arr } fn execute(_: &Spaceship, acc: &Action, space: &mut Space) -> Result<Spaceship, ()> { let old = space.spaceship.clone(); match acc { Action::Acc(acc) => { // Set spaceship acceleration. space.spaceship.rigid_body.acc = *acc; } Action::Wre(wre) => { // Set spaceship wrench. space.spaceship.rigid_body.wre = *wre; } } space.spaceship.rigid_body.update(space.dt); Ok(old) } fn undo(old: &Spaceship, space: &mut Space) { // Reset spaceship position. space.spaceship = old.clone(); } /// Computes utility of getting close to surface. fn utility_get_close_to_surface(space: &Space) -> f64 { space.utility_get_close_to_surface(space.target_planet) } /// Computes utility of stopping spaceship. fn utility_full_stop(space: &Space) -> f64 { let dist = space.planets[space.target_planet] .distance(space.spaceship.rigid_body.pos).abs(); absoid(0.2, 1.0, dist) * space.utility_full_stop() } fn utility_orientation(space: &Space) -> f64 { let dist = space.planets[space.target_planet] .distance(space.spaceship.rigid_body.pos).abs(); absoid(0.2, 1.0, dist) * space.utility_orientation() } /// Used with `full`. pub fn utility1(_: &Spaceship, space: &Space) -> f64 { utility_get_close_to_surface(space) + space.utility_full_stop() } /// Used with `greedy`. pub fn utility2(_: &Spaceship, space: &Space) -> f64 { utility_get_close_to_surface(space) + utility_full_stop(space) + utility_orientation(space) } /// Used to control transition to full stop. /// /// For more information, see paper about "Absoid Functions" /// (https://github.com/advancedresearch/path_semantics/blob/master/papers-wip/absoid-functions.pdf). pub fn absoid(z: f64, n: f64, x: f64) -> f64 { 1.0 / ((x / z).powf(n) + 1.0) }
use midi_message::MidiMessage; use color::Color; use color_strip::ColorStrip; use effects::effect::Effect; use rainbow::get_rainbow_color; pub struct Flash { color_strip: ColorStrip } impl Flash { pub fn new(led_count: usize) -> Flash { Flash { color_strip: ColorStrip::new(led_count) } } } impl Effect for Flash { fn paint(&mut self, color_strip: &mut ColorStrip) { color_strip.add(&self.color_strip); } fn tick(&mut self) { let darkened_first_pixel = self.color_strip.pixel[0] - Color::gray(10); self.color_strip.insert(darkened_first_pixel); } fn on_midi_message(&mut self, midi_message: MidiMessage) { if let MidiMessage::NoteOn(_, note, _) = midi_message { self.color_strip.pixel[0] = get_rainbow_color(note); } } }
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub enum Format { Unknown, R32UNorm, R16UNorm, R8Unorm, RGBA8UNorm, RGBA8Srgb, BGR8UNorm, BGRA8UNorm, DXT1, DXT1Alpha, DXT3, DXT5, R16Float, R32Float, RG32Float, RG16Float, RGB32Float, RGBA32Float, RG16UNorm, RG8UNorm, R32UInt, RGBA16Float, R11G11B10Float, RG16UInt, R16UInt, R16SNorm, D16, D16S8, D32, D32S8, D24 } impl Format { pub fn is_depth(&self) -> bool { matches!(self, Format::D32 | Format::D16 | Format::D16S8 | Format::D24 | Format::D32S8) } pub fn is_stencil(&self) -> bool { matches!(self, Format::D16S8 | Format::D24 | Format::D32S8) } pub fn is_compressed(&self) -> bool { matches!(self, Format::DXT1 | Format::DXT1Alpha | Format::DXT3 | Format::DXT5) } pub fn element_size(&self) -> u32 { match self { Format::R32Float => 4, Format::R16Float => 2, Format::RG32Float => 8, Format::RGB32Float => 12, Format::RGBA32Float => 16, _ => todo!() } } pub fn srgb_format(&self) -> Option<Format> { match self { Format::RGBA8UNorm => Some(Format::RGBA8Srgb), _ => None } } }
//! Private module for selective re-export. use crate::util::DenseNatMap; use crate::Rewrite; use std::fmt; use std::iter::FromIterator; use std::ops::Index; /// A `RewritePlan<R>` is derived from a data structure instance and indicates how values of type /// `R` (short for "rewritten") should be rewritten. When that plan is recursively applied via /// [`Rewrite`], the resulting data structure instance will be behaviorally equivalent to the /// original data structure under a symmetry equivalence relation, enabling symmetry reduction. /// /// Typically the `RewritePlan` would be constructed by an implementation of [`Representative`] for /// [`Model::State`]. /// /// [`Model::State`]: crate::Model::State /// [`Representative`]: crate::Representative pub struct RewritePlan<R, S> { s: S, f: fn(&R, &S) -> R, } impl<R, S> RewritePlan<R, S> { /// Applies the rewrite plan to a value of type R pub fn rewrite(&self, x: &R) -> R { (self.f)(x, &self.s) } /// Returns the state. Useful for debugging pub fn get_state(&self) -> &S { &self.s } /// Creates a new rewrite plan from a given state and function pub fn new(s: S, f: fn(&R, &S) -> R) -> Self { RewritePlan { s, f } } } impl<R, S> fmt::Debug for RewritePlan<R, S> where S: fmt::Debug, { fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result { fmt.debug_struct("RewritePlan") .field("S", &self.s) .finish_non_exhaustive() } } impl<R, V> From<DenseNatMap<R, V>> for RewritePlan<R, DenseNatMap<R, R>> where R: From<usize> + Copy, usize: From<R>, V: Ord, { fn from(s: DenseNatMap<R, V>) -> Self { Self::from_values_to_sort(s.values()) } } impl<R, V> From<&DenseNatMap<R, V>> for RewritePlan<R, DenseNatMap<R, R>> where R: From<usize> + Copy, usize: From<R>, V: Ord, { fn from(s: &DenseNatMap<R, V>) -> Self { Self::from_values_to_sort(s.values()) } } impl<R> RewritePlan<R, DenseNatMap<R, R>> where R: From<usize> + Copy, usize: From<R>, { /// Constructs a `RewritePlan` by sorting values in a specified iterator. Favor using the /// [`RewritePlan::new`] constructor over this one as it provides additional type safety. pub fn from_values_to_sort<'a, V: 'a>(to_sort: impl IntoIterator<Item = &'a V>) -> Self where R: From<usize>, usize: From<R>, V: Ord, { // Example in comments // [B,C,A] let mut combined = to_sort.into_iter().enumerate().collect::<Vec<_>>(); // [(0,B), (1,C), (2,A)] combined.sort_by_key(|(_, v)| *v); // [(2,A), (0,B), (1,C)] let mut combined: Vec<_> = combined.iter().enumerate().collect(); // [(0,(2,A)), (1,(0,B)), (2,(1,C))] combined.sort_by_key(|(_, (i, _))| i); // [(1,(0,B)), (2,(1,C)), (0,(2,A))] let map: DenseNatMap<R, R> = combined .iter() .map(|(sid, (_, _))| (*sid).into()) .collect::<Vec<R>>() .into(); RewritePlan { s: map, f: (|&x, s| *s.get(x).unwrap()), } } /// Permutes the elements of a [`Vec`]-like collection whose indices correspond with the /// indices of the `Vec`-like that was used to construct this `RewritePlan`. pub fn reindex<C>(&self, indexed: &C) -> C where C: Index<usize>, C: FromIterator<C::Output>, C::Output: Rewrite<R> + Sized, { let mut inverse_map = self.s.iter().map(|(i, &v)| (v, i)).collect::<Vec<_>>(); inverse_map.sort_by_key(|(k, _)| Into::<usize>::into(*k)); inverse_map .iter() .map(|(_, i)| indexed[(*i).into()].rewrite(self)) .collect::<C>() } } #[cfg(test)] mod test { use super::*; use crate::actor::Id; use std::collections::{BTreeMap, BTreeSet, VecDeque}; #[test] fn from_sort_sorts() { let original = vec!['B', 'D', 'C', 'A']; let plan = RewritePlan::<Id, _>::from_values_to_sort(&original); assert_eq!(plan.reindex(&original), vec!['A', 'B', 'C', 'D']); assert_eq!(plan.reindex(&vec![1, 3, 2, 0]), vec![0, 1, 2, 3]); } #[test] fn can_reindex() { use crate::actor::Id; let swap_first_and_last = RewritePlan::<Id, _>::from_values_to_sort(&vec![2, 1, 0]); let rotate_left = RewritePlan::<Id, _>::from_values_to_sort(&vec![2, 0, 1]); let original = vec!['A', 'B', 'C']; assert_eq!(swap_first_and_last.reindex(&original), vec!['C', 'B', 'A']); assert_eq!(rotate_left.reindex(&original), vec!['B', 'C', 'A']); let original: VecDeque<_> = vec!['A', 'B', 'C'].into_iter().collect(); assert_eq!( swap_first_and_last.reindex(&original), vec!['C', 'B', 'A'].into_iter().collect::<VecDeque<_>>() ); assert_eq!( rotate_left.reindex(&original), vec!['B', 'C', 'A'].into_iter().collect::<VecDeque<_>>() ); } #[test] fn can_rewrite() { #[derive(Debug, PartialEq)] struct GlobalState { process_states: DenseNatMap<Id, char>, run_sequence: Vec<Id>, zombies1: BTreeSet<Id>, zombies2: BTreeMap<Id, bool>, zombies3: DenseNatMap<Id, bool>, } impl Rewrite<Id> for GlobalState { fn rewrite<S>(&self, plan: &RewritePlan<Id, S>) -> Self { Self { process_states: self.process_states.rewrite(plan), run_sequence: self.run_sequence.rewrite(plan), zombies1: self.zombies1.rewrite(plan), zombies2: self.zombies2.rewrite(plan), zombies3: self.zombies3.rewrite(plan), } } } let gs = GlobalState { process_states: DenseNatMap::from_iter(['B', 'A', 'A', 'C']), run_sequence: Id::vec_from([2, 2, 2, 2, 3]).into_iter().collect(), zombies1: Id::vec_from([0, 2]).into_iter().collect(), zombies2: vec![(0.into(), true), (2.into(), true)] .into_iter() .collect(), zombies3: vec![true, false, true, false].into_iter().collect(), }; let plan = (&gs.process_states).into(); assert_eq!( gs.rewrite(&plan), GlobalState { process_states: DenseNatMap::from_iter(['A', 'A', 'B', 'C']), run_sequence: Id::vec_from([1, 1, 1, 1, 3]).into_iter().collect(), zombies1: Id::vec_from([1, 2]).into_iter().collect(), zombies2: vec![(1.into(), true), (2.into(), true)] .into_iter() .collect(), zombies3: vec![false, true, true, false].into_iter().collect(), } ); } }
pub mod camera; pub mod homogeneous; pub mod interpolation; pub mod projection; pub mod semi_dense; pub mod transform; pub mod triangulation; pub mod warp;
#![deny(missing_docs)] //! A crate implementing cancellable synchronous network I/O. //! //! This crate exposes structs [TcpStream](struct.TcpStream.html), //! [TcpListener](struct.TcpListener.html) and [UdpSocket](struct.UdpSocket.html) //! that are similar to their std::net variants, except that I/O operations //! can be cancelled through [Canceller](struct.Canceller.html) objects //! created with them. //! //! Most methods work as they do in the std::net implementations, and you //! should refer to the [original documentation](https://doc.rust-lang.org/std/net/) //! for details and examples. //! //! Main differences with the original std::net implementations : //! * Methods that return a [TcpStream](struct.TcpStream.html), a //! [TcpListener](struct.TcpListener.html), or an [UdpSocket](struct.UdpSocket.html) //! also return a [Canceller](struct.Canceller.html) object. //! * There are no peek() methods (yet?) //! * [TcpListener](struct.TcpListener.html) and [UdpSocket](struct.UdpSocket.html) //! are not `Sync` (yet?) //! //! # Example //! ``` //! use cancellable_io::*; //! let (listener, canceller) = TcpListener::bind("127.0.0.1:0").unwrap(); //! let handle = std::thread::spawn(move || { //! println!("Waiting for connections."); //! let r = listener.accept(); //! assert!(is_cancelled(&r.unwrap_err())); //! println!("Server cancelled."); //! }); //! //! std::thread::sleep(std::time::Duration::from_secs(2)); //! canceller.cancel().unwrap(); //! handle.join().unwrap(); //! ``` extern crate mio; use std::cell::RefCell; use std::fmt; use std::fmt::{Debug, Formatter}; use std::io; use std::io::{Read, Write}; use std::net::{Ipv4Addr, Ipv6Addr, SocketAddr, ToSocketAddrs}; use std::sync::{Arc, RwLock}; use std::time::Duration; use mio::*; const STOP_TOKEN: Token = Token(0); const OBJECT_TOKEN: Token = Token(1); /// An object that can be used to cancel an i/o operation. /// /// It is created with the object it can cancel. /// When an operation is cancelled, it returns an error that can be /// identified with the [is_cancelled](fn.is_cancelled.html) function. #[derive(Clone, Debug)] pub struct Canceller { set_readiness: SetReadiness, } /// A TCP stream between a local and a remote socket. /// /// The socket will be closed when the value is dropped. /// /// The [read](struct.TcpStream.html#method.read) and /// [write](struct.TcpStream.html#method.write) methods can be interrupted /// using the [Canceller](struct.Canceller.html) object created with the /// stream. /// /// Otherwise similar to /// [std::net::TcpStream](https://doc.rust-lang.org/std/net/struct.TcpStream.html). pub struct TcpStream { stream: mio::net::TcpStream, poll: Poll, _stop_registration: Registration, events: Events, options: Arc<RwLock<TcpStreamOptions>>, } struct TcpStreamOptions { read_timeout: Option<Duration>, write_timeout: Option<Duration>, nonblocking: bool, } /// A TCP socket server, listening for connections. /// /// The socket will be closed when the value is dropped. /// /// The [accept](struct.TcpListener.html#method.accept) and the /// [incoming](struct.TcpListener.html#method.incoming) methods can be /// interrupted using the [Canceller](struct.Canceller.html) object /// created with the socket. /// /// Otherwise similar to /// [std::net::TcpListener](https://doc.rust-lang.org/std/net/struct.TcpListener.html). pub struct TcpListener { listener: mio::net::TcpListener, poll: Poll, _stop_registration: Registration, // RefCell makes TcpListener !Sync while std::net::TcpListener is, but // using a Mutex would conflict with nonblocking mode, and allocating // events on each call to accept() is not that nice. So let's keep it // this way for now. One can always use try_clone() anyway if sharing // a socket between threads is needed. events: RefCell<Events>, options: Arc<RwLock<TcpListenerOptions>>, } struct TcpListenerOptions { timeout: Option<Duration>, nonblocking: bool, } /// An iterator that infinitely [accept](struct.TcpListener.html#method.accept)s /// connections on a TcpListener. /// /// It is created by the [incoming](struct.TcpListener.html#method.incoming) method. pub struct Incoming<'a> { listener: &'a TcpListener, } /// An UDP socket bound to an address. /// /// The [recv_from](struct.UdpSocket.html#method.recv_from), /// [send_to](struct.UdpSocket.html#method.send_to), /// [recv](struct.UdpSocket.html#method.recv), and /// [send](struct.UdpSocket.html#method.send) can be interrupted using the /// [Canceller](struct.Canceller.html) object created with the socket. /// /// Otherwise similar to /// [std::net::UdpSocket](https://doc.rust-lang.org/std/net/struct.UdpSocket.html). pub struct UdpSocket { socket: mio::net::UdpSocket, poll: Poll, _stop_registration: Registration, events: RefCell<Events>, // !Sync, cf TcpListener. options: Arc<RwLock<UdpSocketOptions>>, } struct UdpSocketOptions { read_timeout: Option<Duration>, write_timeout: Option<Duration>, nonblocking: bool, } impl Canceller { /// Cancels an operation on the associated object. /// /// The pending operation is aborted and returns an error that can be /// checked by the [is_cancelled](fn.is_cancelled.html) function. If /// there is no pending operation, the next one will be cancelled. pub fn cancel(&self) -> io::Result<()> { self.set_readiness.set_readiness(Ready::readable()) } } fn cancelled_error() -> io::Error { // Can't use ErrorKind::Interrupted because it causes silent retries // from various library functions. io::Error::new(io::ErrorKind::Other, "cancelled") } /// Checks if the error returned by a method was caused by the operation /// being cancelled. pub fn is_cancelled(e: &io::Error) -> bool { e.kind() == io::ErrorKind::Other && e.to_string() == "cancelled" } impl TcpStream { fn simple_connect(address: &SocketAddr) -> io::Result<(Self, Canceller)> { let poll = Poll::new()?; let (stop_registration, stop_set_readiness) = Registration::new2(); poll.register( &stop_registration, STOP_TOKEN, Ready::readable(), PollOpt::edge(), )?; let stream = mio::net::TcpStream::connect(address)?; poll.register( &stream, OBJECT_TOKEN, Ready::readable() | Ready::writable(), PollOpt::level(), )?; let events = Events::with_capacity(4); Ok(( TcpStream { stream, poll, _stop_registration: stop_registration, events, options: Arc::new(RwLock::new(TcpStreamOptions { read_timeout: None, write_timeout: None, nonblocking: false, })), }, Canceller { set_readiness: stop_set_readiness, }, )) } /// Creates a new TCP stream with an object used to cancel read/write /// operations, and connects it to a remote address. pub fn connect<A: ToSocketAddrs>(address: A) -> io::Result<(Self, Canceller)> { let mut error = io::Error::from(io::ErrorKind::InvalidInput); for a in address.to_socket_addrs()? { match Self::simple_connect(&a) { Ok(r) => return Ok(r), Err(e) => error = e, } } Err(error) } /// Returns the socket address of the remote peer of this TCP connection. pub fn peer_addr(&self) -> io::Result<SocketAddr> { self.stream.peer_addr() } /// Returns the socket address of the local half of this TCP connection. pub fn local_addr(&self) -> io::Result<SocketAddr> { self.stream.local_addr() } /// Shuts down the read, write, or both halves of this connection. pub fn shutdown(&self, how: std::net::Shutdown) -> io::Result<()> { self.stream.shutdown(how) } /// Creates a new independently owned handle to the underlying socket. /// The [Canceller](struct.Canceller.html)s associated with the original /// object and its clone are also independent. pub fn try_clone(&self) -> io::Result<(Self, Canceller)> { let poll = Poll::new()?; let (stop_registration, stop_set_readiness) = Registration::new2(); poll.register( &stop_registration, STOP_TOKEN, Ready::readable(), PollOpt::edge(), )?; let stream = self.stream.try_clone()?; poll.register( &stream, OBJECT_TOKEN, Ready::readable() | Ready::writable(), PollOpt::level(), )?; let events = Events::with_capacity(4); Ok(( TcpStream { stream, poll, _stop_registration: stop_registration, events, options: self.options.clone(), }, Canceller { set_readiness: stop_set_readiness, }, )) } /// Sets the read timeout. pub fn set_read_timeout(&self, duration: Option<Duration>) -> io::Result<()> { self.options.write().unwrap().read_timeout = duration; Ok(()) } /// Sets the write timeout. pub fn set_write_timeout(&self, duration: Option<Duration>) -> io::Result<()> { self.options.write().unwrap().write_timeout = duration; Ok(()) } /// Gets the read timeout. pub fn read_timeout(&self) -> io::Result<Option<Duration>> { Ok(self.options.read().unwrap().read_timeout) } /// Gets the write timeout. pub fn write_timeout(&self) -> io::Result<Option<Duration>> { Ok(self.options.read().unwrap().write_timeout) } //pub fn peek(&self) /// Sets the value of the `TCP_NODELAY` option on this socket. pub fn set_nodelay(&self, nodelay: bool) -> io::Result<()> { self.stream.set_nodelay(nodelay) } /// Gets the value of the `TCP_NODELAY` option for this socket. pub fn nodelay(&self) -> io::Result<bool> { self.stream.nodelay() } /// Sets the value for the `IP_TTL` option on this socket. pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.stream.set_ttl(ttl) } /// Gets the value for the `IP_TTL` option for this socket. pub fn ttl(&self) -> io::Result<u32> { self.stream.ttl() } /// Gets the value of the `SO_ERROR` option for this socket. pub fn take_error(&self) -> io::Result<Option<io::Error>> { self.stream.take_error() } /// Moves this TCP stream into or out of nonblocking mode. pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { self.options.write().unwrap().nonblocking = nonblocking; Ok(()) } } impl Read for TcpStream { /// Reads data from the socket. This operation can be cancelled /// by the associated [Canceller](struct.Canceller.html) object. fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.poll.reregister( &self.stream, OBJECT_TOKEN, Ready::readable(), PollOpt::level(), )?; if self.options.read().unwrap().nonblocking { self.poll .poll(&mut self.events, Some(Duration::from_millis(0)))?; for event in self.events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_readable() { return self.stream.read(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } Err(io::Error::from(io::ErrorKind::WouldBlock)) } else { let read_timeout = self.options.read().unwrap().read_timeout; loop { self.poll.poll(&mut self.events, read_timeout)?; for event in self.events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_readable() { return self.stream.read(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } if read_timeout.is_some() { return Err(io::Error::from(io::ErrorKind::TimedOut)); } } } } } impl Write for TcpStream { /// Writes data to the socket. This operation can be cancelled /// by the associated [Canceller](struct.Canceller.html) object. fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.poll.reregister( &self.stream, OBJECT_TOKEN, Ready::writable(), PollOpt::level(), )?; if self.options.read().unwrap().nonblocking { self.poll .poll(&mut self.events, Some(Duration::from_millis(0)))?; for event in self.events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_writable() { return self.stream.write(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } Err(io::Error::from(io::ErrorKind::WouldBlock)) } else { let write_timeout = self.options.read().unwrap().write_timeout; loop { self.poll.poll(&mut self.events, write_timeout)?; for event in self.events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_writable() { return self.stream.write(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } if write_timeout.is_some() { return Err(io::Error::from(io::ErrorKind::TimedOut)); } } } } fn flush(&mut self) -> io::Result<()> { self.poll.reregister( &self.stream, OBJECT_TOKEN, Ready::writable(), PollOpt::level(), )?; loop { self.poll.poll(&mut self.events, None)?; for event in self.events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_writable() { return self.stream.flush(); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } } } } impl Debug for TcpStream { fn fmt(&self, f: &mut Formatter) -> fmt::Result { self.stream.fmt(f) } } impl TcpListener { fn simple_bind(address: &SocketAddr) -> io::Result<(Self, Canceller)> { let poll = Poll::new()?; let (stop_registration, stop_set_readiness) = Registration::new2(); poll.register( &stop_registration, STOP_TOKEN, Ready::readable(), PollOpt::edge(), )?; let listener = mio::net::TcpListener::bind(address)?; poll.register(&listener, OBJECT_TOKEN, Ready::readable(), PollOpt::level())?; let events = Events::with_capacity(4); Ok(( TcpListener { listener, poll, _stop_registration: stop_registration, events: RefCell::new(events), options: Arc::new(RwLock::new(TcpListenerOptions { timeout: None, nonblocking: false, })), }, Canceller { set_readiness: stop_set_readiness, }, )) } /// Creates a new [TcpListener](struct.TcpListener.html) which will be /// bound to the specified address, together with an object that allows /// cancelling [accept](struct.TcpListener.html#method.accept) operations. pub fn bind<A: ToSocketAddrs>(address: A) -> io::Result<(Self, Canceller)> { let mut error = io::Error::from(io::ErrorKind::InvalidInput); for a in address.to_socket_addrs()? { match Self::simple_bind(&a) { Ok(r) => return Ok(r), Err(e) => error = e, } } Err(error) } /// Returns the local socket address of this listener. pub fn local_addr(&self) -> io::Result<SocketAddr> { self.listener.local_addr() } /// Creates a new independently owned handle to the underlying socket. pub fn try_clone(&self) -> io::Result<(Self, Canceller)> { let poll = Poll::new()?; let (stop_registration, stop_set_readiness) = Registration::new2(); poll.register( &stop_registration, STOP_TOKEN, Ready::readable(), PollOpt::edge(), )?; let listener = self.listener.try_clone()?; poll.register(&listener, OBJECT_TOKEN, Ready::readable(), PollOpt::level())?; let events = Events::with_capacity(4); Ok(( TcpListener { listener, poll, _stop_registration: stop_registration, events: RefCell::new(events), options: self.options.clone(), }, Canceller { set_readiness: stop_set_readiness, }, )) } /// Accepts a new incoming connection from this listener. /// /// This method can be cancelled by the associated [Canceller](struct.Canceller.html) /// object. /// /// This method returns a [TcpStream](struct.TcpStream.html) with an /// associated [Canceller](struct.Canceller.html) and the address of the /// remote peer. pub fn accept(&self) -> io::Result<(TcpStream, Canceller, SocketAddr)> { let mut events = self.events.borrow_mut(); if self.options.read().unwrap().nonblocking { self.poll .poll(&mut events, Some(Duration::from_millis(0)))?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { let (stream, addr) = self.listener.accept()?; let poll = Poll::new()?; let stop_token = Token(0); let (stop_registration, stop_set_readiness) = Registration::new2(); poll.register( &stop_registration, stop_token, Ready::readable(), PollOpt::edge(), )?; let stream_token = Token(1); poll.register( &stream, stream_token, Ready::readable() | Ready::writable(), PollOpt::level(), )?; let events = Events::with_capacity(4); return Ok(( TcpStream { stream, poll, _stop_registration: stop_registration, events, options: Arc::new(RwLock::new(TcpStreamOptions { read_timeout: None, write_timeout: None, nonblocking: false, })), }, Canceller { set_readiness: stop_set_readiness, }, addr, )); } else if t == STOP_TOKEN { return Err(cancelled_error()); } } Err(io::Error::from(io::ErrorKind::WouldBlock)) } else { let timeout = self.options.read().unwrap().timeout; loop { self.poll.poll(&mut events, timeout)?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { let (stream, addr) = self.listener.accept()?; let poll = Poll::new()?; let stop_token = Token(0); let (stop_registration, stop_set_readiness) = Registration::new2(); poll.register( &stop_registration, stop_token, Ready::readable(), PollOpt::edge(), )?; let stream_token = Token(1); poll.register( &stream, stream_token, Ready::readable() | Ready::writable(), PollOpt::level(), )?; let events = Events::with_capacity(4); return Ok(( TcpStream { stream, poll, _stop_registration: stop_registration, events, options: Arc::new(RwLock::new(TcpStreamOptions { read_timeout: None, write_timeout: None, nonblocking: false, })), }, Canceller { set_readiness: stop_set_readiness, }, addr, )); } else if t == STOP_TOKEN { return Err(cancelled_error()); } } if timeout.is_some() { return Err(io::Error::from(io::ErrorKind::TimedOut)); } } } } /// Returns an iterator over the connections being received by this listener. /// /// The iteration can be cancelled by the associated [Canceller](struct.Canceller.html) /// object. If the iteration is cancelled, the next() method will return an /// error that can be identified with [is_cancelled](fn.is_cancelled.html). pub fn incoming(&self) -> Incoming { Incoming { listener: self } } /// Sets the value for the `IP_TTL` option on this socket. pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.listener.set_ttl(ttl) } /// Gets the value for the `IP_TTL` option for this socket. pub fn ttl(&self) -> io::Result<u32> { self.listener.ttl() } /// Gets the value for the `SO_ERROR` option for this socket. pub fn take_error(&self) -> io::Result<Option<io::Error>> { self.listener.take_error() } /// Moves this TCP connection into or out of non blocking mode. pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { self.options.write().unwrap().nonblocking = nonblocking; Ok(()) } } impl Debug for TcpListener { fn fmt(&self, f: &mut Formatter) -> fmt::Result { self.listener.fmt(f) } } impl<'a> Iterator for Incoming<'a> { type Item = io::Result<(TcpStream, Canceller, SocketAddr)>; fn next(&mut self) -> Option<Self::Item> { Some(self.listener.accept()) } } impl UdpSocket { fn simple_bind(address: &SocketAddr) -> io::Result<(Self, Canceller)> { let poll = Poll::new()?; let (stop_registration, stop_set_readiness) = Registration::new2(); poll.register( &stop_registration, STOP_TOKEN, Ready::readable(), PollOpt::edge(), )?; let socket = mio::net::UdpSocket::bind(address)?; poll.register( &socket, OBJECT_TOKEN, Ready::readable() | Ready::writable(), PollOpt::level(), )?; let events = Events::with_capacity(4); Ok(( UdpSocket { socket, poll, _stop_registration: stop_registration, events: RefCell::new(events), options: Arc::new(RwLock::new(UdpSocketOptions { read_timeout: None, write_timeout: None, nonblocking: false, })), }, Canceller { set_readiness: stop_set_readiness, }, )) } /// Creates an UDP socket from the given address, together with an /// object that can be used to cancel send/recv operations. pub fn bind<A: ToSocketAddrs>(address: A) -> io::Result<(Self, Canceller)> { let mut error = io::Error::from(io::ErrorKind::InvalidInput); for a in address.to_socket_addrs()? { match Self::simple_bind(&a) { Ok(r) => return Ok(r), Err(e) => error = e, } } Err(error) } /// Receives a single datagram message from the socket. /// /// This method can be cancelled by the associated [Canceller](struct.Canceller.html) /// object. pub fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> { self.poll.reregister( &self.socket, OBJECT_TOKEN, Ready::readable(), PollOpt::level(), )?; let mut events = self.events.borrow_mut(); if self.options.read().unwrap().nonblocking { self.poll .poll(&mut events, Some(Duration::from_millis(0)))?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_readable() { return self.socket.recv_from(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } Err(io::Error::from(io::ErrorKind::WouldBlock)) } else { let read_timeout = self.options.read().unwrap().read_timeout; loop { self.poll.poll(&mut events, read_timeout)?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_readable() { return self.socket.recv_from(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } if read_timeout.is_some() { return Err(io::Error::from(io::ErrorKind::TimedOut)); } } } } /// Sends a single datagram message to the given address. /// /// This method can be cancelled by the associated [Canceller](struct.Canceller.html) /// object. pub fn send_to(&self, buf: &[u8], addr: &SocketAddr) -> io::Result<usize> { self.poll.reregister( &self.socket, OBJECT_TOKEN, Ready::writable(), PollOpt::level(), )?; let mut events = self.events.borrow_mut(); if self.options.read().unwrap().nonblocking { self.poll .poll(&mut events, Some(Duration::from_millis(0)))?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_writable() { return self.socket.send_to(buf, addr); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } Err(io::Error::from(io::ErrorKind::WouldBlock)) } else { let write_timeout = self.options.read().unwrap().write_timeout; loop { self.poll.poll(&mut events, write_timeout)?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_writable() { return self.socket.send_to(buf, addr); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } if write_timeout.is_some() { return Err(io::Error::from(io::ErrorKind::TimedOut)); } } } } /// Gets the socket address that this object was created from. pub fn local_addr(&self) -> io::Result<SocketAddr> { self.socket.local_addr() } /// Creates a new independently owned handle to the underlying socket. pub fn try_clone(&self) -> io::Result<(Self, Canceller)> { let poll = Poll::new()?; let (stop_registration, stop_set_readiness) = Registration::new2(); poll.register( &stop_registration, STOP_TOKEN, Ready::readable(), PollOpt::edge(), )?; let socket = self.socket.try_clone()?; poll.register( &socket, OBJECT_TOKEN, Ready::readable() | Ready::writable(), PollOpt::level(), )?; let events = Events::with_capacity(4); Ok(( UdpSocket { socket, poll, _stop_registration: stop_registration, events: RefCell::new(events), options: self.options.clone(), }, Canceller { set_readiness: stop_set_readiness, }, )) } /// Sets the read timeout to the timeout specified. pub fn set_read_timeout(&self, duration: Option<Duration>) -> io::Result<()> { self.options.write().unwrap().read_timeout = duration; Ok(()) } /// Sets the write timeout to the timeout specified. pub fn set_write_timeout(&self, duration: Option<Duration>) -> io::Result<()> { self.options.write().unwrap().write_timeout = duration; Ok(()) } /// Returns the read timeout of this socket. pub fn read_timeout(&self) -> io::Result<Option<Duration>> { Ok(self.options.read().unwrap().read_timeout) } /// Returns the write timeout of this socket. pub fn write_timeout(&self) -> io::Result<Option<Duration>> { Ok(self.options.read().unwrap().write_timeout) } /// Sets the value of the `SO_BROADCAST` option for this socket. pub fn set_broadcast(&self, broadcast: bool) -> io::Result<()> { self.socket.set_broadcast(broadcast) } /// Gets the value of the `SO_BROADCAST` option for this socket. pub fn broadcast(&self) -> io::Result<bool> { self.socket.broadcast() } /// Sets the value of the `IP_MULTICAST_LOOP` option for this socket. pub fn set_multicast_loop_v4(&self, multicast_loop: bool) -> io::Result<()> { self.socket.set_multicast_loop_v4(multicast_loop) } /// Gets the value of the `IP_MULTICAST_LOOP` option for this socket. pub fn multicast_loop_v4(&self) -> io::Result<bool> { self.socket.multicast_loop_v4() } /// Sets the value of the `IP_MULTICAST_TTL` option for this socket. pub fn set_multicast_ttl_v4(&self, multicast_ttl: u32) -> io::Result<()> { self.socket.set_multicast_ttl_v4(multicast_ttl) } /// Gets the value of the `IP_MULTICAST_TTL` option for this socket. pub fn multicast_ttl_v4(&self) -> io::Result<u32> { self.socket.multicast_ttl_v4() } /// Sets the value of the `IPV6_MULTICAST_LOOP` option for this socket. pub fn set_multicast_loop_v6(&self, multicast_loop: bool) -> io::Result<()> { self.socket.set_multicast_loop_v6(multicast_loop) } /// Gets the value of the `IPV6_MULTICAST_LOOP` option for this socket. pub fn multicast_loop_v6(&self) -> io::Result<bool> { self.socket.multicast_loop_v6() } /// Sets the value for the `IP_TTL` option on this socket. pub fn set_ttl(&self, ttl: u32) -> io::Result<()> { self.socket.set_ttl(ttl) } /// Gets the value for the `IP_TTL` option for this socket. pub fn ttl(&self) -> io::Result<u32> { self.socket.ttl() } /// Executes an operation of the `IP_ADD_MEMBERSHIP` type. pub fn join_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { self.socket.join_multicast_v4(multiaddr, interface) } /// Executes an operation of the `IPV6_ADD_MEMBERSHIP` type. pub fn join_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { self.socket.join_multicast_v6(multiaddr, interface) } /// Executes an operation of the `IP_DROP_MEMBERSHIP` type. pub fn leave_multicast_v4(&self, multiaddr: &Ipv4Addr, interface: &Ipv4Addr) -> io::Result<()> { self.socket.leave_multicast_v4(multiaddr, interface) } /// Executes an operation of the `IPV6_DROP_MEMBERSHIP` type. pub fn leave_multicast_v6(&self, multiaddr: &Ipv6Addr, interface: u32) -> io::Result<()> { self.socket.leave_multicast_v6(multiaddr, interface) } /// Gets the value of the `SO_ERROR` option for this socket. pub fn take_error(&self) -> io::Result<Option<io::Error>> { self.socket.take_error() } /// Sets the value for the `IPV6_V6ONLY` option on this socket. pub fn set_only_v6(&self, only_v6: bool) -> io::Result<()> { self.socket.set_only_v6(only_v6) } /// Gets the value for the `IPV6_V6ONLY` option for this socket. pub fn only_v6(&self) -> io::Result<bool> { self.socket.only_v6() } fn simple_connect(&self, address: SocketAddr) -> io::Result<()> { self.socket.connect(address) } /// Connects this socket to a remote address. pub fn connect<A: ToSocketAddrs>(&self, address: A) -> io::Result<()> { let mut error = io::Error::from(io::ErrorKind::InvalidInput); for a in address.to_socket_addrs()? { match self.simple_connect(a) { Ok(r) => return Ok(r), Err(e) => error = e, } } Err(error) } /// Moves this socket into or out of non blocking mode. pub fn set_nonblocking(&self, nonblocking: bool) -> io::Result<()> { self.options.write().unwrap().nonblocking = nonblocking; Ok(()) } /// Receives a single datagram from the connected remote address. /// /// This method can be cancelled by the associated [Canceller](struct.Canceller.html) /// object. pub fn recv(&self, buf: &mut [u8]) -> io::Result<usize> { self.poll.reregister( &self.socket, OBJECT_TOKEN, Ready::readable(), PollOpt::level(), )?; let mut events = self.events.borrow_mut(); if self.options.read().unwrap().nonblocking { self.poll .poll(&mut events, Some(Duration::from_millis(0)))?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_readable() { return self.socket.recv(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } Err(io::Error::from(io::ErrorKind::WouldBlock)) } else { let read_timeout = self.options.read().unwrap().read_timeout; loop { self.poll.poll(&mut events, read_timeout)?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_readable() { return self.socket.recv(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } if read_timeout.is_some() { return Err(io::Error::from(io::ErrorKind::TimedOut)); } } } } /// Sends a single datagram to the connected remote address. /// /// This method can be cancelled by the associated [Canceller](struct.Canceller.html) /// object. pub fn send(&self, buf: &[u8]) -> io::Result<usize> { self.poll.reregister( &self.socket, OBJECT_TOKEN, Ready::writable(), PollOpt::level(), )?; let mut events = self.events.borrow_mut(); if self.options.read().unwrap().nonblocking { self.poll .poll(&mut events, Some(Duration::from_millis(0)))?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_writable() { return self.socket.send(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } Err(io::Error::from(io::ErrorKind::WouldBlock)) } else { let write_timeout = self.options.read().unwrap().write_timeout; loop { self.poll.poll(&mut events, write_timeout)?; for event in events.iter() { let t = event.token(); if t == OBJECT_TOKEN { if event.readiness().is_writable() { return self.socket.send(buf); } } else if t == STOP_TOKEN { return Err(cancelled_error()); } } if write_timeout.is_some() { return Err(io::Error::from(io::ErrorKind::TimedOut)); } } } } } impl Debug for UdpSocket { fn fmt(&self, f: &mut Formatter) -> fmt::Result { self.socket.fmt(f) } } #[cfg(test)] mod tests { use super::*; use std::sync::{Arc, Barrier}; use std::thread; #[test] fn test_is_cancelled() { assert_eq!( is_cancelled(&io::Error::new(io::ErrorKind::Interrupted, "")), false ); assert_eq!( is_cancelled(&io::Error::new(io::ErrorKind::Other, "")), false ); assert_eq!(is_cancelled(&cancelled_error()), true); } #[test] fn test_simple_connection() { let (listener, listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let handle = thread::spawn(move || { for r in listener.incoming() { match r { Ok((mut stream, _canceller, _addr)) => { thread::spawn(move || { let mut buf = [0; 3]; stream.read_exact(&mut buf).unwrap(); assert_eq!(&buf, b"foo"); stream.write_all(b"bar").unwrap(); }); } Err(ref e) if is_cancelled(e) => break, Err(ref e) => panic!("{:?}", e), } } }); for _ in 0..3 { let (mut stream, _stream_canceller) = TcpStream::connect(&addr).unwrap(); stream.write_all(b"foo").unwrap(); stream.flush().unwrap(); let mut buf = Vec::new(); assert_eq!(stream.read_to_end(&mut buf).unwrap(), 3); assert_eq!(&buf[..], b"bar"); } listener_canceller.cancel().unwrap(); handle.join().unwrap(); } #[test] fn test_cancel_stream() { let (listener, _listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let server = thread::spawn(move || { let (mut stream, _canceller, _addr) = listener.accept().unwrap(); let mut buf = [0; 16]; assert_eq!(stream.read(&mut buf).unwrap(), 0); }); let (mut stream, stream_canceller) = TcpStream::connect(&addr).unwrap(); let client = thread::spawn(move || { let mut buf = [0; 16]; assert!(is_cancelled(&stream.read(&mut buf).unwrap_err())); }); thread::sleep(Duration::from_secs(1)); stream_canceller.cancel().unwrap(); client.join().unwrap(); server.join().unwrap(); } #[test] fn test_non_blocking() { let barrier = Arc::new(Barrier::new(3)); let barrier_server = barrier.clone(); let (listener, _listener_canceller) = TcpListener::bind("127.0.0.1:0").unwrap(); let addr = listener.local_addr().unwrap(); let server = thread::spawn(move || { let (mut stream, _canceller, _addr) = listener.accept().unwrap(); // Wait for the client to attempt reading when no data is there. barrier_server.wait(); stream.write(b"foo").unwrap(); // Wake up the client now that there is data. barrier_server.wait(); barrier_server.wait(); barrier_server.wait(); let mut buf = [0; 16]; assert_eq!(stream.read(&mut buf).unwrap(), 0); }); let barrier_client = barrier.clone(); let (mut stream, stream_canceller) = TcpStream::connect(&addr).unwrap(); stream.set_nonblocking(true).unwrap(); let client = thread::spawn(move || { let mut buf = [0; 3]; // Attempt reading while there is no data available. assert_eq!( stream.read(&mut buf).unwrap_err().kind(), io::ErrorKind::WouldBlock ); // Tell the server it can put some data now. barrier_client.wait(); // Wait until the server has put some data. barrier_client.wait(); // Some data is available now. stream.read_exact(&mut buf).unwrap(); assert_eq!(&buf, b"foo"); // Tell the main thread it can cancel the stream now. barrier_client.wait(); // Wait for the stream to be cancelled. barrier_client.wait(); // It is cancelled now. assert!(is_cancelled(&stream.read(&mut buf).unwrap_err())); }); // Wait until the client has attempted is first read. barrier.wait(); // Wait until the server has written some data. barrier.wait(); // Wait until the client has done is second read. barrier.wait(); stream_canceller.cancel().unwrap(); // Tell the client it can attempt reading again. barrier.wait(); client.join().unwrap(); server.join().unwrap(); } #[test] fn test_udp() { let barrier = Arc::new(Barrier::new(3)); let (socket1, canceller1) = UdpSocket::bind("127.0.0.1:0").unwrap(); let (socket2, canceller2) = UdpSocket::bind("127.0.0.1:0").unwrap(); let address1 = socket1.local_addr().unwrap(); let address2 = socket2.local_addr().unwrap(); let barrier1 = barrier.clone(); let barrier2 = barrier.clone(); let thread1 = thread::spawn(move || { let mut buf = [0; 16]; assert_eq!(socket1.recv_from(&mut buf).unwrap(), (3, address2)); assert_eq!(socket1.send_to(b"bar", &address2).unwrap(), 3); barrier1.wait(); assert!(is_cancelled(&socket1.recv_from(&mut buf).unwrap_err())); }); let thread2 = thread::spawn(move || { assert_eq!(socket2.send_to(b"foo", &address1).unwrap(), 3); let mut buf = [0; 16]; assert_eq!(socket2.recv_from(&mut buf).unwrap(), (3, address1)); barrier2.wait(); assert!(is_cancelled(&socket2.recv_from(&mut buf).unwrap_err())); }); barrier.wait(); canceller1.cancel().unwrap(); canceller2.cancel().unwrap(); thread1.join().unwrap(); thread2.join().unwrap(); } /* TcpListener is !Sync. #[test] fn test_sync() { let listener = Arc::new(TcpListener::bind("127.0.0.1:0").unwrap().0); let listener2 = listener.clone(); let t = thread::spawn(move|| { listener.accept().unwrap(); }); listener2.accept().unwrap(); t.join().unwrap(); }*/ }
use buffer::VkBufferSlice; use texture::VkTextureView; use crate::pipeline::VkShader; use crate::rt::VkAccelerationStructure; use crate::swapchain::VkBinarySemaphore; use crate::sync::VkTimelineSemaphore; use crate::texture::VkSampler; use crate::{ VkDevice, *, }; #[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)] pub enum VkBackend {} impl sourcerenderer_core::graphics::Backend for VkBackend { type Device = VkDevice; type Instance = VkInstance; type CommandBuffer = VkCommandBufferRecorder; type CommandBufferSubmission = VkCommandBufferSubmission; type Adapter = VkAdapter; type Surface = VkSurface; type Texture = VkTexture; type Buffer = VkBufferSlice; type Shader = VkShader; type GraphicsPipeline = VkPipeline; type ComputePipeline = VkPipeline; type RayTracingPipeline = VkPipeline; type Swapchain = VkSwapchain; type TextureView = VkTextureView; type Sampler = VkSampler; type Fence = VkTimelineSemaphore; type Queue = VkQueue; type QueryRange = VkQueryRange; type AccelerationStructure = VkAccelerationStructure; type WSIFence = VkBinarySemaphore; }
pub mod file_io { pub fn some_function() { println!("# some_function called"); } pub fn some_function2() { println!("# some_function2 called"); } use std::{fs::File, io, io::BufRead, path::Path}; pub 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()) } // notice println! is using hexadecimal escape strings to turn the code red pub fn read_lines_example() { println!( "{}", "// read_lines() example usage use leonhard_lib::file_io; let mut rows: Vec<String> = Vec::new(); if let Ok(lines) = file_io::read_lines('./data/day3.txt') { for line in lines { if let Ok(raw_line) = line { rows.push(raw_line.clone()); } } } " ); } }
#[derive(Debug)] pub struct Todo { id: usize, title: String, is_done: bool, } impl Todo { pub fn new(title: String) -> Todo { Todo { id: 0, title, is_done: false, } } }
use std::{borrow::Cow, convert::Infallible, future::Future, str::FromStr}; use async_graphql::{ futures_util::task::{Context, Poll}, http::{WebSocketProtocols, WsMessage, ALL_WEBSOCKET_PROTOCOLS}, Data, Executor, Result, }; use axum::{ body::{boxed, BoxBody, HttpBody}, extract::{ ws::{CloseFrame, Message}, FromRequestParts, WebSocketUpgrade, }, http::{self, request::Parts, Request, Response, StatusCode}, response::IntoResponse, Error, }; use futures_util::{ future, future::{BoxFuture, Ready}, stream::{SplitSink, SplitStream}, Sink, SinkExt, Stream, StreamExt, }; use tower_service::Service; /// A GraphQL protocol extractor. /// /// It extract GraphQL protocol from `SEC_WEBSOCKET_PROTOCOL` header. #[derive(Debug, Copy, Clone, PartialEq, Eq)] pub struct GraphQLProtocol(WebSocketProtocols); #[async_trait::async_trait] impl<S> FromRequestParts<S> for GraphQLProtocol where S: Send + Sync, { type Rejection = StatusCode; async fn from_request_parts(parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { parts .headers .get(http::header::SEC_WEBSOCKET_PROTOCOL) .and_then(|value| value.to_str().ok()) .and_then(|protocols| { protocols .split(',') .find_map(|p| WebSocketProtocols::from_str(p.trim()).ok()) }) .map(Self) .ok_or(StatusCode::BAD_REQUEST) } } /// A GraphQL subscription service. pub struct GraphQLSubscription<E> { executor: E, } impl<E> Clone for GraphQLSubscription<E> where E: Executor, { fn clone(&self) -> Self { Self { executor: self.executor.clone(), } } } impl<E> GraphQLSubscription<E> where E: Executor, { /// Create a GraphQL subscription service. pub fn new(executor: E) -> Self { Self { executor } } } impl<B, E> Service<Request<B>> for GraphQLSubscription<E> where B: HttpBody + Send + 'static, E: Executor, { type Response = Response<BoxBody>; type Error = Infallible; type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>; fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, req: Request<B>) -> Self::Future { let executor = self.executor.clone(); Box::pin(async move { let (mut parts, _body) = req.into_parts(); let protocol = match GraphQLProtocol::from_request_parts(&mut parts, &()).await { Ok(protocol) => protocol, Err(err) => return Ok(err.into_response().map(boxed)), }; let upgrade = match WebSocketUpgrade::from_request_parts(&mut parts, &()).await { Ok(protocol) => protocol, Err(err) => return Ok(err.into_response().map(boxed)), }; let executor = executor.clone(); let resp = upgrade .protocols(ALL_WEBSOCKET_PROTOCOLS) .on_upgrade(move |stream| { GraphQLWebSocket::new(stream, executor, protocol).serve() }); Ok(resp.into_response().map(boxed)) }) } } type DefaultOnConnInitType = fn(serde_json::Value) -> Ready<async_graphql::Result<Data>>; fn default_on_connection_init(_: serde_json::Value) -> Ready<async_graphql::Result<Data>> { futures_util::future::ready(Ok(Data::default())) } /// A Websocket connection for GraphQL subscription. pub struct GraphQLWebSocket<Sink, Stream, E, OnConnInit> { sink: Sink, stream: Stream, executor: E, data: Data, on_connection_init: OnConnInit, protocol: GraphQLProtocol, } impl<S, E> GraphQLWebSocket<SplitSink<S, Message>, SplitStream<S>, E, DefaultOnConnInitType> where S: Stream<Item = Result<Message, Error>> + Sink<Message>, E: Executor, { /// Create a [`GraphQLWebSocket`] object. pub fn new(stream: S, executor: E, protocol: GraphQLProtocol) -> Self { let (sink, stream) = stream.split(); GraphQLWebSocket::new_with_pair(sink, stream, executor, protocol) } } impl<Sink, Stream, E> GraphQLWebSocket<Sink, Stream, E, DefaultOnConnInitType> where Sink: futures_util::sink::Sink<Message>, Stream: futures_util::stream::Stream<Item = Result<Message, Error>>, E: Executor, { /// Create a [`GraphQLWebSocket`] object with sink and stream objects. pub fn new_with_pair( sink: Sink, stream: Stream, executor: E, protocol: GraphQLProtocol, ) -> Self { GraphQLWebSocket { sink, stream, executor, data: Data::default(), on_connection_init: default_on_connection_init, protocol, } } } impl<Sink, Stream, E, OnConnInit, OnConnInitFut> GraphQLWebSocket<Sink, Stream, E, OnConnInit> where Sink: futures_util::sink::Sink<Message>, Stream: futures_util::stream::Stream<Item = Result<Message, Error>>, E: Executor, OnConnInit: FnOnce(serde_json::Value) -> OnConnInitFut + Send + 'static, OnConnInitFut: Future<Output = async_graphql::Result<Data>> + Send + 'static, { /// Specify the initial subscription context data, usually you can get /// something from the incoming request to create it. #[must_use] pub fn with_data(self, data: Data) -> Self { Self { data, ..self } } /// Specify a callback function to be called when the connection is /// initialized. /// /// You can get something from the payload of [`GQL_CONNECTION_INIT` message](https://github.com/apollographql/subscriptions-transport-ws/blob/master/PROTOCOL.md#gql_connection_init) to create [`Data`]. /// The data returned by this callback function will be merged with the data /// specified by [`with_data`]. pub fn on_connection_init<OnConnInit2, Fut>( self, callback: OnConnInit2, ) -> GraphQLWebSocket<Sink, Stream, E, OnConnInit2> where OnConnInit2: FnOnce(serde_json::Value) -> Fut + Send + 'static, Fut: Future<Output = async_graphql::Result<Data>> + Send + 'static, { GraphQLWebSocket { sink: self.sink, stream: self.stream, executor: self.executor, data: self.data, on_connection_init: callback, protocol: self.protocol, } } /// Processing subscription requests. pub async fn serve(self) { let input = self .stream .take_while(|res| future::ready(res.is_ok())) .map(Result::unwrap) .filter_map(|msg| { if let Message::Text(_) | Message::Binary(_) = msg { future::ready(Some(msg)) } else { future::ready(None) } }) .map(Message::into_data); let stream = async_graphql::http::WebSocket::new(self.executor.clone(), input, self.protocol.0) .connection_data(self.data) .on_connection_init(self.on_connection_init) .map(|msg| match msg { WsMessage::Text(text) => Message::Text(text), WsMessage::Close(code, status) => Message::Close(Some(CloseFrame { code, reason: Cow::from(status), })), }); let sink = self.sink; futures_util::pin_mut!(stream, sink); while let Some(item) = stream.next().await { let _ = sink.send(item).await; } } }
extern crate rand; extern crate ansi_term; use ansi_term::{Style}; const PASSCODE_LEN: usize = 8; fn main() { let style = Style::new().bold(); for i in (0..1000000) { let mut password = gen_string(PASSCODE_LEN); password.insert(PASSCODE_LEN/2, '-'); println!("{}", style.paint( password)); } } fn gen_string(len: usize) -> String{ use rand::Rng; const CHARSET: &[u8] = b"ACDEFGHIJKLMNPQRSTUVWXYZ\ 23456789"; let mut rng = rand::thread_rng(); let password: String = (0..len) .map(|_| { let i = rng.gen_range(0, CHARSET.len()); char::from(unsafe { *CHARSET.get_unchecked(i) }) //(i is in the range of CHARSET) //char::from({ *CHARSET.get(i).unwrap() }) // safe but slower }).collect(); password }
pub struct PackageEntry { /// File name of this entry pub file_name: String, /// The name of the directory this file is in. /// '/' is always used as a directory separator in Valve's implementation. /// Directory names are also always lower cased in Valve's implementation. pub directory_name: String, /// The file extension /// If the file has no extension, this is an empty string pub type_name: String, /// The CRC32 checksum of this entry pub crc32: u32, /// the length in bytes pub len: u32, /// The offset in the package pub offset: u32, /// Which archive this entry is in pub archive_index: u16, /// The preloaded bytes pub small_data: Box<[u8]> } impl PackageEntry { pub fn total_len(&self) -> u32 { self.len + self.small_data.len() as u32 } pub fn full_file_name(&self) -> String { if self.type_name == " " { self.file_name.clone() } else { self.file_name.clone() + "." + &self.type_name } } pub fn full_path(&self) -> String { if self.directory_name == " " { return self.full_file_name(); } self.directory_name.clone() + &self.full_file_name() } } impl ToString for PackageEntry { fn to_string(&self) -> String { format!("{} crc={:x} metadatasz={} fnumber={}, ofs={:x} sz={}", self.full_path(), self.crc32, self.small_data.len(), self.archive_index, self.offset, self.len) } }
use std::ffi::OsStr; use std::io::{self, Error, ErrorKind, Result}; use std::iter::once; use std::os::windows::ffi::OsStrExt; use std::sync::mpsc::TryRecvError; use crate::config::{Program, PtyConfig}; use crate::event::{OnResize, WindowSize}; use crate::tty::windows::child::ChildExitWatcher; use crate::tty::{ChildEvent, EventedPty, EventedReadWrite}; mod child; mod conpty; use conpty::Conpty as Backend; use mio_anonymous_pipes::{EventedAnonRead as ReadPipe, EventedAnonWrite as WritePipe}; pub struct Pty { // XXX: Backend is required to be the first field, to ensure correct drop order. Dropping // `conout` before `backend` will cause a deadlock (with Conpty). backend: Backend, conout: ReadPipe, conin: WritePipe, read_token: mio::Token, write_token: mio::Token, child_event_token: mio::Token, child_watcher: ChildExitWatcher, } pub fn new(config: &PtyConfig, window_size: WindowSize, _window_id: u64) -> Result<Pty> { conpty::new(config, window_size) .ok_or_else(|| Error::new(ErrorKind::Other, "failed to spawn conpty")) } impl Pty { fn new( backend: impl Into<Backend>, conout: impl Into<ReadPipe>, conin: impl Into<WritePipe>, child_watcher: ChildExitWatcher, ) -> Self { Self { backend: backend.into(), conout: conout.into(), conin: conin.into(), read_token: 0.into(), write_token: 0.into(), child_event_token: 0.into(), child_watcher, } } } impl EventedReadWrite for Pty { type Reader = ReadPipe; type Writer = WritePipe; #[inline] fn register( &mut self, poll: &mio::Poll, token: &mut dyn Iterator<Item = mio::Token>, interest: mio::Ready, poll_opts: mio::PollOpt, ) -> io::Result<()> { self.read_token = token.next().unwrap(); self.write_token = token.next().unwrap(); if interest.is_readable() { poll.register(&self.conout, self.read_token, mio::Ready::readable(), poll_opts)? } else { poll.register(&self.conout, self.read_token, mio::Ready::empty(), poll_opts)? } if interest.is_writable() { poll.register(&self.conin, self.write_token, mio::Ready::writable(), poll_opts)? } else { poll.register(&self.conin, self.write_token, mio::Ready::empty(), poll_opts)? } self.child_event_token = token.next().unwrap(); poll.register( self.child_watcher.event_rx(), self.child_event_token, mio::Ready::readable(), poll_opts, )?; Ok(()) } #[inline] fn reregister( &mut self, poll: &mio::Poll, interest: mio::Ready, poll_opts: mio::PollOpt, ) -> io::Result<()> { if interest.is_readable() { poll.reregister(&self.conout, self.read_token, mio::Ready::readable(), poll_opts)?; } else { poll.reregister(&self.conout, self.read_token, mio::Ready::empty(), poll_opts)?; } if interest.is_writable() { poll.reregister(&self.conin, self.write_token, mio::Ready::writable(), poll_opts)?; } else { poll.reregister(&self.conin, self.write_token, mio::Ready::empty(), poll_opts)?; } poll.reregister( self.child_watcher.event_rx(), self.child_event_token, mio::Ready::readable(), poll_opts, )?; Ok(()) } #[inline] fn deregister(&mut self, poll: &mio::Poll) -> io::Result<()> { poll.deregister(&self.conout)?; poll.deregister(&self.conin)?; poll.deregister(self.child_watcher.event_rx())?; Ok(()) } #[inline] fn reader(&mut self) -> &mut Self::Reader { &mut self.conout } #[inline] fn read_token(&self) -> mio::Token { self.read_token } #[inline] fn writer(&mut self) -> &mut Self::Writer { &mut self.conin } #[inline] fn write_token(&self) -> mio::Token { self.write_token } } impl EventedPty for Pty { fn child_event_token(&self) -> mio::Token { self.child_event_token } fn next_child_event(&mut self) -> Option<ChildEvent> { match self.child_watcher.event_rx().try_recv() { Ok(ev) => Some(ev), Err(TryRecvError::Empty) => None, Err(TryRecvError::Disconnected) => Some(ChildEvent::Exited), } } } impl OnResize for Pty { fn on_resize(&mut self, window_size: WindowSize) { self.backend.on_resize(window_size) } } fn cmdline(config: &PtyConfig) -> String { let default_shell = Program::Just("powershell".to_owned()); let shell = config.shell.as_ref().unwrap_or(&default_shell); once(shell.program()) .chain(shell.args().iter().map(|a| a.as_ref())) .collect::<Vec<_>>() .join(" ") } /// Converts the string slice into a Windows-standard representation for "W"- /// suffixed function variants, which accept UTF-16 encoded string values. pub fn win32_string<S: AsRef<OsStr> + ?Sized>(value: &S) -> Vec<u16> { OsStr::new(value).encode_wide().chain(once(0)).collect() }