text
stringlengths
8
4.13M
use std::str::FromStr; use toml_datetime::*; use crate::array_of_tables::ArrayOfTables; use crate::table::TableLike; use crate::{Array, InlineTable, Table, Value}; /// Type representing either a value, a table, an array of tables, or none. #[derive(Debug)] pub enum Item { /// Type representing none. None, /// Type representing value. Value(Value), /// Type representing table. Table(Table), /// Type representing array of tables. ArrayOfTables(ArrayOfTables), } impl Item { /// Sets `self` to the given item iff `self` is none and /// returns a mutable reference to `self`. pub fn or_insert(&mut self, item: Item) -> &mut Item { if self.is_none() { *self = item } self } } // TODO: This should be generated by macro or derive /// Downcasting impl Item { /// Text description of value type pub fn type_name(&self) -> &'static str { match self { Item::None => "none", Item::Value(v) => v.type_name(), Item::Table(..) => "table", Item::ArrayOfTables(..) => "array of tables", } } /// Index into a TOML array or map. A string index can be used to access a /// value in a map, and a usize index can be used to access an element of an /// array. /// /// Returns `None` if: /// - The type of `self` does not match the type of the /// index, for example if the index is a string and `self` is an array or a /// number. /// - The given key does not exist in the map /// or the given index is not within the bounds of the array. pub fn get<I: crate::index::Index>(&self, index: I) -> Option<&Item> { index.index(self) } /// Mutably index into a TOML array or map. A string index can be used to /// access a value in a map, and a usize index can be used to access an /// element of an array. /// /// Returns `None` if: /// - The type of `self` does not match the type of the /// index, for example if the index is a string and `self` is an array or a /// number. /// - The given key does not exist in the map /// or the given index is not within the bounds of the array. pub fn get_mut<I: crate::index::Index>(&mut self, index: I) -> Option<&mut Item> { index.index_mut(self) } /// Casts `self` to value. pub fn as_value(&self) -> Option<&Value> { match *self { Item::Value(ref v) => Some(v), _ => None, } } /// Casts `self` to table. pub fn as_table(&self) -> Option<&Table> { match *self { Item::Table(ref t) => Some(t), _ => None, } } /// Casts `self` to array of tables. pub fn as_array_of_tables(&self) -> Option<&ArrayOfTables> { match *self { Item::ArrayOfTables(ref a) => Some(a), _ => None, } } /// Casts `self` to mutable value. pub fn as_value_mut(&mut self) -> Option<&mut Value> { match *self { Item::Value(ref mut v) => Some(v), _ => None, } } /// Casts `self` to mutable table. pub fn as_table_mut(&mut self) -> Option<&mut Table> { match *self { Item::Table(ref mut t) => Some(t), _ => None, } } /// Casts `self` to mutable array of tables. pub fn as_array_of_tables_mut(&mut self) -> Option<&mut ArrayOfTables> { match *self { Item::ArrayOfTables(ref mut a) => Some(a), _ => None, } } /// Casts `self` to value. pub fn into_value(self) -> Result<Value, Self> { match self { Item::None => Err(self), Item::Value(v) => Ok(v), Item::Table(v) => { let v = v.into_inline_table(); Ok(Value::InlineTable(v)) } Item::ArrayOfTables(v) => { let v = v.into_array(); Ok(Value::Array(v)) } } } /// In-place convert to a value pub fn make_value(&mut self) { let other = std::mem::take(self); let other = other.into_value().map(Item::Value).unwrap_or(Item::None); *self = other; } /// Casts `self` to table. pub fn into_table(self) -> Result<Table, Self> { match self { Item::Table(t) => Ok(t), Item::Value(Value::InlineTable(t)) => Ok(t.into_table()), _ => Err(self), } } /// Casts `self` to array of tables. pub fn into_array_of_tables(self) -> Result<ArrayOfTables, Self> { match self { Item::ArrayOfTables(a) => Ok(a), Item::Value(Value::Array(a)) => { if a.is_empty() { Err(Item::Value(Value::Array(a))) } else if a.iter().all(|v| v.is_inline_table()) { let mut aot = ArrayOfTables::new(); aot.values = a.values; for value in aot.values.iter_mut() { value.make_item(); } Ok(aot) } else { Err(Item::Value(Value::Array(a))) } } _ => Err(self), } } // Starting private because the name is unclear pub(crate) fn make_item(&mut self) { let other = std::mem::take(self); let other = match other.into_table().map(crate::Item::Table) { Ok(i) => i, Err(i) => i, }; let other = match other.into_array_of_tables().map(crate::Item::ArrayOfTables) { Ok(i) => i, Err(i) => i, }; *self = other; } /// Returns true iff `self` is a value. pub fn is_value(&self) -> bool { self.as_value().is_some() } /// Returns true iff `self` is a table. pub fn is_table(&self) -> bool { self.as_table().is_some() } /// Returns true iff `self` is an array of tables. pub fn is_array_of_tables(&self) -> bool { self.as_array_of_tables().is_some() } /// Returns true iff `self` is `None`. pub fn is_none(&self) -> bool { matches!(*self, Item::None) } // Duplicate Value downcasting API /// Casts `self` to integer. pub fn as_integer(&self) -> Option<i64> { self.as_value().and_then(Value::as_integer) } /// Returns true iff `self` is an integer. pub fn is_integer(&self) -> bool { self.as_integer().is_some() } /// Casts `self` to float. pub fn as_float(&self) -> Option<f64> { self.as_value().and_then(Value::as_float) } /// Returns true iff `self` is a float. pub fn is_float(&self) -> bool { self.as_float().is_some() } /// Casts `self` to boolean. pub fn as_bool(&self) -> Option<bool> { self.as_value().and_then(Value::as_bool) } /// Returns true iff `self` is a boolean. pub fn is_bool(&self) -> bool { self.as_bool().is_some() } /// Casts `self` to str. pub fn as_str(&self) -> Option<&str> { self.as_value().and_then(Value::as_str) } /// Returns true iff `self` is a string. pub fn is_str(&self) -> bool { self.as_str().is_some() } /// Casts `self` to date-time. pub fn as_datetime(&self) -> Option<&Datetime> { self.as_value().and_then(Value::as_datetime) } /// Returns true iff `self` is a date-time. pub fn is_datetime(&self) -> bool { self.as_datetime().is_some() } /// Casts `self` to array. pub fn as_array(&self) -> Option<&Array> { self.as_value().and_then(Value::as_array) } /// Casts `self` to mutable array. pub fn as_array_mut(&mut self) -> Option<&mut Array> { self.as_value_mut().and_then(Value::as_array_mut) } /// Returns true iff `self` is an array. pub fn is_array(&self) -> bool { self.as_array().is_some() } /// Casts `self` to inline table. pub fn as_inline_table(&self) -> Option<&InlineTable> { self.as_value().and_then(Value::as_inline_table) } /// Casts `self` to mutable inline table. pub fn as_inline_table_mut(&mut self) -> Option<&mut InlineTable> { self.as_value_mut().and_then(Value::as_inline_table_mut) } /// Returns true iff `self` is an inline table. pub fn is_inline_table(&self) -> bool { self.as_inline_table().is_some() } /// Casts `self` to either a table or an inline table. pub fn as_table_like(&self) -> Option<&dyn TableLike> { self.as_table() .map(|t| t as &dyn TableLike) .or_else(|| self.as_inline_table().map(|t| t as &dyn TableLike)) } /// Casts `self` to either a table or an inline table. pub fn as_table_like_mut(&mut self) -> Option<&mut dyn TableLike> { match self { Item::Table(t) => Some(t as &mut dyn TableLike), Item::Value(Value::InlineTable(t)) => Some(t as &mut dyn TableLike), _ => None, } } /// Returns true iff `self` is either a table, or an inline table. pub fn is_table_like(&self) -> bool { self.as_table_like().is_some() } /// Returns the location within the original document pub(crate) fn span(&self) -> Option<std::ops::Range<usize>> { match self { Item::None => None, Item::Value(v) => v.span(), Item::Table(v) => v.span(), Item::ArrayOfTables(v) => v.span(), } } pub(crate) fn despan(&mut self, input: &str) { match self { Item::None => {} Item::Value(v) => v.despan(input), Item::Table(v) => v.despan(input), Item::ArrayOfTables(v) => v.despan(input), } } } impl Clone for Item { #[inline(never)] fn clone(&self) -> Self { match self { Item::None => Item::None, Item::Value(v) => Item::Value(v.clone()), Item::Table(v) => Item::Table(v.clone()), Item::ArrayOfTables(v) => Item::ArrayOfTables(v.clone()), } } } impl Default for Item { fn default() -> Self { Item::None } } impl FromStr for Item { type Err = crate::TomlError; /// Parses a value from a &str fn from_str(s: &str) -> Result<Self, Self::Err> { let value = s.parse::<Value>()?; Ok(Item::Value(value)) } } impl std::fmt::Display for Item { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { match &self { Item::None => Ok(()), Item::Value(v) => v.fmt(f), Item::Table(v) => v.fmt(f), Item::ArrayOfTables(v) => v.fmt(f), } } } /// Returns a formatted value. /// /// Since formatting is part of a `Value`, the right hand side of the /// assignment needs to be decorated with a space before the value. /// The `value` function does just that. /// /// # Examples /// ```rust /// # use snapbox::assert_eq; /// # use toml_edit::*; /// let mut table = Table::default(); /// let mut array = Array::default(); /// array.push("hello"); /// array.push("\\, world"); // \ is only allowed in a literal string /// table["key1"] = value("value1"); /// table["key2"] = value(42); /// table["key3"] = value(array); /// assert_eq(table.to_string(), /// r#"key1 = "value1" /// key2 = 42 /// key3 = ["hello", '\, world'] /// "#); /// ``` pub fn value<V: Into<Value>>(v: V) -> Item { Item::Value(v.into()) } /// Returns an empty table. pub fn table() -> Item { Item::Table(Table::new()) } /// Returns an empty array of tables. pub fn array() -> Item { Item::ArrayOfTables(ArrayOfTables::new()) }
/* Gordon Adam 1107425 This is the main program though as it is getting over complex the plan is to change it to the server program and also break it up */ #![feature(macro_rules)] use std::io::net::udp::UdpSocket; use std::io::net::ip::{Ipv4Addr, SocketAddr}; use std::collections::HashMap; use std::num::SignedInt; use std::io::Command; use std::string::String; use std::io::BufReader; use std::str; use std::os::args; use message::Message; mod server; mod header; mod question; mod data; mod resource; mod message; fn main() { print!("\x1b[2J\x1b[H"); if args().len() != 3 { println!("Error: 2 arguments need to be provided"); return; } let mut mess_arg: String = args()[1].clone(); let mut addr_arg: String = args()[2].clone(); println!("Rust DNS Resolver\n") let mut addr: Vec<u8> = vec![(0 as u8), (0 as u8), (0 as u8), (0 as u8)]; if addr_arg.as_slice() == "detect" { match detect_addr() { Some(a) => { println!("IP Address succesfully detected"); addr = a; }, None => { println!("Error: IP Address detection not supported"); println!("Listening on all interfaces"); } } } match mess_arg.as_slice() { "none" => { println!("No message details will be printed"); let mut s = server::Server::new(addr, 0); s.run(); } "details" => { println!("Detailed message information will be printed"); let mut s = server::Server::new(addr, 1); s.run(); }, "hostname" => { println!("Simplified details will be printed"); let mut s = server::Server::new(addr, 2); s.run(); } _ => { println!("Error: argument not recognised"); return; } } } pub fn detect_addr() -> Option<Vec<u8>> { let mut addr: Vec<u8> = vec![]; let output = match Command::new("ifconfig").arg("en0").output() { Ok(output) => output, Err(e) => panic!("failed to execute process: {}", e), }; if output.output.len() == 0 { return None; } let mut reader = BufReader::new(output.output.as_slice()); let mut found: bool = false; let mut line = reader.read_line().unwrap().into_bytes(); let mut buffer: Vec<u8> = vec![]; let mut i: uint = 0; while found == false { match reader.read_line() { Ok(l) => { line = l.into_bytes(); }, Err(e) => {return None;} } for j in range(1u, 6) { buffer.push(line[j]); } if String::from_utf8(buffer.clone()).unwrap() == String::from_str("inet ") { buffer = vec![]; let mut j: uint = 6; while line[j] != 0x0020 { if line[j] == 0x002e { j = j + 1; let mut num: u8 = from_str(str::from_utf8(buffer.as_slice()).unwrap()).unwrap(); addr.push(num); buffer = vec![]; continue; } buffer.push(line[j]); j = j + 1; } let mut num: u8 = from_str(str::from_utf8(buffer.as_slice()).unwrap()).unwrap(); addr.push(num); found = true; } buffer = vec![]; } return Some(addr); }
//! Returns a new document whose `origin` is the `origin` of the current global object's associated //! `Document`. //! //! ```elixir //! case Lumen.Web.Document.new() do //! {:ok, document} -> ... //! :error -> ... //! end //! ``` use liblumen_alloc::atom; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::Term; use crate::ok_tuple; #[native_implemented::function(Elixir.Lumen.Web.Document:new/0)] fn result(process: &Process) -> Term { match web_sys::Document::new() { Ok(document) => ok_tuple(process, document), // Not sure how this can happen Err(_) => atom!("error"), } }
pub mod board_groups; pub mod grouprc; pub mod group; pub mod stone;
extern crate piston_window; extern crate sprite; extern crate find_folder; extern crate ai_behavior; use piston_window::*; use sprite::*; use std::rc::Rc; use ai_behavior::{ Action, Sequence }; fn main() { let mut window: PistonWindow = WindowSettings::new("Hello Piston!", [640, 480]) .exit_on_esc(true) .vsync(true) .build().unwrap(); let assets = find_folder::Search::ParentsThenKids(3, 3) .for_folder("assets").unwrap(); let mut scene = Scene::new(); let robo_tex = Rc::new( Texture::from_path( &mut window.factory, assets.join("robo-main.png"), Flip::None, &TextureSettings::new() ).unwrap()); let side_tex = Rc::new( Texture::from_path( &mut window.factory, assets.join("robo-side.png"), Flip::None, &TextureSettings::new() ).unwrap()); let front_tex = Rc::new( Texture::from_path( &mut window.factory, assets.join("robo.png"), Flip::None, &TextureSettings::new() ).unwrap()); let mut robo = Sprite::from_texture(robo_tex); let mut side_robo = Sprite::from_texture(side_tex); let mut front_robo = Sprite::from_texture(front_tex); side_robo.set_visible(false); let side_robo_id = robo.add_child(side_robo); let front_robo_id = robo.add_child(front_robo); robo.set_position(360.0, 240.0); let id = scene.add_child(robo); while let Some(e) = window.next() { let mut robo_movement = Action(MoveBy(0.0, 0.0, 0.0)); let mut side_visibility = Action(MoveBy(0.0, 0.0, 0.0)); let mut front_visibility = Action(MoveBy(0.0, 0.0, 0.0)); match e { Input::Press(button) => { match button { Button::Keyboard(key) => { match key { Key::Up => { robo_movement = Action(MoveBy(0.1, 0.0, -15.0)); side_visibility = Action(Hide); front_visibility = Action(Show); } Key::Right => { robo_movement = Action(MoveBy(0.1, 15.0, 0.0)); side_visibility = Sequence(vec![ Action(Show), Action(FlipX(false))]); front_visibility = Action(Hide); } Key::Down => { robo_movement = Action(MoveBy(0.1, 0.0, 15.0)); side_visibility = Action(Hide); front_visibility = Action(Show); } Key::Left => { robo_movement = Action(MoveBy(0.1, -15.0, 0.0)); side_visibility = Sequence(vec![ Action(Show), Action(FlipX(true))]); front_visibility = Action(Hide); } Key::Space => { robo_movement = Action(ToggleVisibility); } _ => {} } } _ => {} } } Input::Render(_) => { window.draw_2d(&e, |c, g| { clear([1.0, 1.0, 1.0, 1.0], g); scene.draw(c.transform, g); }); } _ => {} } scene.event(&e); scene.run(id, &robo_movement); scene.run(front_robo_id, &front_visibility); scene.run(side_robo_id, &side_visibility); } }
use rule::Rule; #[test] fn literal() { let code = "y̆y̆y̆x̆"; let r: Rule<u64> = Rule::new(|_, l| { assert_eq!(l, "y̆y̆y̆x̆"); Ok(7777u64) }); r.literal("y̆y̆").literal("y̆").literal("x̆"); if let Ok(branches) = r.scan(&code) { assert_eq!(branches[0], 7777u64); } else { assert!(false); } } #[test] #[should_panic] fn empty_literal_should_panic() { let empty: Rule<i32> = Rule::default(); empty.literal(""); }
#![feature(plugin)] #![feature(proc_macro_hygiene, decl_macro)] mod http; mod udp; extern crate ctrlc; #[macro_use] extern crate rocket; extern crate rocket_contrib; extern crate serde_json; #[macro_use] extern crate serde_derive; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::Arc; use structopt::StructOpt; use http::start_http_endpoint; use udp::*; // Command line arguments struct #[derive(StructOpt, Debug)] pub struct Cli { #[structopt(short = "h", long = "httpPort")] pub port_http: Option<u16>, #[structopt(short = "u", long = "httpUDP")] pub port_udp: u32, } fn main() { // Parse command line arguments let args = Cli::from_args(); // Start Http Endpoint start_http_endpoint(&args.port_http); let mut endpoint = udp::UDP_Endpoint::new(args.port_udp); let (q_sender,msg_rec) = endpoint.start_Server(); let running = Arc::new(AtomicBool::new(true)); let r = running.clone(); ctrlc::set_handler(move || { r.store(false, Ordering::SeqCst); }).expect("Error setting Ctrl-C handler"); println!("Waiting for Ctrl-C..."); while running.load(Ordering::SeqCst) {} // To a graceful shutdown here }
use std::io; use std::mem; use std::os::windows::io::AsRawHandle; use std::str::Bytes; use windows_sys::Win32::Foundation::HANDLE; use windows_sys::Win32::System::Console::{ GetConsoleScreenBufferInfo, SetConsoleTextAttribute, CONSOLE_SCREEN_BUFFER_INFO, FOREGROUND_BLUE as FG_BLUE, FOREGROUND_GREEN as FG_GREEN, FOREGROUND_INTENSITY as FG_INTENSITY, FOREGROUND_RED as FG_RED, }; use crate::Term; type WORD = u16; const FG_CYAN: WORD = FG_BLUE | FG_GREEN; const FG_MAGENTA: WORD = FG_BLUE | FG_RED; const FG_YELLOW: WORD = FG_GREEN | FG_RED; const FG_WHITE: WORD = FG_BLUE | FG_GREEN | FG_RED; /// Query the given handle for information about the console's screen buffer. /// /// The given handle should represent a console. Otherwise, an error is /// returned. /// /// This corresponds to calling [`GetConsoleScreenBufferInfo`]. /// /// [`GetConsoleScreenBufferInfo`]: https://docs.microsoft.com/en-us/windows/console/getconsolescreenbufferinfo pub fn screen_buffer_info(h: HANDLE) -> io::Result<ScreenBufferInfo> { unsafe { let mut info: CONSOLE_SCREEN_BUFFER_INFO = mem::zeroed(); let rc = GetConsoleScreenBufferInfo(h, &mut info); if rc == 0 { return Err(io::Error::last_os_error()); } Ok(ScreenBufferInfo(info)) } } /// Set the text attributes of the console represented by the given handle. /// /// This corresponds to calling [`SetConsoleTextAttribute`]. /// /// [`SetConsoleTextAttribute`]: https://docs.microsoft.com/en-us/windows/console/setconsoletextattribute pub fn set_text_attributes(h: HANDLE, attributes: u16) -> io::Result<()> { if unsafe { SetConsoleTextAttribute(h, attributes) } == 0 { Err(io::Error::last_os_error()) } else { Ok(()) } } /// Represents console screen buffer information such as size, cursor position /// and styling attributes. /// /// This wraps a [`CONSOLE_SCREEN_BUFFER_INFO`]. /// /// [`CONSOLE_SCREEN_BUFFER_INFO`]: https://docs.microsoft.com/en-us/windows/console/console-screen-buffer-info-str #[derive(Clone)] pub struct ScreenBufferInfo(CONSOLE_SCREEN_BUFFER_INFO); impl ScreenBufferInfo { /// Returns the character attributes associated with this console. /// /// This corresponds to `wAttributes`. /// /// See [`char info`] for more details. /// /// [`char info`]: https://docs.microsoft.com/en-us/windows/console/char-info-str pub fn attributes(&self) -> u16 { self.0.wAttributes } } /// A Windows console. /// /// This represents a very limited set of functionality available to a Windows /// console. In particular, it can only change text attributes such as color /// and intensity. This may grow over time. If you need more routines, please /// file an issue and/or PR. /// /// There is no way to "write" to this console. Simply write to /// stdout or stderr instead, while interleaving instructions to the console /// to change text attributes. /// /// A common pitfall when using a console is to forget to flush writes to /// stdout before setting new text attributes. #[derive(Debug)] pub struct Console { kind: HandleKind, start_attr: TextAttributes, cur_attr: TextAttributes, } #[derive(Clone, Copy, Debug)] enum HandleKind { Stdout, Stderr, } impl HandleKind { fn handle(&self) -> HANDLE { match *self { HandleKind::Stdout => io::stdout().as_raw_handle() as HANDLE, HandleKind::Stderr => io::stderr().as_raw_handle() as HANDLE, } } } impl Console { /// Get a console for a standard I/O stream. fn create_for_stream(kind: HandleKind) -> io::Result<Console> { let h = kind.handle(); let info = screen_buffer_info(h)?; let attr = TextAttributes::from_word(info.attributes()); Ok(Console { kind: kind, start_attr: attr, cur_attr: attr, }) } /// Create a new Console to stdout. /// /// If there was a problem creating the console, then an error is returned. pub fn stdout() -> io::Result<Console> { Self::create_for_stream(HandleKind::Stdout) } /// Create a new Console to stderr. /// /// If there was a problem creating the console, then an error is returned. pub fn stderr() -> io::Result<Console> { Self::create_for_stream(HandleKind::Stderr) } /// Applies the current text attributes. fn set(&mut self) -> io::Result<()> { set_text_attributes(self.kind.handle(), self.cur_attr.to_word()) } /// Apply the given intensity and color attributes to the console /// foreground. /// /// If there was a problem setting attributes on the console, then an error /// is returned. pub fn fg(&mut self, intense: Intense, color: Color) -> io::Result<()> { self.cur_attr.fg_color = color; self.cur_attr.fg_intense = intense; self.set() } /// Apply the given intensity and color attributes to the console /// background. /// /// If there was a problem setting attributes on the console, then an error /// is returned. pub fn bg(&mut self, intense: Intense, color: Color) -> io::Result<()> { self.cur_attr.bg_color = color; self.cur_attr.bg_intense = intense; self.set() } /// Reset the console text attributes to their original settings. /// /// The original settings correspond to the text attributes on the console /// when this `Console` value was created. /// /// If there was a problem setting attributes on the console, then an error /// is returned. pub fn reset(&mut self) -> io::Result<()> { self.cur_attr = self.start_attr; self.set() } } /// A representation of text attributes for the Windows console. #[derive(Copy, Clone, Debug, Eq, PartialEq)] struct TextAttributes { fg_color: Color, fg_intense: Intense, bg_color: Color, bg_intense: Intense, } impl TextAttributes { fn to_word(&self) -> WORD { let mut w = 0; w |= self.fg_color.to_fg(); w |= self.fg_intense.to_fg(); w |= self.bg_color.to_bg(); w |= self.bg_intense.to_bg(); w } fn from_word(word: WORD) -> TextAttributes { TextAttributes { fg_color: Color::from_fg(word), fg_intense: Intense::from_fg(word), bg_color: Color::from_bg(word), bg_intense: Intense::from_bg(word), } } } /// Whether to use intense colors or not. #[allow(missing_docs)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Intense { Yes, No, } impl Intense { fn to_bg(&self) -> WORD { self.to_fg() << 4 } fn from_bg(word: WORD) -> Intense { Intense::from_fg(word >> 4) } fn to_fg(&self) -> WORD { match *self { Intense::No => 0, Intense::Yes => FG_INTENSITY, } } fn from_fg(word: WORD) -> Intense { if word & FG_INTENSITY > 0 { Intense::Yes } else { Intense::No } } } /// The set of available colors for use with a Windows console. #[allow(missing_docs)] #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Color { Black, Blue, Green, Red, Cyan, Magenta, Yellow, White, } impl Color { fn to_bg(&self) -> WORD { self.to_fg() << 4 } fn from_bg(word: WORD) -> Color { Color::from_fg(word >> 4) } fn to_fg(&self) -> WORD { match *self { Color::Black => 0, Color::Blue => FG_BLUE, Color::Green => FG_GREEN, Color::Red => FG_RED, Color::Cyan => FG_CYAN, Color::Magenta => FG_MAGENTA, Color::Yellow => FG_YELLOW, Color::White => FG_WHITE, } } fn from_fg(word: WORD) -> Color { match word & 0b111 { FG_BLUE => Color::Blue, FG_GREEN => Color::Green, FG_RED => Color::Red, FG_CYAN => Color::Cyan, FG_MAGENTA => Color::Magenta, FG_YELLOW => Color::Yellow, FG_WHITE => Color::White, _ => Color::Black, } } } pub fn console_colors(out: &Term, mut con: Console, bytes: &[u8]) -> io::Result<()> { use crate::ansi::AnsiCodeIterator; use std::str::from_utf8; let s = from_utf8(bytes).expect("data to be printed is not an ansi string"); let mut iter = AnsiCodeIterator::new(s); while !iter.rest_slice().is_empty() { if let Some((part, is_esc)) = iter.next() { if !is_esc { out.write_through_common(part.as_bytes())?; } else if part == "\x1b[0m" { con.reset()?; } else if let Some((intense, color, fg_bg)) = driver(parse_color, part) { match fg_bg { FgBg::Foreground => con.fg(intense, color), FgBg::Background => con.bg(intense, color), }?; } else if driver(parse_attr, part).is_none() { out.write_through_common(part.as_bytes())?; } } } Ok(()) } #[derive(Debug, PartialEq, Eq)] enum FgBg { Foreground, Background, } impl FgBg { fn new(byte: u8) -> Option<Self> { match byte { b'3' => Some(Self::Foreground), b'4' => Some(Self::Background), _ => None, } } } fn driver<Out>(parse: fn(Bytes<'_>) -> Option<Out>, part: &str) -> Option<Out> { let mut bytes = part.bytes(); loop { while bytes.next()? != b'\x1b' {} if let ret @ Some(_) = (parse)(bytes.clone()) { return ret; } } } // `driver(parse_color, s)` parses the equivalent of the regex // \x1b\[(3|4)8;5;(8|9|1[0-5])m // for intense or // \x1b\[(3|4)([0-7])m // for normal fn parse_color(mut bytes: Bytes<'_>) -> Option<(Intense, Color, FgBg)> { parse_prefix(&mut bytes)?; let fg_bg = FgBg::new(bytes.next()?)?; let (intense, color) = match bytes.next()? { b @ b'0'..=b'7' => (Intense::No, normal_color_ansi_from_byte(b)?), b'8' => { if &[bytes.next()?, bytes.next()?, bytes.next()?] != b";5;" { return None; } (Intense::Yes, parse_intense_color_ansi(&mut bytes)?) } _ => return None, }; parse_suffix(&mut bytes)?; Some((intense, color, fg_bg)) } // `driver(parse_attr, s)` parses the equivalent of the regex // \x1b\[([1-8])m fn parse_attr(mut bytes: Bytes<'_>) -> Option<u8> { parse_prefix(&mut bytes)?; let attr = match bytes.next()? { attr @ b'1'..=b'8' => attr, _ => return None, }; parse_suffix(&mut bytes)?; Some(attr) } fn parse_prefix(bytes: &mut Bytes<'_>) -> Option<()> { if bytes.next()? == b'[' { Some(()) } else { None } } fn parse_intense_color_ansi(bytes: &mut Bytes<'_>) -> Option<Color> { let color = match bytes.next()? { b'8' => Color::Black, b'9' => Color::Red, b'1' => match bytes.next()? { b'0' => Color::Green, b'1' => Color::Yellow, b'2' => Color::Blue, b'3' => Color::Magenta, b'4' => Color::Cyan, b'5' => Color::White, _ => return None, }, _ => return None, }; Some(color) } fn normal_color_ansi_from_byte(b: u8) -> Option<Color> { let color = match b { b'0' => Color::Black, b'1' => Color::Red, b'2' => Color::Green, b'3' => Color::Yellow, b'4' => Color::Blue, b'5' => Color::Magenta, b'6' => Color::Cyan, b'7' => Color::White, _ => return None, }; Some(color) } fn parse_suffix(bytes: &mut Bytes<'_>) -> Option<()> { if bytes.next()? == b'm' { Some(()) } else { None } } #[cfg(test)] mod tests { use super::*; #[test] fn color_parsing() { let intense_color = "leading bytes \x1b[38;5;10m trailing bytes"; let parsed = driver(parse_color, intense_color).unwrap(); assert_eq!(parsed, (Intense::Yes, Color::Green, FgBg::Foreground)); let normal_color = "leading bytes \x1b[40m trailing bytes"; let parsed = driver(parse_color, normal_color).unwrap(); assert_eq!(parsed, (Intense::No, Color::Black, FgBg::Background)); } #[test] fn attr_parsing() { let attr = "leading bytes \x1b[1m trailing bytes"; let parsed = driver(parse_attr, attr).unwrap(); assert_eq!(parsed, b'1'); } }
// Copyright (C) 2019 Sebastian Dröge <sebastian@centricular.com> // // Licensed under the MIT license, see the LICENSE file or <http://opensource.org/licenses/MIT> //! Crate for handling SDP ([RFC 4566](https://tools.ietf.org/html/rfc4566)) //! session descriptions, including a parser and serializer. //! //! ## Serializing an SDP //! //! ```rust,ignore //! // Create SDP session description //! let sdp = sdp_types::Session { //! ... //! }; //! //! // And write it to an `Vec<u8>` //! let mut output = Vec::new(); //! sdp.write(&mut output).unwrap(); //! ``` //! //! ## Parsing an SDP //! //! ```rust,no_run //! # let data = [0u8]; //! // Parse SDP session description from a byte slice //! let sdp = sdp_types::Session::parse(&data).unwrap(); //! //! // Access the 'tool' attribute //! match sdp.get_first_attribute_value("tool") { //! Ok(Some(tool)) => println!("tool: {}", tool), //! Ok(None) => println!("tool: empty"), //! Err(_) => println!("no tool attribute"), //! } //! ``` //! //! ## Limitations //! //! * SDP session descriptions are by default in UTF-8 but an optional `charset` //! attribute can change this for various SDP fields, including various other //! attributes. This is currently not supported, only UTF-8 is supported. //! //! * Network addresses, Phone numbers, E-Mail addresses and various other fields //! are currently parsed as a plain string and not according to the SDP //! grammar. use bstr::*; use fallible_iterator::FallibleIterator; mod parser; mod writer; pub use parser::ParserError; /// Originator of the session. /// /// See [RFC 4566 Section 5.2](https://tools.ietf.org/html/rfc4566#section-5.2) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Origin { /// User's login on the originating host. pub username: Option<String>, /// Session ID to make the whole `Origin` unique. /// /// Must be a numeric string but this is *not* checked. pub sess_id: String, /// Session version number. pub sess_version: u64, /// Type of network for this session. pub nettype: String, /// Type of the `unicast_address`. pub addrtype: String, /// Address where the session was created. pub unicast_address: String, } /// Connection data for the session or media. /// /// See [RFC 4566 Section 5.7](https://tools.ietf.org/html/rfc4566#section-5.7) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Connection { /// Type of network for this connection. pub nettype: String, /// Type of the `connection_address`. pub addrtype: String, /// Connection address. pub connection_address: String, } /// Bandwidth information for the session or media. /// /// See [RFC 4566 Section 5.8](https://tools.ietf.org/html/rfc4566#section-5.8) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Bandwidth { /// Bandwidth type, usually "CT" or "AS". pub bwtype: String, /// Bandwidth. pub bandwidth: u64, } /// Timing information of the session. /// /// See [RFC 4566 Section 5.9](https://tools.ietf.org/html/rfc4566#section-5.9) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Time { /// Start time of the session in seconds since 1900. pub start_time: u64, /// Stop time of the session in seconds since 1900. pub stop_time: u64, /// Repeat times. pub repeats: Vec<Repeat>, } /// Repeat times for timing information. /// /// See [RFC 4566 Section 5.10](https://tools.ietf.org/html/rfc4566#section-5.10) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Repeat { /// Repeat interval in seconds. pub repeat_interval: u64, /// Duration of one repeat. pub active_duration: u64, /// Offsets for the repeats from the `start_time`. pub offsets: Vec<u64>, } /// Time zone information for the session. /// /// See [RFC 4566 Section 5.11](https://tools.ietf.org/html/rfc4566#section-5.11) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct TimeZone { /// Time in seconds since 1900 when the adjustment happens. pub adjustment_time: u64, /// Amount of the adjustment in seconds. pub offset: i64, } /// Encryption key for the session or media. /// /// See [RFC 4566 Section 5.12](https://tools.ietf.org/html/rfc4566#section-5.12) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Key { /// Encryption method that is used. pub method: String, /// Encryption key or information to obtain the encryption key. pub encryption_key: Option<String>, } /// Attributes for the session or media. /// /// See [RFC 4566 Section 5.13](https://tools.ietf.org/html/rfc4566#section-5.13) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Attribute { /// Attribute name. pub attribute: String, /// Attribute value. pub value: Option<String>, } /// Media description. /// /// See [RFC 4566 Section 5.14](https://tools.ietf.org/html/rfc4566#section-5.14) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Media { /// Media type, e.g. "audio", "video", "text", "application" or "message". pub media: String, /// Transport port to which the media is sent. pub port: u16, /// Number of ports starting at `port` used for the media. pub num_ports: Option<u16>, /// Transport protocol. pub proto: String, /// Media format description. pub fmt: String, /// Media title. pub media_title: Option<String>, /// Connection data for the media. pub connections: Vec<Connection>, /// Bandwidth information for the media. pub bandwidths: Vec<Bandwidth>, /// Encryption key for the media. pub key: Option<Key>, /// Attributes of the media. pub attributes: Vec<Attribute>, } /// SDP session description. /// /// See [RFC 4566 Section 5](https://tools.ietf.org/html/rfc4566#section-5) for more details. #[derive(Debug, PartialEq, Eq, Clone)] pub struct Session { /// Originator of the session. pub origin: Origin, /// Name of the session. pub session_name: String, /// Session description. pub session_description: Option<String>, /// URI to additional information about the session. pub uri: Option<String>, /// E-Mail contacts for the session. pub emails: Vec<String>, /// Phone contacts for the session. pub phones: Vec<String>, /// Connection data for the session. pub connection: Option<Connection>, /// Bandwidth information for the session. pub bandwidths: Vec<Bandwidth>, /// Timing information for the session. pub times: Vec<Time>, /// Time zone information for the session. pub time_zones: Vec<TimeZone>, /// Encryption key for the session. pub key: Option<Key>, /// Attributes of the session. pub attributes: Vec<Attribute>, /// Media descriptions for this session. pub medias: Vec<Media>, } /// Error returned when an attribute is not found. #[derive(Debug, PartialEq, Eq)] pub struct AttributeNotFoundError; impl std::error::Error for AttributeNotFoundError {} impl std::fmt::Display for AttributeNotFoundError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { write!(f, "Attribute not found") } } impl Media { /// Checks if the given attribute exists. pub fn has_attribute(&self, name: &str) -> bool { self.attributes.iter().any(|a| a.attribute == name) } /// Gets the first value of the given attribute, if existing. pub fn get_first_attribute_value( &self, name: &str, ) -> Result<Option<&str>, AttributeNotFoundError> { self.attributes .iter() .find(|a| a.attribute == name) .ok_or(AttributeNotFoundError) .map(|a| a.value.as_deref()) } /// Gets an iterator over all attribute values of the given name, if existing. pub fn get_attribute_values<'a>( &'a self, name: &'a str, ) -> Result<impl Iterator<Item = Option<&'a str>> + 'a, AttributeNotFoundError> { let mut iter = self .attributes .iter() .filter(move |a| a.attribute == name) .map(|a| a.value.as_deref()) .peekable(); if iter.peek().is_some() { Ok(iter) } else { Err(AttributeNotFoundError) } } } impl Session { /// Checks if the given attribute exists. pub fn has_attribute(&self, name: &str) -> bool { self.attributes.iter().any(|a| a.attribute == name) } /// Gets the first value of the given attribute, if existing. pub fn get_first_attribute_value( &self, name: &str, ) -> Result<Option<&str>, AttributeNotFoundError> { self.attributes .iter() .find(|a| a.attribute == name) .ok_or(AttributeNotFoundError) .map(|a| a.value.as_deref()) } /// Gets an iterator over all attribute values of the given name, if existing. pub fn get_attribute_values<'a>( &'a self, name: &'a str, ) -> Result<impl Iterator<Item = Option<&'a str>> + 'a, AttributeNotFoundError> { let mut iter = self .attributes .iter() .filter(move |a| a.attribute == name) .map(|a| a.value.as_deref()) .peekable(); if iter.peek().is_some() { Ok(iter) } else { Err(AttributeNotFoundError) } } } #[cfg(test)] mod tests { use super::*; #[test] fn parse_write() { let sdp = "v=0\r o=jdoe 2890844526 2890842807 IN IP4 10.47.16.5\r s=SDP Seminar\r i=A Seminar on the session description protocol\r u=http://www.example.com/seminars/sdp.pdf\r e=j.doe@example.com (Jane Doe)\r p=+1 617 555-6011\r c=IN IP4 224.2.17.12/127\r b=AS:128\r t=2873397496 2873404696\r r=7d 1h 0 25h\r z=2882844526 -1h 2898848070 0\r k=clear:1234\r a=recvonly\r m=audio 49170 RTP/AVP 0\r m=video 51372/2 RTP/AVP 99\r a=rtpmap:99 h263-1998/90000\r a=fingerprint:sha-256 3A:96:6D:57:B2:C2:C7:61:A0:46:3E:1C:97:39:D3:F7:0A:88:A0:B1:EC:03:FB:10:A5:5D:3A:37:AB:DD:02:AA\r "; let parsed = Session::parse(sdp.as_bytes()).unwrap(); let mut written = vec![]; parsed.write(&mut written).unwrap(); assert_eq!(String::from_utf8_lossy(&written), sdp); } #[test] fn parse_media_attributes() { let media = Media { media: "video".into(), port: 51372, num_ports: Some(2), proto: "RTP/AVP".into(), fmt: "99 100".into(), media_title: None, connections: vec![], bandwidths: vec![], key: None, attributes: vec![ Attribute { attribute: "rtpmap".into(), value: Some("99 h263-1998/90000".into()), }, Attribute { attribute: "rtpmap".into(), value: Some("100 h264/90000".into()), }, Attribute { attribute: "rtcp".into(), value: None, }, ], }; assert!(media.has_attribute("rtpmap")); assert!(media.has_attribute("rtcp")); assert!(!media.has_attribute("foo")); assert_eq!( media.get_first_attribute_value("rtpmap"), Ok(Some("99 h263-1998/90000")) ); assert_eq!(media.get_first_attribute_value("rtcp"), Ok(None)); assert_eq!( media.get_first_attribute_value("foo"), Err(AttributeNotFoundError) ); assert_eq!( media .get_attribute_values("rtpmap") .unwrap() .collect::<Vec<_>>(), &[Some("99 h263-1998/90000"), Some("100 h264/90000")] ); assert_eq!( media .get_attribute_values("rtcp") .unwrap() .collect::<Vec<_>>(), &[None] ); assert!(media.get_attribute_values("foo").is_err()); } #[test] fn parse_session_attributes() { let session = Session { origin: Origin { username: Some("jdoe".into()), sess_id: "2890844526".into(), sess_version: 2890842807, nettype: "IN".into(), addrtype: "IP4".into(), unicast_address: "10.47.16.5".into(), }, session_name: "SDP Seminar".into(), session_description: None, uri: None, emails: vec![], phones: vec![], connection: None, bandwidths: vec![], times: vec![Time { start_time: 0, stop_time: 0, repeats: vec![], }], time_zones: vec![], key: None, attributes: vec![ Attribute { attribute: "rtpmap".into(), value: Some("99 h263-1998/90000".into()), }, Attribute { attribute: "rtpmap".into(), value: Some("100 h264/90000".into()), }, Attribute { attribute: "rtcp".into(), value: None, }, ], medias: vec![], }; assert!(session.has_attribute("rtpmap")); assert!(session.has_attribute("rtcp")); assert!(!session.has_attribute("foo")); assert_eq!( session.get_first_attribute_value("rtpmap"), Ok(Some("99 h263-1998/90000")) ); assert_eq!(session.get_first_attribute_value("rtcp"), Ok(None)); assert_eq!( session.get_first_attribute_value("foo"), Err(AttributeNotFoundError) ); assert_eq!( session .get_attribute_values("rtpmap") .unwrap() .collect::<Vec<_>>(), &[Some("99 h263-1998/90000"), Some("100 h264/90000")] ); assert_eq!( session .get_attribute_values("rtcp") .unwrap() .collect::<Vec<_>>(), &[None] ); assert!(session.get_attribute_values("foo").is_err()); } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - DES Key 3 LSW for 192-Bit Key"] pub key3_l: KEY3_L, #[doc = "0x04 - DES Key 3 MSW for 192-Bit Key"] pub key3_h: KEY3_H, #[doc = "0x08 - DES Key 2 LSW for 128-Bit Key"] pub key2_l: KEY2_L, #[doc = "0x0c - DES Key 2 MSW for 128-Bit Key"] pub key2_h: KEY2_H, #[doc = "0x10 - DES Key 1 LSW for 64-Bit Key"] pub key1_l: KEY1_L, #[doc = "0x14 - DES Key 1 MSW for 64-Bit Key"] pub key1_h: KEY1_H, #[doc = "0x18 - DES Initialization Vector"] pub iv_l: IV_L, #[doc = "0x1c - DES Initialization Vector"] pub iv_h: IV_H, #[doc = "0x20 - DES Control"] pub ctrl: CTRL, #[doc = "0x24 - DES Cryptographic Data Length"] pub length: LENGTH, #[doc = "0x28 - DES LSW Data RW"] pub data_l: DATA_L, #[doc = "0x2c - DES MSW Data RW"] pub data_h: DATA_H, #[doc = "0x30 - DES Revision Number"] pub revision: REVISION, #[doc = "0x34 - DES System Configuration"] pub sysconfig: SYSCONFIG, #[doc = "0x38 - DES System Status"] pub sysstatus: SYSSTATUS, #[doc = "0x3c - DES Interrupt Status"] pub irqstatus: IRQSTATUS, #[doc = "0x40 - DES Interrupt Enable"] pub irqenable: IRQENABLE, #[doc = "0x44 - DES Dirty Bits"] pub dirtybits: DIRTYBITS, } #[doc = "DES Key 3 LSW for 192-Bit Key"] pub struct KEY3_L { register: vcell::VolatileCell<u32>, } #[doc = "DES Key 3 LSW for 192-Bit Key"] pub mod key3_l; #[doc = "DES Key 3 MSW for 192-Bit Key"] pub struct KEY3_H { register: vcell::VolatileCell<u32>, } #[doc = "DES Key 3 MSW for 192-Bit Key"] pub mod key3_h; #[doc = "DES Key 2 LSW for 128-Bit Key"] pub struct KEY2_L { register: vcell::VolatileCell<u32>, } #[doc = "DES Key 2 LSW for 128-Bit Key"] pub mod key2_l; #[doc = "DES Key 2 MSW for 128-Bit Key"] pub struct KEY2_H { register: vcell::VolatileCell<u32>, } #[doc = "DES Key 2 MSW for 128-Bit Key"] pub mod key2_h; #[doc = "DES Key 1 LSW for 64-Bit Key"] pub struct KEY1_L { register: vcell::VolatileCell<u32>, } #[doc = "DES Key 1 LSW for 64-Bit Key"] pub mod key1_l; #[doc = "DES Key 1 MSW for 64-Bit Key"] pub struct KEY1_H { register: vcell::VolatileCell<u32>, } #[doc = "DES Key 1 MSW for 64-Bit Key"] pub mod key1_h; #[doc = "DES Initialization Vector"] pub struct IV_L { register: vcell::VolatileCell<u32>, } #[doc = "DES Initialization Vector"] pub mod iv_l; #[doc = "DES Initialization Vector"] pub struct IV_H { register: vcell::VolatileCell<u32>, } #[doc = "DES Initialization Vector"] pub mod iv_h; #[doc = "DES Control"] pub struct CTRL { register: vcell::VolatileCell<u32>, } #[doc = "DES Control"] pub mod ctrl; #[doc = "DES Cryptographic Data Length"] pub struct LENGTH { register: vcell::VolatileCell<u32>, } #[doc = "DES Cryptographic Data Length"] pub mod length; #[doc = "DES LSW Data RW"] pub struct DATA_L { register: vcell::VolatileCell<u32>, } #[doc = "DES LSW Data RW"] pub mod data_l; #[doc = "DES MSW Data RW"] pub struct DATA_H { register: vcell::VolatileCell<u32>, } #[doc = "DES MSW Data RW"] pub mod data_h; #[doc = "DES Revision Number"] pub struct REVISION { register: vcell::VolatileCell<u32>, } #[doc = "DES Revision Number"] pub mod revision; #[doc = "DES System Configuration"] pub struct SYSCONFIG { register: vcell::VolatileCell<u32>, } #[doc = "DES System Configuration"] pub mod sysconfig; #[doc = "DES System Status"] pub struct SYSSTATUS { register: vcell::VolatileCell<u32>, } #[doc = "DES System Status"] pub mod sysstatus; #[doc = "DES Interrupt Status"] pub struct IRQSTATUS { register: vcell::VolatileCell<u32>, } #[doc = "DES Interrupt Status"] pub mod irqstatus; #[doc = "DES Interrupt Enable"] pub struct IRQENABLE { register: vcell::VolatileCell<u32>, } #[doc = "DES Interrupt Enable"] pub mod irqenable; #[doc = "DES Dirty Bits"] pub struct DIRTYBITS { register: vcell::VolatileCell<u32>, } #[doc = "DES Dirty Bits"] pub mod dirtybits;
pub fn task1( text : &str ) -> i32 { tasks(text ).0 } pub fn task2( text : &str ) -> i32 { tasks(text ).1 } pub fn tasks( text : &str ) -> (i32,i32) { let mut level = 1; let mut total_score = 0; let mut total_garbage = 0; let mut prev_ch = ' '; let mut is_garbage = false; for ch in text.chars() { if prev_ch == '!' && ch == '!' { prev_ch = ' '; } else { if prev_ch != '!' { match ch { '{' => { if !is_garbage { total_score += level; level += 1; } else { total_garbage += 1; } }, '}' => { if !is_garbage { level -= 1; } else { total_garbage += 1; } }, '<' => { if is_garbage { total_garbage += 1; } else { is_garbage = true; } }, '>' => { is_garbage = false; }, '!' => {}, _ => { if is_garbage { total_garbage += 1; } } } } prev_ch = ch; } } (total_score, total_garbage) }
use crate::clock::clock::Clock; use std::sync::atomic::{AtomicI64, Ordering}; pub struct ArbitraryClock { pub now: AtomicI64, } impl Clock for ArbitraryClock { fn now(&self) -> i64 { self.now.load(Ordering::Relaxed) } } impl ArbitraryClock { pub fn new() -> ArbitraryClock { ArbitraryClock { now: AtomicI64::new(0), } } }
use std::{ fs::{create_dir_all, File}, io::prelude::Read, io::Error, io::Write, path::Path, }; use serde_json::{from_str, to_string}; use crate::credentials::{generate_mqtt_password, get_db_password_from_file}; use crate::APP_VERSION; const BASE_DIRECTORY: &str = "/etc/BlackBox/"; const SETTINGS_FILE_LOCATION: &str = "/etc/BlackBox/settings.json"; const VERSION_FILE_LOCATION: &str = "/etc/BlackBox/blackbox.version"; const SETTINGS_DEFAULT: &str = r#"{ "mosquitto_broker_config": { "mosquitto_conf_save_location": "/etc/mosquitto/mosquitto.conf", "db_ip": "127.0.0.1", "db_port": "5432", "db_username": "postgres", "db_password": "", "db_name": "postgres" }, "database_settings": { "db_ip": "127.0.0.1", "db_port": "5432", "db_username": "postgres", "db_password": "", "db_name": "postgres" }, "blackbox_mqtt_client": { "mqtt_ip": "127.0.0.1", "mqtt_port": "8883", "mqtt_password": "", "cafile": "/etc/mosquitto/ca.crt" }, "nodes": { "mqtt_unregistered_node_password": "unregistered" }, "external_interface_settings": { "mqtt_password": "" }, "neutron_communicators": [ { "mqtt_username": "", "mqtt_password": "" } ] }"#; #[derive(Debug, Serialize, Deserialize)] pub struct Settings { pub mosquitto_broker_config: SettingsMosquitto, pub database_settings: SettingsDatabase, pub blackbox_mqtt_client: SettingsMqttClient, pub nodes: SettingsNodes, pub external_interface_settings: SettingsWebInterface, pub neutron_communicators: Vec<NeutronCommunicator>, } #[derive(Debug, Serialize, Deserialize)] pub struct SettingsMosquitto { pub mosquitto_conf_save_location: String, pub db_ip: String, pub db_port: String, pub db_username: String, pub db_password: String, pub db_name: String, } #[derive(Debug, Serialize, Deserialize)] pub struct SettingsMqttClient { pub mqtt_ip: String, pub mqtt_port: String, pub mqtt_password: String, pub cafile: String, } #[derive(Debug, Serialize, Deserialize)] pub struct SettingsNodes { pub mqtt_unregistered_node_password: String, } #[derive(Debug, Serialize, Deserialize)] pub struct SettingsDatabase { pub db_ip: String, pub db_port: String, pub db_username: String, pub db_password: String, pub db_name: String, } #[derive(Debug, Serialize, Deserialize)] pub struct SettingsWebInterface { pub mqtt_password: String, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct NeutronCommunicator { pub mqtt_username: String, pub mqtt_password: String, } /** * Checks if the settings file exists. * If it exists, try to load and return it. * If it exists, but fails to load, log error message and exit. * If it doesn't exist return Err to main. */ pub fn init() -> Result<Settings, ()> { refresh_version_file(); if !Path::new(SETTINGS_FILE_LOCATION).exists() { error!("Settings file not found."); info!("Run 'sudo black_box commands' to get the command for generating a settings file."); Err(()) } else { match load_settings() { Ok(settings) => { info!("Settings loaded successfully."); Ok(settings) } Err(e) => { error!("Failed to load settings file. {}", e); Err(()) } } } } /** * Generates/rewrites a JSON file, containing the current version number, in the settings base directory. * This file is primarily used by Neutron Update Client. */ fn refresh_version_file() { debug!("Generating version file..."); //let v_file = format!("{{\"version\": \"{}\"}}", APP_VERSION); match create_dir_all(BASE_DIRECTORY) { Ok(_) => match File::create(VERSION_FILE_LOCATION) { Ok(mut file) => match file.write_all(APP_VERSION.as_bytes()) { Ok(_) => { debug!("Version file generated."); } Err(e) => error!( "Could not generate version file. Failed to write to file. {}", e ), }, Err(e) => error!( "Could not generate version file. Failed to create file. {}", e ), }, Err(e) => error!( "Could not generate version file. Failed to create folder. {}", e ), } } /** * Creates a settings file and saves the default settings in it. * Returns Settings object if successfull. */ pub fn write_default_settings() -> Result<(), Error> { info!("Generating default settings file..."); let mut file = File::create(SETTINGS_FILE_LOCATION)?; file.write_all(SETTINGS_DEFAULT.as_bytes())?; info!( "Default settings file generated. Only root can modify the file. Location: {}", SETTINGS_FILE_LOCATION ); Ok(()) } /** * Tries to load the settings file. * Returns Settings object if successfull. */ fn load_settings() -> Result<Settings, Error> { info!("Loading settings file: '{}'", SETTINGS_FILE_LOCATION); let mut contents = String::new(); let mut file = File::open(SETTINGS_FILE_LOCATION)?; file.read_to_string(&mut contents)?; let mut settings: Settings = from_str(&contents)?; // If the database password field is empty, try to load from file by calling <credentials> if settings.database_settings.db_password.is_empty() { match get_db_password_from_file() { Ok(pass) => { settings.database_settings.db_password = pass.to_owned(); if settings.mosquitto_broker_config.db_password.is_empty() { info!("Mosquitto broker database password found empty, setting to BlackBox database password."); settings.mosquitto_broker_config.db_password = pass; } } Err(_) => { error!("Database password not found, please contact the system owner."); return Err(Error::new(std::io::ErrorKind::InvalidData, "")); } } } if settings.blackbox_mqtt_client.mqtt_password.is_empty() { info!("BlackBox MQTT password not found. Generating and saving new password."); let password = generate_mqtt_password(); // Just in case we are going to startup, set the password in the struct settings.blackbox_mqtt_client.mqtt_password = password.to_string(); // Save to settings file match save_mqtt_password(&password) { Ok(_) => {} Err(e) => { error!("Could not save BlackBox mqtt password to file. {}", e); return Err(Error::new(std::io::ErrorKind::InvalidData, "")); } } } if settings.nodes.mqtt_unregistered_node_password.is_empty() { warn!("Unregistered node password field is empty. Using default password: 'unregistered'."); settings.nodes.mqtt_unregistered_node_password = "unregistered".to_string(); } if settings .external_interface_settings .mqtt_password .is_empty() { info!("External Interface is enabled but its password is not set. Generating and saving new password.."); let password = generate_mqtt_password(); settings.external_interface_settings.mqtt_password = password.to_string(); // Save to settings file match save_web_interface_password(&password) { Ok(_) => {} Err(e) => { error!("Could not save WebInterface mqtt password to file. {}", e); return Err(Error::new(std::io::ErrorKind::InvalidData, "")); } } } let mut neco_accounts = Vec::new(); for mut neco in settings.neutron_communicators.clone() { if !neco.mqtt_username.is_empty() && neco.mqtt_password.is_empty() { // Set the password in the settings struct neco.mqtt_password = generate_mqtt_password(); neco_accounts.push(neco); } } if !neco_accounts.is_empty() { // Set the neutron_communicators struct to the changed one settings.neutron_communicators = neco_accounts.clone(); // Save the new settings to file if let Err(e) = save_neutron_accounts(neco_accounts) { error!("Could not save Neutron Communicator mqtt accounts to settings. {}", e); return Err(Error::new(std::io::ErrorKind::Other, "")); } } Ok(settings) } /** * Saves mqtt password in the settings file for the BlackBox client. */ fn save_mqtt_password(password: &str) -> Result<(), Error> { let mut contents = String::new(); let mut file = File::open(SETTINGS_FILE_LOCATION)?; file.read_to_string(&mut contents)?; let mut settings: Settings = from_str(&contents)?; settings.blackbox_mqtt_client.mqtt_password = String::from(password); let mut file = File::create(SETTINGS_FILE_LOCATION)?; file.write_all(to_string(&settings)?.as_bytes())?; Ok(()) } /** * Saves External Interface mqtt password in the settings file for setting up mqtt access. */ fn save_web_interface_password(password: &str) -> Result<(), Error> { let mut contents = String::new(); let mut file = File::open(SETTINGS_FILE_LOCATION)?; file.read_to_string(&mut contents)?; let mut settings: Settings = from_str(&contents)?; settings.external_interface_settings.mqtt_password = String::from(password); let mut file = File::create(SETTINGS_FILE_LOCATION)?; file.write_all(to_string(&settings)?.as_bytes())?; Ok(()) } /** * Saves Neutron mqtt account data to the settings file. */ pub fn save_neutron_accounts(mut neutron_communicators: Vec<NeutronCommunicator>) -> Result<(), Error> { let mut contents = String::new(); let mut file = File::open(SETTINGS_FILE_LOCATION)?; file.read_to_string(&mut contents)?; let mut settings: Settings = from_str(&contents)?; settings.neutron_communicators.append(&mut neutron_communicators); let mut file = File::create(SETTINGS_FILE_LOCATION)?; file.write_all(to_string(&settings)?.as_bytes())?; Ok(()) }
extern crate rand; extern crate time; use std::f64::consts::PI; use rand::Rng; use time::precise_time_ns; use std::env; use std::fmt; #[derive(Copy, Clone, PartialEq)] struct Biquad { b0: f64, b1: f64, b2: f64, a1: f64, a2: f64, x1: f64, x2: f64, y1: f64, y2: f64, } impl fmt::Debug for Biquad { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { try!(writeln!(f, "Biquad coefficents:")); try!(writeln!(f, "b0={:+.13},", self.b0)); try!(writeln!(f, "b1={:+.13},", self.b1)); try!(writeln!(f, "b2={:+.13},", self.b2)); try!(writeln!(f, "a1={:+.13},", self.a1)); try!(write! (f, "a2={:+.13},", self.a2)); Ok(()) } } fn peak_eq_coefs(fs: f64, f0: f64, q: f64, db_gain: f64) -> Biquad { let a = 10.0_f64.powf(db_gain / 40.0); let omega = 2.0 * PI * f0 / fs; let alpha = omega.sin() / (2.0 * q); let a0 = 1.0 + alpha / a; let b0 = (1.0 + alpha * a) / a0; let b1 = (-2.0 * omega.cos()) / a0; let b2 = (1.0 - alpha * a) / a0; let a2 = (1.0 - alpha / a) / a0; Biquad { b0: b0, b1: b1, b2: b2, a1: b1, a2: a2, x1: 0.0, x2: 0.0, y1: 0.0, y2: 0.0, } } fn white_noise(length: usize) -> Vec<f64> { let mut rng = rand::thread_rng(); let mut vec: Vec<f64> = Vec::new(); vec.resize(length, 0.0); for i in 0..vec.len() { vec[i] = rng.gen::<f64>() } return vec; } fn white_noise_array() -> [f64; 4096] { let mut rng = rand::thread_rng(); let mut arr = [0.0; 4096]; for i in 0..arr.len() { arr[i] = rng.gen::<f64>() } return arr; } fn iir_vec(input: &Vec<f64>, output: &mut Vec<f64>, bq: &mut Biquad) { for i in 0..input.len() { output[i] = (bq.b0 * input[i]) + (bq.b1 * bq.x1) + (bq.b2 * bq.x2) - (bq.a1 * bq.y1) - (bq.a2 * bq.y2); bq.x2 = bq.x1; bq.x1 = input[i]; bq.y2 = bq.y1; bq.y1 = output[i]; } } fn iir_vec_zip(input: &Vec<f64>, output: &mut Vec<f64>, bq: &mut Biquad) { for (x, y) in input.iter().zip(output.iter_mut()) { *y = (bq.b0 * *x) + (bq.b1 * bq.x1) + (bq.b2 * bq.x2) - (bq.a1 * bq.y1) - (bq.a2 * bq.y2); bq.x2 = bq.x1; bq.x1 = *x; bq.y2 = bq.y1; bq.y1 = *y; } } fn iir_vec_zip_2(input: &Vec<f64>, output: &mut Vec<f64>, bq: &mut Biquad) { for (&x, y) in input.iter().zip(output.iter_mut()) { *y = (bq.b0 * x) + (bq.b1 * bq.x1) + (bq.b2 * bq.x2) - (bq.a1 * bq.y1) - (bq.a2 * bq.y2); bq.x2 = bq.x1; bq.x1 = x; bq.y2 = bq.y1; bq.y1 = *y; } } fn iir_vec_2(input: &Vec<f64>, output: &mut Vec<f64>, bq: &mut Biquad) { let len = input.len(); for i in 0..len { let inval = input[i]; let outval = (bq.b0 * inval) + (bq.b1 * bq.x1) + (bq.b2 * bq.x2) - (bq.a1 * bq.y1) - (bq.a2 * bq.y2); output[i] = outval; bq.x2 = bq.x1; bq.x1 = inval; bq.y2 = bq.y1; bq.y1 = outval; } } fn iir_array(input: &[f64; 4096], output: &mut [f64; 4096], bq: &mut Biquad) { for i in 0..input.len() { output[i] = (bq.b0 * input[i]) + (bq.b1 * bq.x1) + (bq.b2 * bq.x2) - (bq.a1 * bq.y1) - (bq.a2 * bq.y2); bq.x2 = bq.x1; bq.x1 = input[i]; bq.y2 = bq.y1; bq.y1 = output[i]; } } fn iir_slice(input: &[f64], output: &mut [f64], bq: &mut Biquad) { for i in 0..input.len() { output[i] = (bq.b0 * input[i]) + (bq.b1 * bq.x1) + (bq.b2 * bq.x2) - (bq.a1 * bq.y1) - (bq.a2 * bq.y2); bq.x2 = bq.x1; bq.x1 = input[i]; bq.y2 = bq.y1; bq.y1 = output[i]; } } fn iir_slice_unsafe(input: &[f64], output: &mut [f64], bq: &mut Biquad) { unsafe { for i in 0..input.len() { output[i] = (bq.b0 * *input.get_unchecked(i)) + (bq.b1 * bq.x1) + (bq.b2 * bq.x2) - (bq.a1 * bq.y1) - (bq.a2 * bq.y2); bq.x2 = bq.x1; bq.x1 = *input.get_unchecked(i); bq.y2 = bq.y1; bq.y1 = *output.get_unchecked(i); } } } fn main() { println!("DSP bench rust"); let buffer_length = env::args().nth(1).and_then(|arg| arg.parse::<usize>().ok()).unwrap_or(4096); let bench_loops = 200000; let mut bq = peak_eq_coefs(48000.0, 200.0, 2.0, 6.0); println!("{:?}", bq); let input = white_noise(buffer_length); let mut output: Vec<f64> = vec![0.0; input.len()]; { let start = precise_time_ns(); for _ in 0..bench_loops { iir_vec(&input, &mut output, &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_vec:\t\t\t{} ns per loop", elapsed / bench_loops); } { let start = precise_time_ns(); for _ in 0..bench_loops { iir_vec_zip(&input, &mut output, &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_vec_zip:\t\t\t{} ns per loop", elapsed / bench_loops); } { let start = precise_time_ns(); for _ in 0..bench_loops { iir_vec_zip_2(&input, &mut output, &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_vec_zip_2:\t\t\t{} ns per loop", elapsed / bench_loops); } { let start = precise_time_ns(); for _ in 0..bench_loops { iir_vec_2(&input, &mut output, &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_vec_2:\t\t\t{} ns per loop", elapsed / bench_loops); } { let input_array = white_noise_array(); let mut output_array = [0.0; 4096]; let start = precise_time_ns(); for _ in 0..bench_loops { iir_array(&input_array, &mut output_array, &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_array (4096):\t\t{} ns per loop", elapsed / bench_loops); } { let input_array = white_noise_array(); let mut output_array = [0.0; 4096]; let start = precise_time_ns(); for _ in 0..bench_loops { iir_slice(&input_array[0..buffer_length], &mut output_array[0..buffer_length], &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_slice (array):\t\t{} ns per loop", elapsed / bench_loops); } { let input_array = white_noise_array(); let mut output_array = [0.0; 4096]; let start = precise_time_ns(); for _ in 0..bench_loops { iir_slice(&input_array, &mut output_array, &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_slice (4096 array):\t\t{} ns per loop", elapsed / bench_loops); } { let input_array = white_noise_array(); let mut output_array = [0.0; 4096]; let start = precise_time_ns(); for _ in 0..bench_loops { iir_slice_unsafe(&input_array, &mut output_array, &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_slice_unsafe (4096 array):\t{} ns per loop", elapsed / bench_loops); } { let start = precise_time_ns(); for _ in 0..bench_loops { iir_slice(&input, &mut output, &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_slice (vec):\t\t{} ns per loop", elapsed / bench_loops); } { let start = precise_time_ns(); for _ in 0..bench_loops { iir_slice_unsafe(&input, &mut output, &mut bq); } let elapsed = precise_time_ns() - start; println!("iir_slice_unsafe (vec):\t\t{} ns per loop", elapsed / bench_loops); } }
#[doc = "Reader of register OBR"] pub type R = crate::R<u32, super::OBR>; #[doc = "Reader of field `OPTERR`"] pub type OPTERR_R = crate::R<bool, bool>; #[doc = "Reader of field `RDPRT`"] pub type RDPRT_R = crate::R<bool, bool>; #[doc = "Reader of field `WDG_SW`"] pub type WDG_SW_R = crate::R<bool, bool>; #[doc = "Reader of field `nRST_STOP`"] pub type NRST_STOP_R = crate::R<bool, bool>; #[doc = "Reader of field `nRST_STDBY`"] pub type NRST_STDBY_R = crate::R<bool, bool>; #[doc = "Reader of field `Data0`"] pub type DATA0_R = crate::R<u8, u8>; #[doc = "Reader of field `Data1`"] pub type DATA1_R = crate::R<u8, u8>; impl R { #[doc = "Bit 0 - Option byte error"] #[inline(always)] pub fn opterr(&self) -> OPTERR_R { OPTERR_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Read protection"] #[inline(always)] pub fn rdprt(&self) -> RDPRT_R { RDPRT_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 2 - WDG_SW"] #[inline(always)] pub fn wdg_sw(&self) -> WDG_SW_R { WDG_SW_R::new(((self.bits >> 2) & 0x01) != 0) } #[doc = "Bit 3 - nRST_STOP"] #[inline(always)] pub fn n_rst_stop(&self) -> NRST_STOP_R { NRST_STOP_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 4 - nRST_STDBY"] #[inline(always)] pub fn n_rst_stdby(&self) -> NRST_STDBY_R { NRST_STDBY_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bits 10:17 - Data0"] #[inline(always)] pub fn data0(&self) -> DATA0_R { DATA0_R::new(((self.bits >> 10) & 0xff) as u8) } #[doc = "Bits 18:25 - Data1"] #[inline(always)] pub fn data1(&self) -> DATA1_R { DATA1_R::new(((self.bits >> 18) & 0xff) as u8) } }
use crate::{builtins::PyModule, PyRef, VirtualMachine}; pub use module::raw_set_handle_inheritable; pub(crate) fn make_module(vm: &VirtualMachine) -> PyRef<PyModule> { let module = module::make_module(vm); super::os::extend_module(vm, &module); module } #[pymodule(name = "nt", with(super::os::_os))] pub(crate) mod module { use crate::{ builtins::{PyStrRef, PyTupleRef}, common::{crt_fd::Fd, os::errno, suppress_iph}, convert::ToPyException, function::Either, function::OptionalArg, stdlib::os::{ errno_err, DirFd, FollowSymlinks, OsPath, SupportFunc, TargetIsDirectory, _os, }, PyResult, TryFromObject, VirtualMachine, }; use std::{ env, fs, io, os::windows::ffi::{OsStrExt, OsStringExt}, }; use crate::builtins::PyDictRef; #[cfg(target_env = "msvc")] use crate::builtins::PyListRef; use winapi::{um, vc::vcruntime::intptr_t}; #[pyattr] use libc::{O_BINARY, O_TEMPORARY}; #[pyfunction] pub(super) fn access(path: OsPath, mode: u8, vm: &VirtualMachine) -> PyResult<bool> { use um::{fileapi, winnt}; let attr = unsafe { fileapi::GetFileAttributesW(path.to_widecstring(vm)?.as_ptr()) }; Ok(attr != fileapi::INVALID_FILE_ATTRIBUTES && (mode & 2 == 0 || attr & winnt::FILE_ATTRIBUTE_READONLY == 0 || attr & winnt::FILE_ATTRIBUTE_DIRECTORY != 0)) } #[derive(FromArgs)] pub(super) struct SymlinkArgs { src: OsPath, dst: OsPath, #[pyarg(flatten)] target_is_directory: TargetIsDirectory, #[pyarg(flatten)] _dir_fd: DirFd<{ _os::SYMLINK_DIR_FD as usize }>, } #[pyfunction] pub(super) fn symlink(args: SymlinkArgs, vm: &VirtualMachine) -> PyResult<()> { use std::os::windows::fs as win_fs; let dir = args.target_is_directory.target_is_directory || args .dst .as_path() .parent() .and_then(|dst_parent| dst_parent.join(&args.src).symlink_metadata().ok()) .map_or(false, |meta| meta.is_dir()); let res = if dir { win_fs::symlink_dir(args.src.path, args.dst.path) } else { win_fs::symlink_file(args.src.path, args.dst.path) }; res.map_err(|err| err.to_pyexception(vm)) } #[pyfunction] fn set_inheritable(fd: i32, inheritable: bool, vm: &VirtualMachine) -> PyResult<()> { let handle = Fd(fd).to_raw_handle().map_err(|e| e.to_pyexception(vm))?; set_handle_inheritable(handle as _, inheritable, vm) } #[pyattr] fn environ(vm: &VirtualMachine) -> PyDictRef { let environ = vm.ctx.new_dict(); for (key, value) in env::vars() { environ.set_item(&key, vm.new_pyobj(value), vm).unwrap(); } environ } #[pyfunction] fn chmod( path: OsPath, dir_fd: DirFd<0>, mode: u32, follow_symlinks: FollowSymlinks, vm: &VirtualMachine, ) -> PyResult<()> { const S_IWRITE: u32 = 128; let [] = dir_fd.0; let metadata = if follow_symlinks.0 { fs::metadata(&path) } else { fs::symlink_metadata(&path) }; let meta = metadata.map_err(|err| err.to_pyexception(vm))?; let mut permissions = meta.permissions(); permissions.set_readonly(mode & S_IWRITE == 0); fs::set_permissions(&path, permissions).map_err(|err| err.to_pyexception(vm)) } // cwait is available on MSVC only (according to CPython) #[cfg(target_env = "msvc")] extern "C" { fn _cwait(termstat: *mut i32, procHandle: intptr_t, action: i32) -> intptr_t; } #[cfg(target_env = "msvc")] #[pyfunction] fn waitpid(pid: intptr_t, opt: i32, vm: &VirtualMachine) -> PyResult<(intptr_t, i32)> { let mut status = 0; let pid = unsafe { suppress_iph!(_cwait(&mut status, pid, opt)) }; if pid == -1 { Err(errno_err(vm)) } else { Ok((pid, status << 8)) } } #[cfg(target_env = "msvc")] #[pyfunction] fn wait(vm: &VirtualMachine) -> PyResult<(intptr_t, i32)> { waitpid(-1, 0, vm) } #[pyfunction] fn kill(pid: i32, sig: isize, vm: &VirtualMachine) -> PyResult<()> { { use um::{handleapi, processthreadsapi, wincon, winnt}; let sig = sig as u32; let pid = pid as u32; if sig == wincon::CTRL_C_EVENT || sig == wincon::CTRL_BREAK_EVENT { let ret = unsafe { wincon::GenerateConsoleCtrlEvent(sig, pid) }; let res = if ret == 0 { Err(errno_err(vm)) } else { Ok(()) }; return res; } let h = unsafe { processthreadsapi::OpenProcess(winnt::PROCESS_ALL_ACCESS, 0, pid) }; if h.is_null() { return Err(errno_err(vm)); } let ret = unsafe { processthreadsapi::TerminateProcess(h, sig) }; let res = if ret == 0 { Err(errno_err(vm)) } else { Ok(()) }; unsafe { handleapi::CloseHandle(h) }; res } } #[pyfunction] fn get_terminal_size( fd: OptionalArg<i32>, vm: &VirtualMachine, ) -> PyResult<_os::PyTerminalSize> { let (columns, lines) = { use um::{handleapi, processenv, winbase, wincon}; let stdhandle = match fd { OptionalArg::Present(0) => winbase::STD_INPUT_HANDLE, OptionalArg::Present(1) | OptionalArg::Missing => winbase::STD_OUTPUT_HANDLE, OptionalArg::Present(2) => winbase::STD_ERROR_HANDLE, _ => return Err(vm.new_value_error("bad file descriptor".to_owned())), }; let h = unsafe { processenv::GetStdHandle(stdhandle) }; if h.is_null() { return Err(vm.new_os_error("handle cannot be retrieved".to_owned())); } if h == handleapi::INVALID_HANDLE_VALUE { return Err(errno_err(vm)); } let mut csbi = wincon::CONSOLE_SCREEN_BUFFER_INFO::default(); let ret = unsafe { wincon::GetConsoleScreenBufferInfo(h, &mut csbi) }; if ret == 0 { return Err(errno_err(vm)); } let w = csbi.srWindow; ( (w.Right - w.Left + 1) as usize, (w.Bottom - w.Top + 1) as usize, ) }; Ok(_os::PyTerminalSize { columns, lines }) } #[cfg(target_env = "msvc")] extern "C" { fn _wexecv(cmdname: *const u16, argv: *const *const u16) -> intptr_t; } #[cfg(target_env = "msvc")] #[pyfunction] fn execv( path: PyStrRef, argv: Either<PyListRef, PyTupleRef>, vm: &VirtualMachine, ) -> PyResult<()> { use std::iter::once; let make_widestring = |s: &str| widestring::WideCString::from_os_str(s).map_err(|err| err.to_pyexception(vm)); let path = make_widestring(path.as_str())?; let argv = vm.extract_elements_with(argv.as_ref(), |obj| { let arg = PyStrRef::try_from_object(vm, obj)?; make_widestring(arg.as_str()) })?; let first = argv .first() .ok_or_else(|| vm.new_value_error("execv() arg 2 must not be empty".to_owned()))?; if first.is_empty() { return Err( vm.new_value_error("execv() arg 2 first element cannot be empty".to_owned()) ); } let argv_execv: Vec<*const u16> = argv .iter() .map(|v| v.as_ptr()) .chain(once(std::ptr::null())) .collect(); if (unsafe { suppress_iph!(_wexecv(path.as_ptr(), argv_execv.as_ptr())) } == -1) { Err(errno_err(vm)) } else { Ok(()) } } #[pyfunction] fn _getfinalpathname(path: OsPath, vm: &VirtualMachine) -> PyResult { let real = path .as_ref() .canonicalize() .map_err(|e| e.to_pyexception(vm))?; path.mode.process_path(real, vm) } #[pyfunction] fn _getfullpathname(path: OsPath, vm: &VirtualMachine) -> PyResult { let wpath = path.to_widecstring(vm)?; let mut buffer = vec![0u16; winapi::shared::minwindef::MAX_PATH]; let ret = unsafe { um::fileapi::GetFullPathNameW( wpath.as_ptr(), buffer.len() as _, buffer.as_mut_ptr(), std::ptr::null_mut(), ) }; if ret == 0 { return Err(errno_err(vm)); } if ret as usize > buffer.len() { buffer.resize(ret as usize, 0); let ret = unsafe { um::fileapi::GetFullPathNameW( wpath.as_ptr(), buffer.len() as _, buffer.as_mut_ptr(), std::ptr::null_mut(), ) }; if ret == 0 { return Err(errno_err(vm)); } } let buffer = widestring::WideCString::from_vec_truncate(buffer); path.mode.process_path(buffer.to_os_string(), vm) } #[pyfunction] fn _getvolumepathname(path: OsPath, vm: &VirtualMachine) -> PyResult { let wide = path.to_widecstring(vm)?; let buflen = std::cmp::max(wide.len(), winapi::shared::minwindef::MAX_PATH); let mut buffer = vec![0u16; buflen]; let ret = unsafe { um::fileapi::GetVolumePathNameW(wide.as_ptr(), buffer.as_mut_ptr(), buflen as _) }; if ret == 0 { return Err(errno_err(vm)); } let buffer = widestring::WideCString::from_vec_truncate(buffer); path.mode.process_path(buffer.to_os_string(), vm) } #[pyfunction] fn _path_splitroot(path: OsPath, vm: &VirtualMachine) -> PyResult<(String, String)> { let orig: Vec<_> = path.path.encode_wide().collect(); if orig.is_empty() { return Ok(("".to_owned(), "".to_owned())); } let backslashed: Vec<_> = orig .iter() .copied() .map(|c| if c == b'/' as u16 { b'\\' as u16 } else { c }) .chain(std::iter::once(0)) // null-terminated .collect(); fn from_utf16(wstr: &[u16], vm: &VirtualMachine) -> PyResult<String> { String::from_utf16(wstr).map_err(|e| vm.new_unicode_decode_error(e.to_string())) } let wbuf = windows::core::PCWSTR::from_raw(backslashed.as_ptr()); let (root, path) = match unsafe { windows::Win32::UI::Shell::PathCchSkipRoot(wbuf) } { Ok(end) => { assert!(!end.is_null()); let len: usize = unsafe { end.as_ptr().offset_from(wbuf.as_ptr()) } .try_into() .expect("len must be non-negative"); assert!( len < backslashed.len(), // backslashed is null-terminated "path: {:?} {} < {}", std::path::PathBuf::from(std::ffi::OsString::from_wide(&backslashed)), len, backslashed.len() ); (from_utf16(&orig[..len], vm)?, from_utf16(&orig[len..], vm)?) } Err(_) => ("".to_owned(), from_utf16(&orig, vm)?), }; Ok((root, path)) } #[pyfunction] fn _getdiskusage(path: OsPath, vm: &VirtualMachine) -> PyResult<(u64, u64)> { use um::fileapi::GetDiskFreeSpaceExW; use winapi::shared::{ntdef::ULARGE_INTEGER, winerror}; let wpath = path.to_widecstring(vm)?; let mut _free_to_me = ULARGE_INTEGER::default(); let mut total = ULARGE_INTEGER::default(); let mut free = ULARGE_INTEGER::default(); let ret = unsafe { GetDiskFreeSpaceExW(wpath.as_ptr(), &mut _free_to_me, &mut total, &mut free) }; if ret != 0 { return Ok(unsafe { (*total.QuadPart(), *free.QuadPart()) }); } let err = io::Error::last_os_error(); if err.raw_os_error() == Some(winerror::ERROR_DIRECTORY as i32) { if let Some(parent) = path.as_ref().parent() { let parent = widestring::WideCString::from_os_str(parent).unwrap(); let ret = unsafe { GetDiskFreeSpaceExW(parent.as_ptr(), &mut _free_to_me, &mut total, &mut free) }; return if ret == 0 { Err(errno_err(vm)) } else { Ok(unsafe { (*total.QuadPart(), *free.QuadPart()) }) }; } } Err(err.to_pyexception(vm)) } #[pyfunction] fn get_handle_inheritable(handle: intptr_t, vm: &VirtualMachine) -> PyResult<bool> { let mut flags = 0; if unsafe { um::handleapi::GetHandleInformation(handle as _, &mut flags) } == 0 { Err(errno_err(vm)) } else { Ok(flags & um::winbase::HANDLE_FLAG_INHERIT != 0) } } pub fn raw_set_handle_inheritable(handle: intptr_t, inheritable: bool) -> io::Result<()> { use um::winbase::HANDLE_FLAG_INHERIT; let flags = if inheritable { HANDLE_FLAG_INHERIT } else { 0 }; let res = unsafe { um::handleapi::SetHandleInformation(handle as _, HANDLE_FLAG_INHERIT, flags) }; if res == 0 { Err(errno()) } else { Ok(()) } } #[pyfunction] fn set_handle_inheritable( handle: intptr_t, inheritable: bool, vm: &VirtualMachine, ) -> PyResult<()> { raw_set_handle_inheritable(handle, inheritable).map_err(|e| e.to_pyexception(vm)) } #[pyfunction] fn mkdir( path: OsPath, mode: OptionalArg<i32>, dir_fd: DirFd<{ _os::MKDIR_DIR_FD as usize }>, vm: &VirtualMachine, ) -> PyResult<()> { let mode = mode.unwrap_or(0o777); let [] = dir_fd.0; let _ = mode; let wide = path.to_widecstring(vm)?; let res = unsafe { um::fileapi::CreateDirectoryW(wide.as_ptr(), std::ptr::null_mut()) }; if res == 0 { return Err(errno_err(vm)); } Ok(()) } pub(crate) fn support_funcs() -> Vec<SupportFunc> { Vec::new() } } pub fn init_winsock() { static WSA_INIT: parking_lot::Once = parking_lot::Once::new(); WSA_INIT.call_once(|| unsafe { let mut wsa_data = std::mem::MaybeUninit::uninit(); let _ = winapi::um::winsock2::WSAStartup(0x0101, wsa_data.as_mut_ptr()); }) }
use console::style; use error::Error; use std::fs; use emoji; use PBAR; pub fn copy_from_crate(path: &str) -> Result<(), Error> { let step = format!( "{} {}Copying over your README...", style("[5/7]").bold().dim(), emoji::DANCERS ); let pb = PBAR.message(&step); let crate_readme_path = format!("{}/README.md", path); let new_readme_path = format!("{}/pkg/README.md", path); if let Err(_) = fs::copy(&crate_readme_path, &new_readme_path) { PBAR.warn("origin crate has no README"); }; pb.finish(); Ok(()) }
#![allow(unused_variables, dead_code)] // macros /// Dbus macro for Layout code use std::process::{Command, Stdio}; use ::ipc::utils::{parse_edge, parse_uuid, parse_direction, parse_axis, lock_tree_dbus}; use dbus::tree::MethodErr; use ::layout::{Layout, commands as layout_cmd}; use rustwlc::{ResizeEdge, Point}; dbus_interface! { path: "/org/way_cooler/Layout"; name: "org.way_cooler.Layout"; fn ActiveContainerId() -> container_id: DBusResult<String> { let tree = try!(lock_tree_dbus()); match tree.active_id() { Some(id) => Ok(id.to_string()), None => Ok("".to_string()) } } // TODO Make this optional, and actually do something with it! fn ToggleFloat(container_id: String) -> success: DBusResult<bool> { let maybe_uuid = try!(parse_uuid("container_id", &container_id)); match maybe_uuid { Some(uuid) => { let mut tree = try!(lock_tree_dbus()); tree.toggle_float() .and(Ok(true)) .map_err(|err| { MethodErr::failed(&format!("{:?}", err)) }) }, None => { layout_cmd::toggle_float(); Ok(true) } } } fn MoveContainer(container_id: String, direction: String) -> success: DBusResult<bool> { let target_uuid = try!(parse_uuid("container_id", &container_id)); let direction = try!(parse_direction("direction", direction.as_str())); let mut tree = try!(lock_tree_dbus()); tree.move_active(target_uuid, direction) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } // TODO Rename ChangeContainerLayout fn SplitContainer(container_id: String, split_axis: String) -> success: DBusResult<bool> { let uuid = try!(parse_uuid("container_id", &container_id)); let axis = try!(parse_axis("split_direction", split_axis.as_str())); // TODO Tree commands need to have these defined on the Tree, // for now this is _ok_, but we are swallowing an potential Tree lock error here. match axis { Layout::Horizontal => layout_cmd::split_horizontal(), Layout::Vertical => layout_cmd::split_vertical(), Layout::Tabbed => layout_cmd::tile_tabbed(), Layout::Stacked => layout_cmd::tile_stacked() } Ok(true) } fn ToggleCardinalTiling(container_id: String) -> success: DBusResult<bool> { let mut tree = try!(lock_tree_dbus()); let uuid = try!(try!(parse_uuid("container_id", &container_id)) .or_else(|| tree.active_id()) .ok_or(MethodErr::failed(&"No active container"))); tree.toggle_cardinal_tiling(uuid) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn SetActiveLayout(layout: String) -> success: DBusResult<bool> { let mut tree = lock_tree_dbus()?; let layout = parse_axis("layout", layout.as_str())?; tree.set_active_layout(layout) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn SwitchWorkspace(w_name: String) -> success: DBusResult<bool> { let mut tree = try!(lock_tree_dbus()); tree.switch_to_workspace(w_name.as_str()) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn SpawnProgram(prog_name: String) -> pid: DBusResult<u32> { Command::new(prog_name) .stdout(Stdio::null()) .stderr(Stdio::null()) .spawn() .map_err(|err| MethodErr::failed(&format!("{:?}", err))) .map(|child| child.id()) } fn CloseView(view_id: String) -> success: DBusResult<bool> { let mut tree = try!(lock_tree_dbus()); let uuid = try!(try!(parse_uuid("view_id", &view_id)) .or_else(|| tree.active_id()) .ok_or(MethodErr::failed(&"No active container"))); tree.remove_view_by_id(uuid) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn Focus(container_id: String) -> success: DBusResult<bool> { let mut tree = try!(lock_tree_dbus()); let uuid = try!(try!(parse_uuid("container_id", &container_id)) .or_else(|| tree.active_id()) .ok_or(MethodErr::failed(&"No active container"))); tree.focus(uuid) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn ToggleFloatingFocus() -> success: DBusResult<bool> { let mut tree = lock_tree_dbus()?; tree.toggle_floating_focus() .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn FocusDir(direction: String) -> success: DBusResult<bool> { let direction = try!(parse_direction("direction", direction.as_str())); let mut tree = try!(lock_tree_dbus()); tree.move_focus(direction) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn SendActiveToWorkspace(w_name: String) -> success: DBusResult<bool> { let mut tree = lock_tree_dbus()?; let uuid = tree.active_id() .ok_or(MethodErr::failed(&"No active container!"))?; tree.send_to_workspace(uuid, w_name.as_str()) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn SendToWorkspace(container_id: String, w_name: String) -> success: DBusResult<bool> { let mut tree = lock_tree_dbus()?; let uuid = parse_uuid("container_id", &container_id)? .or_else(|| tree.active_id()) .ok_or(MethodErr::failed(&"No active container"))?; tree.send_to_workspace(uuid, w_name.as_str()) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } // TODO Remove fn Debug() -> success: DBusResult<String> { Ok(format!("{}", layout_cmd::tree_as_json())) } fn ContainerInActiveWorkspace(container_id: String) -> success: DBusResult<bool> { let tree = try!(lock_tree_dbus()); let uuid = try!(try!(parse_uuid("container_id", &container_id)) .or_else(|| tree.active_id()) .ok_or(MethodErr::failed(&"No active container"))); tree.container_in_active_workspace(uuid) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } // TODO Rename to Fullscreen fn FullScreen(container_id: String, toggle: bool) -> success: DBusResult<bool> { let mut tree = try!(lock_tree_dbus()); let uuid = try!(try!(parse_uuid("container_id", &container_id)) .or_else(|| tree.active_id()) .ok_or(MethodErr::failed(&"No active container"))); tree.set_fullscreen(uuid, toggle) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn SetPointerPos(x: i32, y: i32) -> success: DBusResult<bool> { let mut tree = try!(lock_tree_dbus()); let point = Point { x: x, y: y}; tree.set_pointer_pos(point) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } // TODO Remove fn GrabAtCorner(container_id: String, dir: String) -> success: DBusResult<bool> { let mut tree = try!(lock_tree_dbus()); let uuid = try!(try!(parse_uuid("container_id", &container_id)) .or_else(|| tree.active_id()) .ok_or(MethodErr::failed(&"No active container"))); let mut edge = ResizeEdge::empty(); for word in dir.split(',') { edge |= try!(parse_edge(word)) } tree.grab_at_corner(uuid, edge) .and(Ok(true)) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } fn ActiveWorkspace() -> name: DBusResult<String> { let tree = try!(lock_tree_dbus()); tree.active_workspace() .map(|container| container.name()) .map_err(|err| MethodErr::failed(&format!("{:?}", err))) } }
use super::{Chunk, InterLink, LinkId, CHUNK_SIZE}; use rust_src::{a_star_search, dijkstra_search, Cost, Dir, Materials, Path, Point}; use std::collections::HashMap; #[derive(Debug)] pub struct HPAMap { pub width: usize, pub height: usize, pub chunks: Vec<Vec<Chunk>>, pub links: HashMap<LinkId, InterLink>, pub flood_start: LinkId, pub flood_goals: Vec<LinkId>, pub flood_goal_data: HashMap<LinkId, Path<LinkId>>, next_id: LinkId, } impl HPAMap { pub fn new(width: usize, height: usize, materials: &Materials) -> HPAMap { let width = width / CHUNK_SIZE; let height = height / CHUNK_SIZE; let mut chunks = Vec::with_capacity(width); let mut links = HashMap::new(); let mut next_id = 0; for x in 0..width { let mut col = Vec::with_capacity(height); chunks.push(col); for y in 0..height { let pos = Point::new(x, y) * CHUNK_SIZE; let chunk = { let mut neighbors = [None; 4]; neighbors[Dir::UP as usize] = chunks.get(x).and_then(|vec| vec.get(y - 1)); neighbors[Dir::LEFT as usize] = chunks.get(x - 1).and_then(|vec| vec.get(y)); Chunk::new(pos, materials, neighbors, &mut links, &mut next_id) }; chunks[x].push(chunk); } } HPAMap { width, height, chunks, links, flood_start: 0, flood_goals: vec![], flood_goal_data: HashMap::new(), next_id, } } pub fn empty() -> HPAMap { HPAMap { width: 0, height: 0, chunks: vec![], links: HashMap::new(), flood_start: 0, flood_goals: vec![], flood_goal_data: HashMap::new(), next_id: 0, } } pub fn link_at(&self, point: Point) -> Option<LinkId> { for link in self.links.values() { if link.pos == point { return Some(link.id); } } None } pub fn tile_changed(&mut self, tile: Point, materials: &Materials) { let p = tile / CHUNK_SIZE; { let chunk = &self.chunks[p.x][p.y]; let mut marked = chunk.links.clone(); for dir in (0..4).map(|i| i.into()) { if let Some(other) = p.get_in_dir(dir) { if other.x >= self.width || other.y >= self.height { continue; } for &id in self.chunks[other.x][other.y].links.iter() { marked.push(id); } } } for id in marked { if let Some(link) = self.links.remove(&id) { for outgoing in link.edges() { if let Some(neighbor) = self.links.get_mut(&outgoing) { neighbor.edges.remove(&id); } } for (dir, neighbor) in link.neighbors.iter().enumerate() { if let Some(neighbor) = neighbor { if let Some(neighbor) = self.links.get_mut(neighbor) { neighbor.neighbors[(dir + 2) % 4] = None; } } } } } } for dir in 0..4 { if let Some(point) = p.get_in_dir(dir.into()) { if point.x >= self.width || point.y >= self.height { continue; } let mut use_neighbor = [true; 4]; use_neighbor[(dir + 2) % 4] = false; let chunk = self.create_chunk(point, use_neighbor, materials); self.chunks[point.x][point.y] = chunk; } } let chunk = self.create_chunk(p, [true; 4], materials); self.chunks[p.x][p.y] = chunk; self.id_check(); } fn create_chunk( &mut self, point: Point, use_neighbor: [bool; 4], materials: &Materials, ) -> Chunk { let pos = point * CHUNK_SIZE; let point = Point::from(point); let chunks = &self.chunks; let mut neighbors = [None; 4]; for i in (0..4).filter(|&i| use_neighbor[i]) { neighbors[i] = point .get_in_dir(i.into()) .and_then(|p| chunks.get(p.x).and_then(|vec| vec.get(p.y))); } Chunk::new( pos, materials, neighbors, &mut self.links, &mut self.next_id, ) } pub fn path_find( &mut self, start: Point, end: Point, materials: &Materials, ) -> Option<Path<Point>> { if start == end { return Some(Path::new(vec![start], 0)); } if start / CHUNK_SIZE == end / CHUNK_SIZE { let start_chunk = &self.chunks[start.x / CHUNK_SIZE][start.y / CHUNK_SIZE]; return start_chunk.a_star(start, end, materials); } let backup_next_id = self.next_id; let start_link_id = self .link_at(start) .unwrap_or_else(|| self.temp_insert(start, materials)); let end_link_id = self .link_at(end) .unwrap_or_else(|| self.temp_insert(end, materials)); let path = self.a_star(start_link_id, end_link_id).map(|path| { let first = path[0]; let second = path[1]; let point_path = self.links[&first].path_to(second).unwrap(); Path::new(point_path.path.clone(), path.cost) }); self.clear_temp(); self.next_id = backup_next_id; path } fn temp_insert(&mut self, point: Point, materials: &Materials) -> LinkId { let id; { let chunk = &self.chunks[point.x / CHUNK_SIZE][point.y / CHUNK_SIZE]; let links = chunk .links .iter() .map(|id| self.links[id].pos) .collect::<Vec<Point>>(); let mut paths = Chunk::dijkstra(point, &links, chunk.pos, materials); let walk_cost = materials[point.x][point.y].walk_cost(); let mut link = InterLink::temp(self.next_id, point, walk_cost, [false; 4], [None; 4]); self.next_id += 1; for &other_id in chunk.links.iter() { let other_pos = self.links[&other_id].pos; if let Some(path) = paths.remove(&other_pos) { let mut other_path = path.clone(); other_path.path.reverse(); other_path.cost -= materials[point.x][point.y].walk_cost(); other_path.cost += materials[other_pos.x][other_pos.y].walk_cost(); link.edges.insert(other_id, path); self.links .get_mut(&other_id) .unwrap() .temp_edges .insert(link.id, other_path); } } id = link.id; self.links.insert(id, link); } { let chunk = &mut self.chunks[point.x / CHUNK_SIZE][point.y / CHUNK_SIZE]; chunk.links.push(id); } // check if we need to insert temp links in other chunks for other_pos in point.neighbors() { if other_pos / CHUNK_SIZE == point / CHUNK_SIZE || materials[other_pos.x][other_pos.y].is_solid() { continue; } let other_id = self .link_at(other_pos) .unwrap_or_else(|| self.temp_insert(other_pos, materials)); self.links .get_mut(&id) .unwrap() .add_neighbor(point.get_dir_to(other_pos).into(), other_id); self.links .get_mut(&other_id) .unwrap() .add_neighbor(other_pos.get_dir_to(point).into(), id); } id } fn clear_temp(&mut self) { let marked: Vec<LinkId> = self .links .values() .filter(|l| l.is_temp) .map(|l| l.id) .collect(); for id in marked { for dir in 0..4 { if let Some(neighbor_id) = self.links[&id].neighbors[dir] { self.links .get_mut(&neighbor_id) .unwrap() .remove_neighbor((dir + 2) % 4); } } } let chunks = &mut self.chunks; let links = &mut self.links; chunks .iter_mut() .flat_map(|col| col.iter_mut()) .for_each(|chunk| chunk.links.retain(|id| !links[id].is_temp)); links.retain(|_, link| !link.is_temp); for (_, link) in links.iter_mut() { link.clear_temp(); } } fn a_star(&self, start: LinkId, end: LinkId) -> Option<Path<LinkId>> { let end_point = self.links[&end].pos; let links = &self.links; let get_all_neighbors = |id: LinkId| links[&id].edges(); let get_cost = |id1: LinkId, id2: LinkId| links[&id1].path_to(id2).unwrap().cost; let is_walkable = |_| true; a_star_search( get_all_neighbors, get_cost, is_walkable, start, end, |id| links[&id].pos.dist(&end_point) as Cost, ) } fn id_check(&mut self) { if self.links.len() * 100 >= self.next_id { return; // only operate when actual count < 1% of next_id } let current: Vec<InterLink> = self.links.drain().map(|(_, link)| link).collect(); let mut mapping = HashMap::with_capacity(current.len()); for (i, mut link) in current.into_iter().enumerate() { mapping.insert(link.id, i); link.id = i; self.links.insert(link.id, link); } for link in self.links.values_mut() { let mut new = HashMap::with_capacity(link.edges.len()); for (id, path) in link.edges.drain() { new.insert(mapping[&id], path); } link.edges = new; } self.chunks .iter_mut() .flat_map(|col| col.iter_mut()) .flat_map(|chunk| chunk.links.iter_mut()) .for_each(|link| *link = mapping[link]); self.next_id = self.links.len(); } pub fn add_flood_goal(&mut self, point: Point, materials: &Materials) { let id = self .link_at(point) .unwrap_or_else(|| self.temp_insert(point, materials)); self.flood_goals.push(id); } pub fn flood_search(&mut self, start: Point, materials: &Materials) { let start_id = self .link_at(start) .unwrap_or_else(|| self.temp_insert(start, materials)); self.flood_start = start_id; let links = &self.links; let get_all_neighbors = |id: LinkId| links[&id].edges(); let get_cost = |id1: LinkId, id2: LinkId| links[&id1].path_to(id2).unwrap().cost; let is_walkable = |_| true; self.flood_goal_data = dijkstra_search( get_all_neighbors, get_cost, is_walkable, start_id, &self.flood_goals, ); } pub fn flood_path_to(&self, id: LinkId) -> Option<Path<Point>> { self.flood_goal_data.get(&id).map(|path| { let first = path[0]; let second = path[1]; let point_path = self.links[&first].path_to(second).unwrap(); Path::new(point_path.path.clone(), path.cost) }) } pub fn end_flood_search(&mut self) { self.flood_goals.clear(); self.flood_goal_data.clear(); self.clear_temp(); } }
use std::io::{self, Error, ErrorKind}; use serialport::{SerialPort, ClearBuffer}; use std::time::Duration; use std::convert::TryInto; const ACK: u8 = 0x79; const NACK: u8 = 0x1F; #[derive(Eq, PartialEq)] enum CommandResult { Ack, Nak, } pub struct Bootloader { serial: Box<dyn SerialPort>, supported_commands: Vec<u8>, } impl Bootloader { pub fn new(serial: Box<dyn SerialPort>) -> Self { Self { serial, supported_commands: vec![0x00] } } fn check_suppored_command(&self, command: u8) -> io::Result<()> { if self.supported_commands.iter().find(|v| **v == command).is_some() { Ok(()) } else { Err(Error::new( ErrorKind::Other, format!("Unsupported command: 0x{:02x}", command) )) } } fn recv_byte(&mut self) -> io::Result<u8> { let mut buf = [0; 1]; self.serial.read_exact(&mut buf)?; Ok(buf[0]) } fn wait_for_result(&mut self) -> io::Result<CommandResult> { self.serial.set_timeout(Duration::from_secs(1))?; let byte = self.recv_byte()?; match byte { ACK => Ok(CommandResult::Ack), NACK => Ok(CommandResult::Nak), v => Err(Error::new(ErrorKind::InvalidData, format!("Unexpected result code: {:02x}", v))), } } fn check_result(&mut self) -> io::Result<()> { self.serial.set_timeout(Duration::from_secs(1))?; let byte = self.recv_byte()?; match byte { ACK => Ok(()), NACK => Err(Error::new(ErrorKind::InvalidData, "Unexpected NAK")), v => Err(Error::new(ErrorKind::InvalidData, format!("Unexpected result code: {:02x}", v))), } } fn send(&mut self, data: &[u8]) -> io::Result<()> { self.serial.write_all(data)?; self.check_result()?; Ok(()) } pub fn init(&mut self) -> io::Result<()> { self.serial.clear(ClearBuffer::All)?; self.serial.write_all(&[0x7f])?; if self.wait_for_result()? == CommandResult::Nak { return Err(Error::new( ErrorKind::InvalidData, "Initial command was NAKed" )); } Ok(()) } pub fn cmd_get(&mut self) -> io::Result<()> { self.send(&[0x00, 0xff])?; let len = self.recv_byte()?; let mut buf = vec![0; len as usize + 1]; self.serial.read_exact(&mut buf)?; self.check_result()?; self.supported_commands.clear(); self.supported_commands.extend_from_slice(&buf[1..]); Ok(()) } pub fn get_device_id(&mut self) -> io::Result<u16> { self.check_suppored_command(0x02)?; self.send(&[0x02, 0xfd])?; let len = self.recv_byte()?; let mut buf = vec![0; len as usize + 1]; self.serial.read_exact(&mut buf)?; self.check_result()?; if buf.len() == 2 { let id = u16::from_be_bytes((&buf as &[u8]).try_into().unwrap()); Ok(id) } else { Err(Error::new( ErrorKind::InvalidData, "Unsupported response length" )) } } }
#![warn( clippy::all, clippy::complexity, clippy::style, clippy::perf, clippy::nursery, clippy::cargo )] pub mod chain; pub mod history; pub mod net; pub mod producer; mod client; mod clients; mod error; pub use self::client::*; pub use self::clients::*; pub use self::error::*; #[macro_export] macro_rules! builder { ($path:expr, $params:ty, $output:ty) => { impl $params { pub fn fetch<C: crate::Client>( self, client: &C, ) -> impl std::future::Future<Output = Result<$output, crate::Error>> { client.fetch::<$output, $params>($path, self) } } }; } // mod builder { // use crate::client::Client; // use crate::error::Error; // use futures::future::Future; // use serde::{Deserialize, Serialize}; // pub trait Builder: Serialize { // const PATH: &'static str; // type Output: 'static + for<'de> Deserialize<'de>; // fn fetch(&self, client: &Client) -> Box<Future<Item = Self::Output, Error = Error>> { // Box::new(client.fetch(Self::PATH, Some(self))) // } // } // } // pub use self::builder::*;
use Player; use Result; use BadMoveError; use std::fmt; pub struct Tile { pub owner: Option<Player>, position: u8, } impl Tile { pub fn new(position: u8) -> Tile { Tile { position: position, owner: None, } } pub fn play_x(&mut self) -> Result<()> { self.play(Player::X) } pub fn play_o(&mut self) -> Result<()> { self.play(Player::O) } pub fn play(&mut self, player: Player) -> Result<()> { match self.owner { Some(_) => Err(BadMoveError::AlreadyOccupied), None => { self.owner = Some(player); Ok(()) } } } } impl fmt::Display for Tile { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self.owner { None => write!(f, "{}", self.position), Some(Player::X) => write!(f, "X"), Some(Player::O) => write!(f, "O"), } } }
pub mod blines; pub mod cache; pub mod ctags; pub mod dumb_jump; pub mod exec; pub mod filter; pub mod grep; pub mod gtags; pub mod helptags; pub mod rpc;
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved // extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use crate::{Metadata, Tag, VariationalAsset}; // simplified versions of methods for the benefit only of wasm_bind #[wasm_bindgen] impl VariationalAsset { /// WASM-friendly version of `from_slice`; remaps its errors as `JsValue`. pub fn wasm_from_slice(glb: &[u8], tag: Option<Tag>) -> Result<VariationalAsset, JsValue> { VariationalAsset::from_slice(glb, tag.as_ref(), None).map_err(JsValue::from) } /// WASM-friendly version of `meld``; remaps its errors as `JsValue`. pub fn wasm_meld( base: &VariationalAsset, melded: &VariationalAsset, ) -> Result<VariationalAsset, JsValue> { VariationalAsset::meld(base, melded).map_err(JsValue::from) } /// WASM-friendly version of `glb()`; returns an ownable `Vec<u8>` instead of a `&[u8]` slice. pub fn wasm_glb(&self) -> Vec<u8> { self.glb.to_owned() } /// WASM-friendly version of `default_tag()`; returns a clone of the tag pub fn wasm_default_tag(&self) -> Tag { self.default_tag.clone() } /// WASM-friendly version of `metadata()`; returns a clone of our metadata pub fn wasm_metadata(&self) -> Metadata { self.metadata.clone() } }
include! ( concat! ( env! ("OUT_DIR"), "/serde_types.rs")); // ex: noet ts=4 filetype=rust
use core::marker::PhantomData; use digest::{ generic_array::{typenum::Unsigned, GenericArray}, BlockInput, Digest, ExtendableOutput, Update, XofReader, }; /// Trait for types implementing expand_message interface for hash_to_field pub trait ExpandMsg { /// Expands `msg` to the required number of bytes in `buf` fn expand_message(msg: &[u8], dst: &[u8], buf: &mut [u8]); } /// Placeholder type for implementing expand_message_xof based on a hash function #[derive(Debug)] pub struct ExpandMsgXof<HashT> { phantom: PhantomData<HashT>, } /// Placeholder type for implementing expand_message_xmd based on a hash function #[derive(Debug)] pub struct ExpandMsgXmd<HashT> { phantom: PhantomData<HashT>, } /// ExpandMsgXof implements expand_message_xof for the ExpandMsg trait impl<HashT> ExpandMsg for ExpandMsgXof<HashT> where HashT: Default + ExtendableOutput + Update, { fn expand_message(msg: &[u8], dst: &[u8], buf: &mut [u8]) { let len_in_bytes = buf.len(); let mut r = HashT::default() .chain(msg) .chain([(len_in_bytes >> 8) as u8, len_in_bytes as u8]) .chain(dst) .chain([dst.len() as u8]) .finalize_xof(); r.read(buf); } } /// ExpandMsgXmd implements expand_message_xmd for the ExpandMsg trait impl<HashT> ExpandMsg for ExpandMsgXmd<HashT> where HashT: Digest + BlockInput, { fn expand_message(msg: &[u8], dst: &[u8], buf: &mut [u8]) { let len_in_bytes = buf.len(); let b_in_bytes = HashT::OutputSize::to_usize(); let ell = (len_in_bytes + b_in_bytes - 1) / b_in_bytes; if ell > 255 { panic!("ell was too big in expand_message_xmd"); } let b_0 = HashT::new() .chain(GenericArray::<u8, HashT::BlockSize>::default()) .chain(msg) .chain([(len_in_bytes >> 8) as u8, len_in_bytes as u8, 0u8]) .chain(dst) .chain([dst.len() as u8]) .finalize(); // 288 is the most bytes that will be drawn // G2 requires 128 * 2 for hash_to_curve // but if a 48 byte digest is used then // 48 * 6 = 288 let mut b_vals = [0u8; 288]; // b_1 b_vals[..b_in_bytes].copy_from_slice( HashT::new() .chain(&b_0[..]) .chain([1u8]) .chain(dst) .chain([dst.len() as u8]) .finalize() .as_ref(), ); for i in 1..ell { // b_0 XOR b_(idx - 1) let mut tmp = GenericArray::<u8, HashT::OutputSize>::default(); b_0.iter() .zip(&b_vals[(i - 1) * b_in_bytes..i * b_in_bytes]) .enumerate() .for_each(|(j, (b0val, bi1val))| tmp[j] = b0val ^ bi1val); b_vals[i * b_in_bytes..(i + 1) * b_in_bytes].copy_from_slice( HashT::new() .chain(tmp) .chain([(i + 1) as u8]) .chain(dst) .chain([dst.len() as u8]) .finalize() .as_ref(), ); } buf.copy_from_slice(&b_vals[..len_in_bytes]); } }
use std::collections::HashMap; use rocket_contrib::Template; #[get("/")] fn index() -> Template { Template::render("index", HashMap::<String, String>::new()) }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct CALLFRAMEINFO { pub iMethod: u32, pub fHasInValues: super::super::super::Foundation::BOOL, pub fHasInOutValues: super::super::super::Foundation::BOOL, pub fHasOutValues: super::super::super::Foundation::BOOL, pub fDerivesFromIDispatch: super::super::super::Foundation::BOOL, pub cInInterfacesMax: i32, pub cInOutInterfacesMax: i32, pub cOutInterfacesMax: i32, pub cTopLevelInInterfaces: i32, pub iid: ::windows::core::GUID, pub cMethod: u32, pub cParams: u32, } #[cfg(feature = "Win32_Foundation")] impl CALLFRAMEINFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for CALLFRAMEINFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for CALLFRAMEINFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("CALLFRAMEINFO") .field("iMethod", &self.iMethod) .field("fHasInValues", &self.fHasInValues) .field("fHasInOutValues", &self.fHasInOutValues) .field("fHasOutValues", &self.fHasOutValues) .field("fDerivesFromIDispatch", &self.fDerivesFromIDispatch) .field("cInInterfacesMax", &self.cInInterfacesMax) .field("cInOutInterfacesMax", &self.cInOutInterfacesMax) .field("cOutInterfacesMax", &self.cOutInterfacesMax) .field("cTopLevelInInterfaces", &self.cTopLevelInInterfaces) .field("iid", &self.iid) .field("cMethod", &self.cMethod) .field("cParams", &self.cParams) .finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for CALLFRAMEINFO { fn eq(&self, other: &Self) -> bool { self.iMethod == other.iMethod && self.fHasInValues == other.fHasInValues && self.fHasInOutValues == other.fHasInOutValues && self.fHasOutValues == other.fHasOutValues && self.fDerivesFromIDispatch == other.fDerivesFromIDispatch && self.cInInterfacesMax == other.cInInterfacesMax && self.cInOutInterfacesMax == other.cInOutInterfacesMax && self.cOutInterfacesMax == other.cOutInterfacesMax && self.cTopLevelInInterfaces == other.cTopLevelInInterfaces && self.iid == other.iid && self.cMethod == other.cMethod && self.cParams == other.cParams } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for CALLFRAMEINFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for CALLFRAMEINFO { type Abi = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct CALLFRAMEPARAMINFO { pub fIn: super::super::super::Foundation::BOOLEAN, pub fOut: super::super::super::Foundation::BOOLEAN, pub stackOffset: u32, pub cbParam: u32, } #[cfg(feature = "Win32_Foundation")] impl CALLFRAMEPARAMINFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for CALLFRAMEPARAMINFO { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for CALLFRAMEPARAMINFO { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("CALLFRAMEPARAMINFO").field("fIn", &self.fIn).field("fOut", &self.fOut).field("stackOffset", &self.stackOffset).field("cbParam", &self.cbParam).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for CALLFRAMEPARAMINFO { fn eq(&self, other: &Self) -> bool { self.fIn == other.fIn && self.fOut == other.fOut && self.stackOffset == other.stackOffset && self.cbParam == other.cbParam } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for CALLFRAMEPARAMINFO {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for CALLFRAMEPARAMINFO { 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 CALLFRAME_COPY(pub i32); pub const CALLFRAME_COPY_NESTED: CALLFRAME_COPY = CALLFRAME_COPY(1i32); pub const CALLFRAME_COPY_INDEPENDENT: CALLFRAME_COPY = CALLFRAME_COPY(2i32); impl ::core::convert::From<i32> for CALLFRAME_COPY { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for CALLFRAME_COPY { 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 CALLFRAME_FREE(pub i32); pub const CALLFRAME_FREE_NONE: CALLFRAME_FREE = CALLFRAME_FREE(0i32); pub const CALLFRAME_FREE_IN: CALLFRAME_FREE = CALLFRAME_FREE(1i32); pub const CALLFRAME_FREE_INOUT: CALLFRAME_FREE = CALLFRAME_FREE(2i32); pub const CALLFRAME_FREE_OUT: CALLFRAME_FREE = CALLFRAME_FREE(4i32); pub const CALLFRAME_FREE_TOP_INOUT: CALLFRAME_FREE = CALLFRAME_FREE(8i32); pub const CALLFRAME_FREE_TOP_OUT: CALLFRAME_FREE = CALLFRAME_FREE(16i32); pub const CALLFRAME_FREE_ALL: CALLFRAME_FREE = CALLFRAME_FREE(31i32); impl ::core::convert::From<i32> for CALLFRAME_FREE { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for CALLFRAME_FREE { type Abi = Self; } #[derive(:: core :: clone :: Clone)] #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct CALLFRAME_MARSHALCONTEXT { pub fIn: super::super::super::Foundation::BOOLEAN, pub dwDestContext: u32, pub pvDestContext: *mut ::core::ffi::c_void, pub punkReserved: ::core::option::Option<::windows::core::IUnknown>, pub guidTransferSyntax: ::windows::core::GUID, } #[cfg(feature = "Win32_Foundation")] impl CALLFRAME_MARSHALCONTEXT {} #[cfg(feature = "Win32_Foundation")] impl ::core::default::Default for CALLFRAME_MARSHALCONTEXT { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } #[cfg(feature = "Win32_Foundation")] impl ::core::fmt::Debug for CALLFRAME_MARSHALCONTEXT { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("CALLFRAME_MARSHALCONTEXT").field("fIn", &self.fIn).field("dwDestContext", &self.dwDestContext).field("pvDestContext", &self.pvDestContext).field("punkReserved", &self.punkReserved).field("guidTransferSyntax", &self.guidTransferSyntax).finish() } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::PartialEq for CALLFRAME_MARSHALCONTEXT { fn eq(&self, other: &Self) -> bool { self.fIn == other.fIn && self.dwDestContext == other.dwDestContext && self.pvDestContext == other.pvDestContext && self.punkReserved == other.punkReserved && self.guidTransferSyntax == other.guidTransferSyntax } } #[cfg(feature = "Win32_Foundation")] impl ::core::cmp::Eq for CALLFRAME_MARSHALCONTEXT {} #[cfg(feature = "Win32_Foundation")] unsafe impl ::windows::core::Abi for CALLFRAME_MARSHALCONTEXT { type Abi = ::core::mem::ManuallyDrop<Self>; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct CALLFRAME_NULL(pub i32); pub const CALLFRAME_NULL_NONE: CALLFRAME_NULL = CALLFRAME_NULL(0i32); pub const CALLFRAME_NULL_INOUT: CALLFRAME_NULL = CALLFRAME_NULL(2i32); pub const CALLFRAME_NULL_OUT: CALLFRAME_NULL = CALLFRAME_NULL(4i32); pub const CALLFRAME_NULL_ALL: CALLFRAME_NULL = CALLFRAME_NULL(6i32); impl ::core::convert::From<i32> for CALLFRAME_NULL { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for CALLFRAME_NULL { 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 CALLFRAME_WALK(pub i32); pub const CALLFRAME_WALK_IN: CALLFRAME_WALK = CALLFRAME_WALK(1i32); pub const CALLFRAME_WALK_INOUT: CALLFRAME_WALK = CALLFRAME_WALK(2i32); pub const CALLFRAME_WALK_OUT: CALLFRAME_WALK = CALLFRAME_WALK(4i32); impl ::core::convert::From<i32> for CALLFRAME_WALK { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for CALLFRAME_WALK { type Abi = Self; } #[inline] pub unsafe fn CoGetInterceptor<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(iidintercepted: *const ::windows::core::GUID, punkouter: Param1, iid: *const ::windows::core::GUID, ppv: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CoGetInterceptor(iidintercepted: *const ::windows::core::GUID, punkouter: ::windows::core::RawPtr, iid: *const ::windows::core::GUID, ppv: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; } CoGetInterceptor(::core::mem::transmute(iidintercepted), punkouter.into_param().abi(), ::core::mem::transmute(iid), ::core::mem::transmute(ppv)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[inline] pub unsafe fn CoGetInterceptorFromTypeInfo<'a, Param1: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>, Param2: ::windows::core::IntoParam<'a, super::ITypeInfo>>(iidintercepted: *const ::windows::core::GUID, punkouter: Param1, typeinfo: Param2, iid: *const ::windows::core::GUID, ppv: *mut *mut ::core::ffi::c_void) -> ::windows::core::Result<()> { #[cfg(windows)] { #[link(name = "windows")] extern "system" { fn CoGetInterceptorFromTypeInfo(iidintercepted: *const ::windows::core::GUID, punkouter: ::windows::core::RawPtr, typeinfo: ::windows::core::RawPtr, iid: *const ::windows::core::GUID, ppv: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT; } CoGetInterceptorFromTypeInfo(::core::mem::transmute(iidintercepted), punkouter.into_param().abi(), typeinfo.into_param().abi(), ::core::mem::transmute(iid), ::core::mem::transmute(ppv)).ok() } #[cfg(not(windows))] unimplemented!("Unsupported target OS"); } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICallFrame(pub ::windows::core::IUnknown); impl ICallFrame { #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetInfo(&self) -> ::windows::core::Result<CALLFRAMEINFO> { let mut result__: <CALLFRAMEINFO as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<CALLFRAMEINFO>(result__) } pub unsafe fn GetIIDAndMethod(&self, piid: *mut ::windows::core::GUID, pimethod: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(piid), ::core::mem::transmute(pimethod)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetNames(&self, pwszinterface: *mut super::super::super::Foundation::PWSTR, pwszmethod: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(pwszinterface), ::core::mem::transmute(pwszmethod)).ok() } pub unsafe fn GetStackLocation(&self) -> *mut ::core::ffi::c_void { ::core::mem::transmute((::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self))) } pub unsafe fn SetStackLocation(&self, pvstack: *const ::core::ffi::c_void) { ::core::mem::transmute((::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(pvstack))) } pub unsafe fn SetReturnValue(&self, hr: ::windows::core::HRESULT) { ::core::mem::transmute((::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), ::core::mem::transmute(hr))) } pub unsafe fn GetReturnValue(&self) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).9)(::core::mem::transmute_copy(self)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetParamInfo(&self, iparam: u32) -> ::windows::core::Result<CALLFRAMEPARAMINFO> { let mut result__: <CALLFRAMEPARAMINFO as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).10)(::core::mem::transmute_copy(self), ::core::mem::transmute(iparam), &mut result__).from_abi::<CALLFRAMEPARAMINFO>(result__) } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe fn SetParam(&self, iparam: u32, pvar: *const super::VARIANT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).11)(::core::mem::transmute_copy(self), ::core::mem::transmute(iparam), ::core::mem::transmute(pvar)).ok() } #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe fn GetParam(&self, iparam: u32) -> ::windows::core::Result<super::VARIANT> { let mut result__: <super::VARIANT as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).12)(::core::mem::transmute_copy(self), ::core::mem::transmute(iparam), &mut result__).from_abi::<super::VARIANT>(result__) } pub unsafe fn Copy<'a, Param1: ::windows::core::IntoParam<'a, ICallFrameWalker>>(&self, copycontrol: CALLFRAME_COPY, pwalker: Param1) -> ::windows::core::Result<ICallFrame> { let mut result__: <ICallFrame as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).13)(::core::mem::transmute_copy(self), ::core::mem::transmute(copycontrol), pwalker.into_param().abi(), &mut result__).from_abi::<ICallFrame>(result__) } pub unsafe fn Free<'a, Param0: ::windows::core::IntoParam<'a, ICallFrame>, Param1: ::windows::core::IntoParam<'a, ICallFrameWalker>, Param2: ::windows::core::IntoParam<'a, ICallFrameWalker>, Param4: ::windows::core::IntoParam<'a, ICallFrameWalker>>(&self, pframeargsdest: Param0, pwalkerdestfree: Param1, pwalkercopy: Param2, freeflags: u32, pwalkerfree: Param4, nullflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).14)(::core::mem::transmute_copy(self), pframeargsdest.into_param().abi(), pwalkerdestfree.into_param().abi(), pwalkercopy.into_param().abi(), ::core::mem::transmute(freeflags), pwalkerfree.into_param().abi(), ::core::mem::transmute(nullflags)).ok() } pub unsafe fn FreeParam<'a, Param2: ::windows::core::IntoParam<'a, ICallFrameWalker>>(&self, iparam: u32, freeflags: u32, pwalkerfree: Param2, nullflags: u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).15)(::core::mem::transmute_copy(self), ::core::mem::transmute(iparam), ::core::mem::transmute(freeflags), pwalkerfree.into_param().abi(), ::core::mem::transmute(nullflags)).ok() } pub unsafe fn WalkFrame<'a, Param1: ::windows::core::IntoParam<'a, ICallFrameWalker>>(&self, walkwhat: u32, pwalker: Param1) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).16)(::core::mem::transmute_copy(self), ::core::mem::transmute(walkwhat), pwalker.into_param().abi()).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMarshalSizeMax(&self, pmshlcontext: *const CALLFRAME_MARSHALCONTEXT, mshlflags: super::MSHLFLAGS) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).17)(::core::mem::transmute_copy(self), ::core::mem::transmute(pmshlcontext), ::core::mem::transmute(mshlflags), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Marshal(&self, pmshlcontext: *const CALLFRAME_MARSHALCONTEXT, mshlflags: super::MSHLFLAGS, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, pcbbufferused: *mut u32, pdatarep: *mut u32, prpcflags: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).18)(::core::mem::transmute_copy(self), ::core::mem::transmute(pmshlcontext), ::core::mem::transmute(mshlflags), ::core::mem::transmute(pbuffer), ::core::mem::transmute(cbbuffer), ::core::mem::transmute(pcbbufferused), ::core::mem::transmute(pdatarep), ::core::mem::transmute(prpcflags)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn Unmarshal(&self, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, datarep: u32, pcontext: *const CALLFRAME_MARSHALCONTEXT) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).19)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbuffer), ::core::mem::transmute(cbbuffer), ::core::mem::transmute(datarep), ::core::mem::transmute(pcontext), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ReleaseMarshalData(&self, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, ibfirstrelease: u32, datarep: u32, pcontext: *const CALLFRAME_MARSHALCONTEXT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).20)(::core::mem::transmute_copy(self), ::core::mem::transmute(pbuffer), ::core::mem::transmute(cbbuffer), ::core::mem::transmute(ibfirstrelease), ::core::mem::transmute(datarep), ::core::mem::transmute(pcontext)).ok() } pub unsafe fn Invoke(&self, pvreceiver: *const ::core::ffi::c_void) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).21)(::core::mem::transmute_copy(self), ::core::mem::transmute(pvreceiver)).ok() } } unsafe impl ::windows::core::Interface for ICallFrame { type Vtable = ICallFrame_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd573b4b0_894e_11d2_b8b6_00c04fb9618a); } impl ::core::convert::From<ICallFrame> for ::windows::core::IUnknown { fn from(value: ICallFrame) -> Self { value.0 } } impl ::core::convert::From<&ICallFrame> for ::windows::core::IUnknown { fn from(value: &ICallFrame) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICallFrame { 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 ICallFrame { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICallFrame_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, pinfo: *mut CALLFRAMEINFO) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, piid: *mut ::windows::core::GUID, pimethod: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pwszinterface: *mut super::super::super::Foundation::PWSTR, pwszmethod: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> *mut ::core::ffi::c_void, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvstack: *const ::core::ffi::c_void), pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hr: ::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, iparam: u32, pinfo: *mut CALLFRAMEPARAMINFO) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iparam: u32, pvar: *const ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize, #[cfg(all(feature = "Win32_Foundation", feature = "Win32_System_Ole"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iparam: u32, pvar: *mut ::core::mem::ManuallyDrop<super::VARIANT>) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Win32_Foundation", feature = "Win32_System_Ole")))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, copycontrol: CALLFRAME_COPY, pwalker: ::windows::core::RawPtr, ppframe: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pframeargsdest: ::windows::core::RawPtr, pwalkerdestfree: ::windows::core::RawPtr, pwalkercopy: ::windows::core::RawPtr, freeflags: u32, pwalkerfree: ::windows::core::RawPtr, nullflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iparam: u32, freeflags: u32, pwalkerfree: ::windows::core::RawPtr, nullflags: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, walkwhat: u32, pwalker: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pmshlcontext: *const ::core::mem::ManuallyDrop<CALLFRAME_MARSHALCONTEXT>, mshlflags: super::MSHLFLAGS, pcbbufferneeded: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pmshlcontext: *const ::core::mem::ManuallyDrop<CALLFRAME_MARSHALCONTEXT>, mshlflags: super::MSHLFLAGS, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, pcbbufferused: *mut u32, pdatarep: *mut u32, prpcflags: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, datarep: u32, pcontext: *const ::core::mem::ManuallyDrop<CALLFRAME_MARSHALCONTEXT>, pcbunmarshalled: *mut u32) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, ibfirstrelease: u32, datarep: u32, pcontext: *const ::core::mem::ManuallyDrop<CALLFRAME_MARSHALCONTEXT>) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, pvreceiver: *const ::core::ffi::c_void) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICallFrameEvents(pub ::windows::core::IUnknown); impl ICallFrameEvents { pub unsafe fn OnCall<'a, Param0: ::windows::core::IntoParam<'a, ICallFrame>>(&self, pframe: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), pframe.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for ICallFrameEvents { type Vtable = ICallFrameEvents_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfd5e0843_fc91_11d0_97d7_00c04fb9618a); } impl ::core::convert::From<ICallFrameEvents> for ::windows::core::IUnknown { fn from(value: ICallFrameEvents) -> Self { value.0 } } impl ::core::convert::From<&ICallFrameEvents> for ::windows::core::IUnknown { fn from(value: &ICallFrameEvents) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICallFrameEvents { 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 ICallFrameEvents { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICallFrameEvents_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, pframe: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICallFrameWalker(pub ::windows::core::IUnknown); impl ICallFrameWalker { #[cfg(feature = "Win32_Foundation")] pub unsafe fn OnWalkInterface<'a, Param2: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>, Param3: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, iid: *const ::windows::core::GUID, ppvinterface: *const *const ::core::ffi::c_void, fin: Param2, fout: Param3) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(iid), ::core::mem::transmute(ppvinterface), fin.into_param().abi(), fout.into_param().abi()).ok() } } unsafe impl ::windows::core::Interface for ICallFrameWalker { type Vtable = ICallFrameWalker_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x08b23919_392d_11d2_b8a4_00c04fb9618a); } impl ::core::convert::From<ICallFrameWalker> for ::windows::core::IUnknown { fn from(value: ICallFrameWalker) -> Self { value.0 } } impl ::core::convert::From<&ICallFrameWalker> for ::windows::core::IUnknown { fn from(value: &ICallFrameWalker) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICallFrameWalker { 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 ICallFrameWalker { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICallFrameWalker_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, iid: *const ::windows::core::GUID, ppvinterface: *const *const ::core::ffi::c_void, fin: super::super::super::Foundation::BOOL, fout: super::super::super::Foundation::BOOL) -> ::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 ICallIndirect(pub ::windows::core::IUnknown); impl ICallIndirect { pub unsafe fn CallIndirect(&self, phrreturn: *mut ::windows::core::HRESULT, imethod: u32, pvargs: *const ::core::ffi::c_void, cbargs: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(phrreturn), ::core::mem::transmute(imethod), ::core::mem::transmute(pvargs), ::core::mem::transmute(cbargs)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMethodInfo(&self, imethod: u32, pinfo: *mut CALLFRAMEINFO, pwszmethod: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(imethod), ::core::mem::transmute(pinfo), ::core::mem::transmute(pwszmethod)).ok() } pub unsafe fn GetStackSize(&self, imethod: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(imethod), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIID(&self, piid: *mut ::windows::core::GUID, pfderivesfromidispatch: *mut super::super::super::Foundation::BOOL, pcmethod: *mut u32, pwszinterface: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(piid), ::core::mem::transmute(pfderivesfromidispatch), ::core::mem::transmute(pcmethod), ::core::mem::transmute(pwszinterface)).ok() } } unsafe impl ::windows::core::Interface for ICallIndirect { type Vtable = ICallIndirect_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd573b4b1_894e_11d2_b8b6_00c04fb9618a); } impl ::core::convert::From<ICallIndirect> for ::windows::core::IUnknown { fn from(value: ICallIndirect) -> Self { value.0 } } impl ::core::convert::From<&ICallIndirect> for ::windows::core::IUnknown { fn from(value: &ICallIndirect) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICallIndirect { 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 ICallIndirect { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICallIndirect_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, phrreturn: *mut ::windows::core::HRESULT, imethod: u32, pvargs: *const ::core::ffi::c_void, cbargs: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, imethod: u32, pinfo: *mut CALLFRAMEINFO, pwszmethod: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, imethod: u32, cbargs: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, piid: *mut ::windows::core::GUID, pfderivesfromidispatch: *mut super::super::super::Foundation::BOOL, pcmethod: *mut u32, pwszinterface: *mut super::super::super::Foundation::PWSTR) -> ::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 ICallInterceptor(pub ::windows::core::IUnknown); impl ICallInterceptor { pub unsafe fn CallIndirect(&self, phrreturn: *mut ::windows::core::HRESULT, imethod: u32, pvargs: *const ::core::ffi::c_void, cbargs: *mut u32) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(phrreturn), ::core::mem::transmute(imethod), ::core::mem::transmute(pvargs), ::core::mem::transmute(cbargs)).ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetMethodInfo(&self, imethod: u32, pinfo: *mut CALLFRAMEINFO, pwszmethod: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(imethod), ::core::mem::transmute(pinfo), ::core::mem::transmute(pwszmethod)).ok() } pub unsafe fn GetStackSize(&self, imethod: u32) -> ::windows::core::Result<u32> { let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), ::core::mem::transmute(imethod), &mut result__).from_abi::<u32>(result__) } #[cfg(feature = "Win32_Foundation")] pub unsafe fn GetIID(&self, piid: *mut ::windows::core::GUID, pfderivesfromidispatch: *mut super::super::super::Foundation::BOOL, pcmethod: *mut u32, pwszinterface: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), ::core::mem::transmute(piid), ::core::mem::transmute(pfderivesfromidispatch), ::core::mem::transmute(pcmethod), ::core::mem::transmute(pwszinterface)).ok() } pub unsafe fn RegisterSink<'a, Param0: ::windows::core::IntoParam<'a, ICallFrameEvents>>(&self, psink: Param0) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), psink.into_param().abi()).ok() } pub unsafe fn GetRegisteredSink(&self) -> ::windows::core::Result<ICallFrameEvents> { let mut result__: <ICallFrameEvents as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self), &mut result__).from_abi::<ICallFrameEvents>(result__) } } unsafe impl ::windows::core::Interface for ICallInterceptor { type Vtable = ICallInterceptor_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x60c7ca75_896d_11d2_b8b6_00c04fb9618a); } impl ::core::convert::From<ICallInterceptor> for ::windows::core::IUnknown { fn from(value: ICallInterceptor) -> Self { value.0 } } impl ::core::convert::From<&ICallInterceptor> for ::windows::core::IUnknown { fn from(value: &ICallInterceptor) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICallInterceptor { 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 ICallInterceptor { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::From<ICallInterceptor> for ICallIndirect { fn from(value: ICallInterceptor) -> Self { unsafe { ::core::mem::transmute(value) } } } impl ::core::convert::From<&ICallInterceptor> for ICallIndirect { fn from(value: &ICallInterceptor) -> Self { ::core::convert::From::from(::core::clone::Clone::clone(value)) } } impl<'a> ::windows::core::IntoParam<'a, ICallIndirect> for ICallInterceptor { fn into_param(self) -> ::windows::core::Param<'a, ICallIndirect> { ::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) }) } } impl<'a> ::windows::core::IntoParam<'a, ICallIndirect> for &ICallInterceptor { fn into_param(self) -> ::windows::core::Param<'a, ICallIndirect> { ::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) }) } } #[repr(C)] #[doc(hidden)] pub struct ICallInterceptor_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, phrreturn: *mut ::windows::core::HRESULT, imethod: u32, pvargs: *const ::core::ffi::c_void, cbargs: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, imethod: u32, pinfo: *mut CALLFRAMEINFO, pwszmethod: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, imethod: u32, cbargs: *mut u32) -> ::windows::core::HRESULT, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, piid: *mut ::windows::core::GUID, pfderivesfromidispatch: *mut super::super::super::Foundation::BOOL, pcmethod: *mut u32, pwszinterface: *mut super::super::super::Foundation::PWSTR) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, psink: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, ppsink: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ICallUnmarshal(pub ::windows::core::IUnknown); impl ICallUnmarshal { #[cfg(feature = "Win32_Foundation")] pub unsafe fn Unmarshal<'a, Param3: ::windows::core::IntoParam<'a, super::super::super::Foundation::BOOL>>(&self, imethod: u32, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, fforcebuffercopy: Param3, datarep: u32, pcontext: *const CALLFRAME_MARSHALCONTEXT, pcbunmarshalled: *mut u32, ppframe: *mut ::core::option::Option<ICallFrame>) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)( ::core::mem::transmute_copy(self), ::core::mem::transmute(imethod), ::core::mem::transmute(pbuffer), ::core::mem::transmute(cbbuffer), fforcebuffercopy.into_param().abi(), ::core::mem::transmute(datarep), ::core::mem::transmute(pcontext), ::core::mem::transmute(pcbunmarshalled), ::core::mem::transmute(ppframe), ) .ok() } #[cfg(feature = "Win32_Foundation")] pub unsafe fn ReleaseMarshalData(&self, imethod: u32, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, ibfirstrelease: u32, datarep: u32, pcontext: *const CALLFRAME_MARSHALCONTEXT) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(imethod), ::core::mem::transmute(pbuffer), ::core::mem::transmute(cbbuffer), ::core::mem::transmute(ibfirstrelease), ::core::mem::transmute(datarep), ::core::mem::transmute(pcontext)).ok() } } unsafe impl ::windows::core::Interface for ICallUnmarshal { type Vtable = ICallUnmarshal_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5333b003_2e42_11d2_b89d_00c04fb9618a); } impl ::core::convert::From<ICallUnmarshal> for ::windows::core::IUnknown { fn from(value: ICallUnmarshal) -> Self { value.0 } } impl ::core::convert::From<&ICallUnmarshal> for ::windows::core::IUnknown { fn from(value: &ICallUnmarshal) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ICallUnmarshal { 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 ICallUnmarshal { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct ICallUnmarshal_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, imethod: u32, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, fforcebuffercopy: super::super::super::Foundation::BOOL, datarep: u32, pcontext: *const ::core::mem::ManuallyDrop<CALLFRAME_MARSHALCONTEXT>, pcbunmarshalled: *mut u32, ppframe: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Win32_Foundation"))] usize, #[cfg(feature = "Win32_Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, imethod: u32, pbuffer: *const ::core::ffi::c_void, cbbuffer: u32, ibfirstrelease: u32, datarep: u32, pcontext: *const ::core::mem::ManuallyDrop<CALLFRAME_MARSHALCONTEXT>) -> ::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 IInterfaceRelated(pub ::windows::core::IUnknown); impl IInterfaceRelated { pub unsafe fn SetIID(&self, iid: *const ::windows::core::GUID) -> ::windows::core::Result<()> { (::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), ::core::mem::transmute(iid)).ok() } pub unsafe fn GetIID(&self) -> ::windows::core::Result<::windows::core::GUID> { let mut result__: <::windows::core::GUID as ::windows::core::Abi>::Abi = ::core::mem::zeroed(); (::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), &mut result__).from_abi::<::windows::core::GUID>(result__) } } unsafe impl ::windows::core::Interface for IInterfaceRelated { type Vtable = IInterfaceRelated_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd1fb5a79_7706_11d1_adba_00c04fc2adc0); } impl ::core::convert::From<IInterfaceRelated> for ::windows::core::IUnknown { fn from(value: IInterfaceRelated) -> Self { value.0 } } impl ::core::convert::From<&IInterfaceRelated> for ::windows::core::IUnknown { fn from(value: &IInterfaceRelated) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IInterfaceRelated { 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 IInterfaceRelated { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IInterfaceRelated_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, iid: *const ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, piid: *mut ::windows::core::GUID) -> ::windows::core::HRESULT, );
use crate::enumerate::EnumType; use crate::message::Message; use crate::stream::Buf; use crate::{Error, Result}; use pecan_utils::codec; use std::{ptr, usize}; macro_rules! impl_fixed { ($t:ident, $func:ident, $width:expr) => { pub fn $func(&mut self) -> Result<$t> { if self.read + $width > self.len_limit { return Err(Error::truncated()); } let mut data = [0u8; $width]; let mut read = 0; loop { let len = unsafe { let dst = data.as_mut_ptr().add(read); let bytes = self.buf.bytes(); if bytes.len() >= $width - read { ptr::copy_nonoverlapping(bytes.as_ptr(), dst, $width - read); $width - read } else { ptr::copy_nonoverlapping(bytes.as_ptr(), dst, bytes.len()); bytes.len() } }; self.buf.advance(len); self.read += len; read += len; if read == $width { return Ok($t::from_le_bytes(data)); } } } }; } macro_rules! impl_numeric_array { ($t:ident, $func:ident, $read_one:ident) => { pub fn $func(&mut self, dst: &mut Vec<$t>) -> Result<()> { let len = self.read_raw_varint32()? as usize; let old_limit = self.push_limit(len)?; while self.read < self.len_limit { dst.push(self.$read_one()?); } self.pop_limit(old_limit); Ok(()) } } } pub struct CodedInputStream<B> { buf: B, read: usize, len_limit: usize, depth: usize, recursive_limit: usize, } impl<B: Buf> CodedInputStream<B> { #[inline] pub fn new(buf: B) -> CodedInputStream<B> { CodedInputStream::with_recursive_limit(buf, 100) } #[inline] pub fn with_recursive_limit(buf: B, limit: usize) -> CodedInputStream<B> { CodedInputStream { len_limit: buf.available(), read: 0, buf, depth: 0, recursive_limit: limit, } } #[inline] pub fn read_tag(&mut self) -> Result<u32> { if self.len_limit == usize::MAX { if !self.buf.bytes().is_empty() { match self.read_raw_varint32() { Ok(v) => Ok(v), Err(e) => Err(e), } } else { Ok(0) } } else if self.len_limit != self.read { match self.read_raw_varint32() { Ok(v) => Ok(v), Err(e) => Err(e), } } else { Ok(0) } } #[inline] pub fn read_string(&mut self) -> Result<String> { let l = self.read_raw_varint32()? as usize; if l == 0 { return Ok(String::new()); } if self.read + l > self.len_limit { return Err(Error::truncated()); } let s = { let bytes = self.buf.bytes(); if bytes.len() >= l { match std::str::from_utf8(&bytes[..l]) { Ok(s) => Some(s.to_owned()), Err(_) => { return Err(Error::corrupted()) } } } else { None } }; let s = match s { Some(s) => { self.buf.advance(l); self.read += l; s } None => { let bytes = self.read_fixed_bytes(l)?; match String::from_utf8(bytes) { Ok(s) => s, Err(_) => { return Err(Error::corrupted()) } } } }; Ok(s) } #[inline] pub fn read_bytes(&mut self) -> Result<Vec<u8>> { let l = self.read_raw_varint32()? as usize; if l == 0 { return Ok(Vec::new()); } if self.read + l > self.len_limit { return Err(Error::truncated()); } self.read_fixed_bytes(l) } fn read_fixed_bytes(&mut self, l: usize) -> Result<Vec<u8>> { let mut buf: Vec<u8> = Vec::with_capacity(l); let mut read = 0; while l > read { let to_copy = { let bytes = self.buf.bytes(); if bytes.is_empty() { return Err(Error::truncated()); } let to_copy = if bytes.len() < l - read { bytes.len() } else { l - read }; unsafe { ptr::copy_nonoverlapping(bytes.as_ptr(), buf.as_mut_ptr().add(read), to_copy) } to_copy }; self.buf.advance(to_copy); read += to_copy; } self.read += read; unsafe { buf.set_len(l); } Ok(buf) } impl_fixed!(u32, read_fixed32, 4); impl_fixed!(u64, read_fixed64, 8); impl_fixed!(i32, read_sfixed32, 4); impl_fixed!(i64, read_sfixed64, 8); #[inline] pub fn read_f32(&mut self) -> Result<f32> { let u = self.read_fixed32()?; Ok(f32::from_bits(u)) } #[inline] pub fn read_f64(&mut self) -> Result<f64> { let u = self.read_fixed64()?; Ok(f64::from_bits(u)) } #[inline] pub fn read_var_u32(&mut self) -> Result<u32> { self.read_raw_varint32() } #[inline] pub fn read_var_u64(&mut self) -> Result<u64> { self.read_raw_varint64() } #[inline] pub fn read_var_i32(&mut self) -> Result<i32> { self.read_raw_varint64().map(|u| u as i64 as i32) } #[inline] pub fn read_var_i64(&mut self) -> Result<i64> { self.read_raw_varint64().map(|u| u as i64) } #[inline] pub fn read_var_s32(&mut self) -> Result<i32> { self.read_raw_varint32().map(codec::unzig_zag_32) } #[inline] pub fn read_var_s64(&mut self) -> Result<i64> { self.read_raw_varint64().map(codec::unzig_zag_64) } #[inline] pub fn read_bool(&mut self) -> Result<bool> { if self.read == self.len_limit { return Err(Error::truncated()); } let b = { let bytes = self.buf.bytes(); if bytes.is_empty() { return Err(Error::truncated()); } unsafe { *bytes.get_unchecked(0) } }; if b < 0x80 { self.buf.advance(1); self.read += 1; return Ok(b != 0); } self.read_var_u64().map(|u| u != 0) } #[inline] pub fn read_enum<E: EnumType>(&mut self) -> Result<E> { let value = self.read_raw_varint32()? as i32; Ok(E::from(value)) } pub fn read_message_like(&mut self, f: impl FnOnce(&mut Self) -> Result<()>) -> Result<()> { let len = self.read_raw_varint32()? as usize; if self.depth == self.recursive_limit { return Err(Error::ExceedRecursiveLimit(self.depth)); } let old_limit = self.push_limit(len)?; self.depth += 1; f(self)?; if self.read != self.len_limit { return Err(Error::corrupted()); } self.depth -= 1; self.pop_limit(old_limit); Ok(()) } pub fn read_message(&mut self, msg: &mut impl Message) -> Result<()> { self.read_message_like(|s| msg.merge_from(s)) } pub fn read_message_to(&mut self, msgs: &mut Vec<impl Message + Default>) -> Result<()> { msgs.push(Default::default()); let pos = msgs.len() - 1; let last = unsafe { msgs.get_unchecked_mut(pos) }; self.read_message(last) } impl_numeric_array!(bool, read_bool_array, read_bool); impl_numeric_array!(i32, read_var_i32_array, read_var_i32); impl_numeric_array!(u32, read_var_u32_array, read_var_u32); impl_numeric_array!(i32, read_var_s32_array, read_var_s32); impl_numeric_array!(f32, read_f32_array, read_f32); impl_numeric_array!(i32, read_sfixed32_array, read_sfixed32); impl_numeric_array!(u32, read_fixed32_array, read_fixed32); impl_numeric_array!(i64, read_var_i64_array, read_var_i64); impl_numeric_array!(u64, read_var_u64_array, read_var_u64); impl_numeric_array!(i64, read_var_s64_array, read_var_s64); impl_numeric_array!(f64, read_f64_array, read_f64); impl_numeric_array!(i64, read_sfixed64_array, read_sfixed64); impl_numeric_array!(u64, read_fixed64_array, read_fixed64); pub fn read_enum_array(&mut self, dst: &mut Vec<impl EnumType>) -> Result<()> { let len = self.read_raw_varint32()? as usize; let old_limit = self.push_limit(len)?; while self.read < self.len_limit { dst.push(self.read_var_i32()?.into()); } self.pop_limit(old_limit); Ok(()) } fn push_limit(&mut self, new_limit: usize) -> Result<usize> { let new_len_limit = self.read + new_limit; if new_len_limit > self.len_limit { return Err(Error::truncated()); } let old_limit = self.len_limit; self.len_limit = new_len_limit; Ok(old_limit) } fn pop_limit(&mut self, old_limit: usize) { self.len_limit = old_limit; } fn skip_varint(&mut self, unknown: &mut impl Discard) -> Result<()> { let u = self.read_raw_varint64()?; unknown.discard_varint(u); Ok(()) } fn skip_group(&mut self, unknown: &mut impl Discard, tag: u32) -> Result<()> { self.depth += 1; loop { let next_tag = self.read_tag()?; if next_tag == 0 { self.depth -= 1; return Err(Error::truncated()); } if next_tag & 0x07 == 4 { if next_tag >> 3 == tag >> 3 { unknown.discard_varint(next_tag as u64); self.depth -= 1; return Ok(()); } else { self.depth -= 1; return Err(Error::corrupted()); } } self.skip_field_impl(unknown, next_tag)?; } } fn skip_field_impl(&mut self, unknown: &mut impl Discard, tag: u32) -> Result<()> { if tag >> 3 == 0 { // 0 field number is illegal. return Err(Error::corrupted()); } unknown.discard_varint(tag as u64); let mut to_skip = match tag & 0x07 { 0 => return self.skip_varint(unknown), 1 => 8, 2 => { let len = self.read_raw_varint32()?; unknown.discard_varint(len as u64); len as usize } 3 => return self.skip_group(unknown, tag), 4 => return Err(Error::corrupted()), 5 => 4, _ => return Err(Error::corrupted()), }; if to_skip + self.read > self.len_limit { return Err(Error::truncated()); } while to_skip > 0 { let l = { let bytes = self.buf.bytes(); if bytes.is_empty() { return Err(Error::truncated()); } if bytes.len() > to_skip { unknown.discard_slice(unsafe { bytes.get_unchecked(..to_skip) }); to_skip } else { unknown.discard_slice(bytes); bytes.len() } }; self.buf.advance(l); self.read += l; to_skip -= l; } Ok(()) } #[inline] pub fn skip_field(&mut self, unknown: &mut Vec<u8>, tag: u32) -> Result<()> { self.skip_field_impl(unknown, tag) } #[inline] pub fn discard_field(&mut self, tag: u32) -> Result<()> { self.skip_field_impl(&mut BlackHole, tag) } #[inline] fn read_raw_varint32(&mut self) -> Result<u32> { match codec::decode_varint_u32(self.buf.bytes()) { Ok((u, n)) => { if self.read + n as usize <= self.len_limit { self.read += n as usize; self.buf.advance(n as usize); Ok(u) } else { Err(Error::truncated()) } } Err(codec::Error::Truncated) => self.slow_read_raw_varint32(), Err(codec::Error::Corrupted) => Err(Error::corrupted()), } } fn slow_read_raw_varint32(&mut self) -> Result<u32> { let mut data: u32 = 0; let mut read: usize = 0; 'outer: loop { let l = { let buf = self.buf.bytes(); for i in 0..std::cmp::min(buf.len(), 4 - read) { let b = unsafe { *buf.get_unchecked(i) }; data |= ((b & 0x7f) as u32) << ((i + read) * 7); if b < 0x80 { read = i + 1; break 'outer; } } if buf.len() > 4 - read { let b = unsafe { *buf.get_unchecked(4 - read) }; data |= (b as u32) << 28; if b < 0x80 { read = 4 - read + 1; break 'outer; } for i in 5 - read..std::cmp::min(buf.len(), 10 - read) { let b = unsafe { *buf.get_unchecked(i) }; if b < 0x80 { read = i + 1; break 'outer; } } if buf.len() >= 10 - read { return Err(Error::corrupted()); } } else if buf.is_empty() { return Err(Error::truncated()); } buf.len() }; read += l; if l + self.read <= self.len_limit { self.read += l; self.buf.advance(l); } else { return Err(Error::truncated()); } if read < 5 { continue; } loop { let l = { let buf = self.buf.bytes(); if buf.len() >= 10 - read { let b = unsafe { *buf.get_unchecked(9 - read) }; if b == 1 { read = 10 - read; break 'outer; } else { return Err(Error::corrupted()); } } else if buf.is_empty() { return Err(Error::truncated()); } buf.len() }; read += l; if l + self.read <= self.len_limit { self.read += l; self.buf.advance(l); } else { return Err(Error::truncated()); } } } if read + self.read <= self.len_limit { self.read += read; self.buf.advance(read); Ok(data) } else { Err(Error::truncated()) } } #[inline] fn read_raw_varint64(&mut self) -> Result<u64> { match codec::decode_varint_u64(self.buf.bytes()) { Ok((u, n)) => { if self.read + n as usize <= self.len_limit { self.read += n as usize; self.buf.advance(n as usize); Ok(u) } else { Err(Error::truncated()) } }, Err(codec::Error::Truncated) => self.slow_read_raw_varint64(), Err(codec::Error::Corrupted) => Err(Error::corrupted()), } } fn slow_read_raw_varint64(&mut self) -> Result<u64> { let mut data = 0; let mut read: usize = 0; 'outer: loop { let l = { let buf = self.buf.bytes(); for i in 0..std::cmp::min(buf.len(), 9 - read) { let b = unsafe { *buf.get_unchecked(i) }; data |= ((b & 0x7f) as u64) << ((read + i) * 7); if b < 0x80 { read = i + 1; break 'outer; } } if buf.len() > 9 - read { let b = unsafe { *buf.get_unchecked(9 - read) }; if b <= 1 { data |= (b as u64) << 63; read = 10 - read; break 'outer; } else { return Err(Error::corrupted()); } } else if buf.is_empty() { return Err(Error::truncated()); } buf.len() }; read += l; if l + self.read <= self.len_limit { self.read += l; self.buf.advance(l); } else { return Err(Error::truncated()); } } if read + self.read <= self.len_limit { self.read += read; self.buf.advance(read); Ok(data) } else { Err(Error::truncated()) } } } trait Discard { fn discard_varint(&mut self, tag: u64); fn discard_slice(&mut self, bytes: &[u8]); } impl Discard for Vec<u8> { #[inline] fn discard_varint(&mut self, tag: u64) { codec::encode_varint_u64(self, tag) } #[inline] fn discard_slice(&mut self, bytes: &[u8]) { self.extend_from_slice(bytes) } } struct BlackHole; impl Discard for BlackHole { #[inline] fn discard_varint(&mut self, _: u64) {} #[inline] fn discard_slice(&mut self, _: &[u8]) {} } #[cfg(test)] mod tests { use super::*; #[test] fn test_read_var_i64() { let s: &[u8] = &[0x80]; let mut cis = CodedInputStream::new(s); let e = cis.read_var_i64().unwrap_err(); assert!(e.is_truncated(), "{:?}", e); } #[test] fn test_read_var_u32() { let cases: &[(&[u8], u32)] = &[ (&[0xb9, 0xe0, 0x80, 0x80, 0x80, 0x80, 0x80, 0x80, 0x00], 12345), (&[0x80, 0x80, 0x80, 0x80, 0x30], 0), ]; for (bytes, n) in cases { let mut cis = CodedInputStream::new(*bytes); let u = cis.read_var_u32().unwrap(); assert_eq!(u, *n); } } }
#[doc = "Reader of register CR2"] pub type R = crate::R<u32, super::CR2>; #[doc = "Writer for register CR2"] pub type W = crate::W<u32, super::CR2>; #[doc = "Register CR2 `reset()`'s with value 0"] impl crate::ResetValue for super::CR2 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Most significant bit first\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum MSBFIRST_A { #[doc = "0: data is transmitted/received with data bit 0 first, following the start bit"] LSB = 0, #[doc = "1: data is transmitted/received with MSB (bit 7/8/9) first, following the start bit"] MSB = 1, } impl From<MSBFIRST_A> for bool { #[inline(always)] fn from(variant: MSBFIRST_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `MSBFIRST`"] pub type MSBFIRST_R = crate::R<bool, MSBFIRST_A>; impl MSBFIRST_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MSBFIRST_A { match self.bits { false => MSBFIRST_A::LSB, true => MSBFIRST_A::MSB, } } #[doc = "Checks if the value of the field is `LSB`"] #[inline(always)] pub fn is_lsb(&self) -> bool { *self == MSBFIRST_A::LSB } #[doc = "Checks if the value of the field is `MSB`"] #[inline(always)] pub fn is_msb(&self) -> bool { *self == MSBFIRST_A::MSB } } #[doc = "Write proxy for field `MSBFIRST`"] pub struct MSBFIRST_W<'a> { w: &'a mut W, } impl<'a> MSBFIRST_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: MSBFIRST_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "data is transmitted/received with data bit 0 first, following the start bit"] #[inline(always)] pub fn lsb(self) -> &'a mut W { self.variant(MSBFIRST_A::LSB) } #[doc = "data is transmitted/received with MSB (bit 7/8/9) first, following the start bit"] #[inline(always)] pub fn msb(self) -> &'a mut W { self.variant(MSBFIRST_A::MSB) } #[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 = "Binary data inversion\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum DATAINV_A { #[doc = "0: Logical data from the data register are send/received in positive/direct logic"] POSITIVE = 0, #[doc = "1: Logical data from the data register are send/received in negative/inverse logic"] NEGATIVE = 1, } impl From<DATAINV_A> for bool { #[inline(always)] fn from(variant: DATAINV_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `DATAINV`"] pub type DATAINV_R = crate::R<bool, DATAINV_A>; impl DATAINV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> DATAINV_A { match self.bits { false => DATAINV_A::POSITIVE, true => DATAINV_A::NEGATIVE, } } #[doc = "Checks if the value of the field is `POSITIVE`"] #[inline(always)] pub fn is_positive(&self) -> bool { *self == DATAINV_A::POSITIVE } #[doc = "Checks if the value of the field is `NEGATIVE`"] #[inline(always)] pub fn is_negative(&self) -> bool { *self == DATAINV_A::NEGATIVE } } #[doc = "Write proxy for field `DATAINV`"] pub struct DATAINV_W<'a> { w: &'a mut W, } impl<'a> DATAINV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: DATAINV_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "Logical data from the data register are send/received in positive/direct logic"] #[inline(always)] pub fn positive(self) -> &'a mut W { self.variant(DATAINV_A::POSITIVE) } #[doc = "Logical data from the data register are send/received in negative/inverse logic"] #[inline(always)] pub fn negative(self) -> &'a mut W { self.variant(DATAINV_A::NEGATIVE) } #[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 = "TX pin active level inversion\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum TXINV_A { #[doc = "0: TX pin signal works using the standard logic levels"] STANDARD = 0, #[doc = "1: TX pin signal values are inverted"] INVERTED = 1, } impl From<TXINV_A> for bool { #[inline(always)] fn from(variant: TXINV_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `TXINV`"] pub type TXINV_R = crate::R<bool, TXINV_A>; impl TXINV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> TXINV_A { match self.bits { false => TXINV_A::STANDARD, true => TXINV_A::INVERTED, } } #[doc = "Checks if the value of the field is `STANDARD`"] #[inline(always)] pub fn is_standard(&self) -> bool { *self == TXINV_A::STANDARD } #[doc = "Checks if the value of the field is `INVERTED`"] #[inline(always)] pub fn is_inverted(&self) -> bool { *self == TXINV_A::INVERTED } } #[doc = "Write proxy for field `TXINV`"] pub struct TXINV_W<'a> { w: &'a mut W, } impl<'a> TXINV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: TXINV_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "TX pin signal works using the standard logic levels"] #[inline(always)] pub fn standard(self) -> &'a mut W { self.variant(TXINV_A::STANDARD) } #[doc = "TX pin signal values are inverted"] #[inline(always)] pub fn inverted(self) -> &'a mut W { self.variant(TXINV_A::INVERTED) } #[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 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "RX pin active level inversion\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum RXINV_A { #[doc = "0: RX pin signal works using the standard logic levels"] STANDARD = 0, #[doc = "1: RX pin signal values are inverted"] INVERTED = 1, } impl From<RXINV_A> for bool { #[inline(always)] fn from(variant: RXINV_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `RXINV`"] pub type RXINV_R = crate::R<bool, RXINV_A>; impl RXINV_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> RXINV_A { match self.bits { false => RXINV_A::STANDARD, true => RXINV_A::INVERTED, } } #[doc = "Checks if the value of the field is `STANDARD`"] #[inline(always)] pub fn is_standard(&self) -> bool { *self == RXINV_A::STANDARD } #[doc = "Checks if the value of the field is `INVERTED`"] #[inline(always)] pub fn is_inverted(&self) -> bool { *self == RXINV_A::INVERTED } } #[doc = "Write proxy for field `RXINV`"] pub struct RXINV_W<'a> { w: &'a mut W, } impl<'a> RXINV_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: RXINV_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "RX pin signal works using the standard logic levels"] #[inline(always)] pub fn standard(self) -> &'a mut W { self.variant(RXINV_A::STANDARD) } #[doc = "RX pin signal values are inverted"] #[inline(always)] pub fn inverted(self) -> &'a mut W { self.variant(RXINV_A::INVERTED) } #[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 = "Swap TX/RX pins\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SWAP_A { #[doc = "0: TX/RX pins are used as defined in standard pinout"] STANDARD = 0, #[doc = "1: The TX and RX pins functions are swapped"] SWAPPED = 1, } impl From<SWAP_A> for bool { #[inline(always)] fn from(variant: SWAP_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `SWAP`"] pub type SWAP_R = crate::R<bool, SWAP_A>; impl SWAP_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> SWAP_A { match self.bits { false => SWAP_A::STANDARD, true => SWAP_A::SWAPPED, } } #[doc = "Checks if the value of the field is `STANDARD`"] #[inline(always)] pub fn is_standard(&self) -> bool { *self == SWAP_A::STANDARD } #[doc = "Checks if the value of the field is `SWAPPED`"] #[inline(always)] pub fn is_swapped(&self) -> bool { *self == SWAP_A::SWAPPED } } #[doc = "Write proxy for field `SWAP`"] pub struct SWAP_W<'a> { w: &'a mut W, } impl<'a> SWAP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: SWAP_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "TX/RX pins are used as defined in standard pinout"] #[inline(always)] pub fn standard(self) -> &'a mut W { self.variant(SWAP_A::STANDARD) } #[doc = "The TX and RX pins functions are swapped"] #[inline(always)] pub fn swapped(self) -> &'a mut W { self.variant(SWAP_A::SWAPPED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "STOP bits\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum STOP_A { #[doc = "0: 1 stop bit"] STOP1 = 0, #[doc = "1: 0.5 stop bit"] STOP0P5 = 1, #[doc = "2: 2 stop bit"] STOP2 = 2, #[doc = "3: 1.5 stop bit"] STOP1P5 = 3, } impl From<STOP_A> for u8 { #[inline(always)] fn from(variant: STOP_A) -> Self { variant as _ } } #[doc = "Reader of field `STOP`"] pub type STOP_R = crate::R<u8, STOP_A>; impl STOP_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> STOP_A { match self.bits { 0 => STOP_A::STOP1, 1 => STOP_A::STOP0P5, 2 => STOP_A::STOP2, 3 => STOP_A::STOP1P5, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `STOP1`"] #[inline(always)] pub fn is_stop1(&self) -> bool { *self == STOP_A::STOP1 } #[doc = "Checks if the value of the field is `STOP0P5`"] #[inline(always)] pub fn is_stop0p5(&self) -> bool { *self == STOP_A::STOP0P5 } #[doc = "Checks if the value of the field is `STOP2`"] #[inline(always)] pub fn is_stop2(&self) -> bool { *self == STOP_A::STOP2 } #[doc = "Checks if the value of the field is `STOP1P5`"] #[inline(always)] pub fn is_stop1p5(&self) -> bool { *self == STOP_A::STOP1P5 } } #[doc = "Write proxy for field `STOP`"] pub struct STOP_W<'a> { w: &'a mut W, } impl<'a> STOP_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: STOP_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "1 stop bit"] #[inline(always)] pub fn stop1(self) -> &'a mut W { self.variant(STOP_A::STOP1) } #[doc = "0.5 stop bit"] #[inline(always)] pub fn stop0p5(self) -> &'a mut W { self.variant(STOP_A::STOP0P5) } #[doc = "2 stop bit"] #[inline(always)] pub fn stop2(self) -> &'a mut W { self.variant(STOP_A::STOP2) } #[doc = "1.5 stop bit"] #[inline(always)] pub fn stop1p5(self) -> &'a mut W { self.variant(STOP_A::STOP1P5) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12); self.w } } #[doc = "Clock enable\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum CLKEN_A { #[doc = "0: CK pin disabled"] DISABLED = 0, #[doc = "1: CK pin enabled"] ENABLED = 1, } impl From<CLKEN_A> for bool { #[inline(always)] fn from(variant: CLKEN_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `CLKEN`"] pub type CLKEN_R = crate::R<bool, CLKEN_A>; impl CLKEN_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> CLKEN_A { match self.bits { false => CLKEN_A::DISABLED, true => CLKEN_A::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline(always)] pub fn is_disabled(&self) -> bool { *self == CLKEN_A::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline(always)] pub fn is_enabled(&self) -> bool { *self == CLKEN_A::ENABLED } } #[doc = "Write proxy for field `CLKEN`"] pub struct CLKEN_W<'a> { w: &'a mut W, } impl<'a> CLKEN_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: CLKEN_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "CK pin disabled"] #[inline(always)] pub fn disabled(self) -> &'a mut W { self.variant(CLKEN_A::DISABLED) } #[doc = "CK pin enabled"] #[inline(always)] pub fn enabled(self) -> &'a mut W { self.variant(CLKEN_A::ENABLED) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "7-bit Address Detection/4-bit Address Detection\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ADDM7_A { #[doc = "0: 4-bit address detection"] BIT4 = 0, #[doc = "1: 7-bit address detection"] BIT7 = 1, } impl From<ADDM7_A> for bool { #[inline(always)] fn from(variant: ADDM7_A) -> Self { variant as u8 != 0 } } #[doc = "Reader of field `ADDM7`"] pub type ADDM7_R = crate::R<bool, ADDM7_A>; impl ADDM7_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> ADDM7_A { match self.bits { false => ADDM7_A::BIT4, true => ADDM7_A::BIT7, } } #[doc = "Checks if the value of the field is `BIT4`"] #[inline(always)] pub fn is_bit4(&self) -> bool { *self == ADDM7_A::BIT4 } #[doc = "Checks if the value of the field is `BIT7`"] #[inline(always)] pub fn is_bit7(&self) -> bool { *self == ADDM7_A::BIT7 } } #[doc = "Write proxy for field `ADDM7`"] pub struct ADDM7_W<'a> { w: &'a mut W, } impl<'a> ADDM7_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: ADDM7_A) -> &'a mut W { { self.bit(variant.into()) } } #[doc = "4-bit address detection"] #[inline(always)] pub fn bit4(self) -> &'a mut W { self.variant(ADDM7_A::BIT4) } #[doc = "7-bit address detection"] #[inline(always)] pub fn bit7(self) -> &'a mut W { self.variant(ADDM7_A::BIT7) } #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 4)) | (((value as u32) & 0x01) << 4); self.w } } #[doc = "Reader of field `ADD`"] pub type ADD_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ADD`"] pub struct ADD_W<'a> { w: &'a mut W, } impl<'a> ADD_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 24)) | (((value as u32) & 0xff) << 24); self.w } } impl R { #[doc = "Bit 19 - Most significant bit first"] #[inline(always)] pub fn msbfirst(&self) -> MSBFIRST_R { MSBFIRST_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - Binary data inversion"] #[inline(always)] pub fn datainv(&self) -> DATAINV_R { DATAINV_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - TX pin active level inversion"] #[inline(always)] pub fn txinv(&self) -> TXINV_R { TXINV_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - RX pin active level inversion"] #[inline(always)] pub fn rxinv(&self) -> RXINV_R { RXINV_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 15 - Swap TX/RX pins"] #[inline(always)] pub fn swap(&self) -> SWAP_R { SWAP_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bits 12:13 - STOP bits"] #[inline(always)] pub fn stop(&self) -> STOP_R { STOP_R::new(((self.bits >> 12) & 0x03) as u8) } #[doc = "Bit 11 - Clock enable"] #[inline(always)] pub fn clken(&self) -> CLKEN_R { CLKEN_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 4 - 7-bit Address Detection/4-bit Address Detection"] #[inline(always)] pub fn addm7(&self) -> ADDM7_R { ADDM7_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bits 24:31 - Address of the USART node"] #[inline(always)] pub fn add(&self) -> ADD_R { ADD_R::new(((self.bits >> 24) & 0xff) as u8) } } impl W { #[doc = "Bit 19 - Most significant bit first"] #[inline(always)] pub fn msbfirst(&mut self) -> MSBFIRST_W { MSBFIRST_W { w: self } } #[doc = "Bit 18 - Binary data inversion"] #[inline(always)] pub fn datainv(&mut self) -> DATAINV_W { DATAINV_W { w: self } } #[doc = "Bit 17 - TX pin active level inversion"] #[inline(always)] pub fn txinv(&mut self) -> TXINV_W { TXINV_W { w: self } } #[doc = "Bit 16 - RX pin active level inversion"] #[inline(always)] pub fn rxinv(&mut self) -> RXINV_W { RXINV_W { w: self } } #[doc = "Bit 15 - Swap TX/RX pins"] #[inline(always)] pub fn swap(&mut self) -> SWAP_W { SWAP_W { w: self } } #[doc = "Bits 12:13 - STOP bits"] #[inline(always)] pub fn stop(&mut self) -> STOP_W { STOP_W { w: self } } #[doc = "Bit 11 - Clock enable"] #[inline(always)] pub fn clken(&mut self) -> CLKEN_W { CLKEN_W { w: self } } #[doc = "Bit 4 - 7-bit Address Detection/4-bit Address Detection"] #[inline(always)] pub fn addm7(&mut self) -> ADDM7_W { ADDM7_W { w: self } } #[doc = "Bits 24:31 - Address of the USART node"] #[inline(always)] pub fn add(&mut self) -> ADD_W { ADD_W { w: self } } }
use std::io::Read; pub(crate) fn authentication_group() -> structopt::clap::ArgGroup<'static> { structopt::clap::ArgGroup::with_name("authentication").required(true) } pub(crate) fn parse_authentication( sas_token: Option<String>, certificate_file: Option<std::path::PathBuf>, certificate_file_password: Option<String>, ) -> azure_iot_mqtt::Authentication { match (sas_token, certificate_file, certificate_file_password) { (Some(sas_token), None, None) => azure_iot_mqtt::Authentication::SasToken(sas_token), (None, Some(certificate_file), Some(certificate_file_password)) => { let certificate_file_display = certificate_file.display().to_string(); let mut certificate_file = match std::fs::File::open(certificate_file) { Ok(certificate_file) => certificate_file, Err(err) => panic!( "could not open certificate file {}: {}", certificate_file_display, err ), }; let mut certificate = vec![]; if let Err(err) = certificate_file.read_to_end(&mut certificate) { panic!( "could not read certificate file {}: {}", certificate_file_display, err ); } azure_iot_mqtt::Authentication::Certificate { der: certificate, password: certificate_file_password, } } _ => unreachable!(), } } pub(crate) fn duration_from_secs_str( s: &str, ) -> Result<std::time::Duration, <u64 as std::str::FromStr>::Err> { Ok(std::time::Duration::from_secs(s.parse()?)) }
//! mapbaddr, machine APB base address register read_csr!(0xFC1); /// Get APB peripheral base address #[inline] pub fn read() -> usize { unsafe { _read() } }
use crate::config; use anyhow::Result; use std::process::Command; /// Print a tree of all tracked files. Relies on the `tree` utility. pub fn tree() -> Result<()> { Command::new("tree") .arg(config::tittle_config_dir()) .arg("-aC") .arg("--noreport") .arg("-I") .arg(".git*|tittle_config.json") .status()?; Ok(()) }
use rocket::http::Status; use rocket::request::{self, FromRequest, Request}; use rocket::response::Failure; use rocket::Outcome; use rocket::Route; use rocket_contrib::Json; use dotenv::dotenv; use std::env; use serde_derive::{Deserialize, Serialize}; use bcrypt::{hash, verify, DEFAULT_COST}; use frank_jwt::{decode, encode, Algorithm}; use uuid::Uuid; use super::db::models::*; use super::db::DbConn; use super::diesel::prelude::*; #[derive(Debug, Clone)] pub struct Secret(pub String); #[derive(Serialize, Deserialize, Debug, Clone)] pub struct TokenResponse { pub token: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct LoginRequest { pub email: String, pub password: String, } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct NewUserRequest { pub name: String, pub email: String, pub password: String, } pub struct AuthInfo { pub user_id: Uuid, pub user_email: String, pub user_name: String, } fn secret() -> String { dotenv().ok(); env::var("SECRET").expect("SECRET must be set") } impl<'a, 'r> FromRequest<'a, 'r> for AuthInfo { type Error = (); fn from_request(request: &'a Request<'r>) -> request::Outcome<AuthInfo, ()> { let keys: Vec<_> = request.headers().get("Authorization").collect(); if keys.len() != 1 { return Outcome::Failure((Status::BadRequest, ())); } let key: Vec<&str> = keys[0].split(' ').collect(); if key.len() != 2 { return Outcome::Failure((Status::BadRequest, ())); } let key = key[1]; match decode(&key.to_string(), &secret(), Algorithm::HS256) { Ok((_header, payload)) => Outcome::Success(AuthInfo { user_id: Uuid::parse_str(payload.get("user_id").unwrap().as_str().unwrap()) .unwrap(), user_email: payload .get("user_email") .unwrap() .as_str() .unwrap() .to_string(), user_name: payload .get("user_name") .unwrap() .as_str() .unwrap() .to_string(), }), Err(_e) => Outcome::Forward(()), } } } #[post("/login", data = "<login_request>")] fn login(login_request: Json<LoginRequest>, conn: DbConn) -> Result<Json<TokenResponse>, Failure> { use super::db::schema::users::dsl::*; let login_info = login_request.into_inner(); let results = users .filter(email.eq(login_info.email)) .limit(1) .load::<User>(&*conn) .expect("Failed to query User"); if results.len() == 0 { return Err(Failure(Status::Unauthorized)); } let user = results.get(0).expect("Failed to get User"); let valid = verify(&login_info.password, &user.password).expect("Failed to verify hash"); if !valid { return Err(Failure(Status::Unauthorized)); } let payload = json!({ "user_id": user.id, "user_email": user.email, "user_name": user.name, }); let header = json!({}); let token = encode(header, &secret(), &payload, Algorithm::HS256).expect("Failed to encode token"); let token_response = TokenResponse { token: token }; Ok(Json(token_response)) } #[post("/create_user", data = "<new_user_request>")] fn new_user( new_user_request: Json<NewUserRequest>, conn: DbConn, ) -> Result<Json<&'static str>, Status> { use super::db::schema::users::dsl::*; let hashed = hash(&new_user_request.password, DEFAULT_COST).expect("Error hashing password"); let new_user = NewUser { id: Uuid::new_v4(), name: &new_user_request.name.clone(), email: &new_user_request.email.clone(), password: &hashed.clone(), }; diesel::insert_into(users) .values(new_user) .execute(&*conn) .expect("Failed to add user"); Ok(Json("{'message': 'User added.'}")) } #[get("/renew")] fn renew(auth_info: AuthInfo) -> Result<Json<TokenResponse>, Status> { let payload = json!({ "user_id": auth_info.user_id, "user_email": auth_info.user_email, "user_name": auth_info.user_name, }); let header = json!({}); let token = encode(header, &secret(), &payload, Algorithm::HS256).expect("Failed to encode token"); let token_response = TokenResponse { token: token }; Ok(Json(token_response)) } pub fn routes() -> Vec<Route> { routes![login, renew, new_user] }
//! Combine parsing, translation and compilation with a Standard ML compiler use std::io; use combine::*; use combine::primitives::Error; use parser; use translator::*; pub fn parse_and_translate<I, W>(source_code: I, output: &mut W) -> Result<(), ParseError<I>> where I: Stream<Item = char>, W: io::Write, { parser::function() .and_then(|func| { translate_function(&func, output).map_err(Error::from) }) .parse(source_code) // Check that all input was consumed .and_then(|(_, mut stream)| { if stream.uncons().is_err() { Ok(()) } else { Err(ParseError::new( stream.position(), parser::str_error("Failed to parse all input"), )) } }) }
pub struct SubRectangleQueries { width: i32, matrix: Vec<i32>, } impl SubRectangleQueries { fn new(rectangle: Vec<Vec<i32>>) -> Self { SubRectangleQueries { width: rectangle[0].len() as i32, matrix: rectangle.into_iter().flatten().collect::<Vec<i32>>(), } } fn update_subrectangle(&mut self, row1: i32, col1: i32, row2: i32, col2: i32, new_value: i32) { for x in row1..=row2 { for y in col1..=col2 { let idx = self.xy_idx(x, y); self.matrix[idx] = new_value; } } } fn get_value(&self, row: i32, col: i32) -> i32 { let idx = self.xy_idx(row, col); self.matrix[idx] } fn xy_idx(&self, x: i32, y: i32) -> usize { (x as usize * self.width as usize) + y as usize } } #[cfg(test)] mod sub_rectangle_queries_tests { use super::*; pub enum Instructions { GetValue((Vec<i32>, i32)), UpdateSubRectangle(Vec<i32>), } fn assert_query_instructions( instructions: Vec<Instructions>, mut rect_queries: SubRectangleQueries, ) { use self::Instructions::*; for ins in instructions { match ins { GetValue((pos, expected)) => { let result = rect_queries.get_value(pos[0], pos[1]); assert_eq!(result, expected) } UpdateSubRectangle(pos) => { let row1 = pos[0]; let col1 = pos[1]; let row2 = pos[2]; let col2 = pos[3]; let new_value = pos[4]; rect_queries.update_subrectangle(row1, col1, row2, col2, new_value); } } } } #[test] fn sub_rectangle_queries_one() { use self::Instructions::*; // arrange let tests = vec![ GetValue((vec![0, 2], 1)), UpdateSubRectangle(vec![0, 0, 3, 2, 5]), GetValue((vec![0, 2], 5)), GetValue((vec![3, 1], 5)), UpdateSubRectangle(vec![3, 0, 3, 2, 10]), GetValue((vec![3, 1], 10)), GetValue((vec![0, 2], 5)), ]; let rect_queries = SubRectangleQueries::new(vec![ vec![1, 2, 1], vec![4, 3, 4], vec![3, 2, 1], vec![1, 1, 1], ]); assert_query_instructions(tests, rect_queries); } }
//! This module contains code to translate from InfluxDB IOx data //! formats into the formats needed by gRPC use std::{collections::BTreeSet, sync::Arc}; use arrow::datatypes::DataType as ArrowDataType; use futures::{stream::BoxStream, Stream, StreamExt}; use iox_query::exec::{ fieldlist::FieldList, seriesset::series::{self, Batch, Either}, }; use predicate::rpc_predicate::{FIELD_COLUMN_NAME, MEASUREMENT_COLUMN_NAME}; use generated_types::{ measurement_fields_response::{FieldType, MessageField}, read_response::{ frame::Data, BooleanPointsFrame, DataType, FloatPointsFrame, Frame, GroupFrame, IntegerPointsFrame, SeriesFrame, StringPointsFrame, UnsignedPointsFrame, }, MeasurementFieldsResponse, Tag, }; use super::{TAG_KEY_FIELD, TAG_KEY_MEASUREMENT}; use snafu::Snafu; #[derive(Debug, Snafu)] pub enum Error { #[snafu(display("Error converting series set to gRPC: {}", source))] ConvertingSeries { source: iox_query::exec::seriesset::series::Error, }, #[snafu(display("Unsupported field data type in gRPC data translation: {}", data_type))] UnsupportedFieldType { data_type: ArrowDataType }, } pub type Result<T, E = Error> = std::result::Result<T, E>; /// Convert a set of tag_keys into a form suitable for gRPC transport, /// adding the special `0x00` (`_m`) and `0xff` (`_f`) tag keys /// /// Namely, a `Vec<Vec<u8>>`, including the measurement and field names pub fn tag_keys_to_byte_vecs(tag_keys: Arc<BTreeSet<String>>) -> Vec<Vec<u8>> { // special case measurement (`0x00`) and field (`0xff`) // ensuring they are in the correct sort order (first and last, respectively) let mut byte_vecs = Vec::with_capacity(2 + tag_keys.len()); byte_vecs.push(TAG_KEY_MEASUREMENT.to_vec()); // Shown as `_m == _measurement` tag_keys.iter().for_each(|name| { byte_vecs.push(name.bytes().collect()); }); byte_vecs.push(TAG_KEY_FIELD.to_vec()); // Shown as `_f == _field` byte_vecs } /// Convert Series and Groups into a form suitable for gRPC transport: /// /// ```text /// (GroupFrame) potentially /// /// (SeriesFrame for field1) /// (*Points for field1) /// (SeriesFrame for field12) /// (*Points for field1) /// (....) /// (SeriesFrame for field1) /// (*Points for field1) /// (SeriesFrame for field12) /// (*Points for field1) /// (....) /// ``` /// /// The specific type of (*Points) depends on the type of field column. /// /// If `tag_key_binary_format` is `true` then tag keys for measurements and /// fields are emitted in the canonical TSM format represented by `\x00` and /// `\xff` respectively. pub fn series_or_groups_to_frames<S, E>( series_or_groups: S, tag_key_binary_format: bool, ) -> impl Stream<Item = Result<Frame, E>> where S: Stream<Item = Result<Either, E>>, E: Send + 'static, { series_or_groups.flat_map(move |res| match res { Ok(Either::Series(series)) => series_to_frames(series, tag_key_binary_format) .map(Ok) .boxed() as BoxStream<'static, Result<Frame, E>>, Ok(Either::Group(group)) => futures::stream::once(async move { Ok(group_to_frame(group)) }) .boxed() as BoxStream<'static, Result<Frame, E>>, Err(e) => futures::stream::once(async move { Err(e) }).boxed() as BoxStream<'static, Result<Frame, E>>, }) } /// Converts a `Series` into frames for GRPC transport fn series_to_frames( series: series::Series, tag_key_binary_format: bool, ) -> impl Stream<Item = Frame> { let series::Series { tags, data } = series; let (data_type, data_frames): (DataType, Vec<Frame>) = match data { series::Data::FloatPoints(batches) => ( DataType::Float, batches .into_iter() .map(|Batch { timestamps, values }| Frame { data: Some(Data::FloatPoints(FloatPointsFrame { timestamps, values })), }) .collect(), ), series::Data::IntegerPoints(batches) => ( DataType::Integer, batches .into_iter() .map(|Batch { timestamps, values }| Frame { data: Some(Data::IntegerPoints(IntegerPointsFrame { timestamps, values, })), }) .collect(), ), series::Data::UnsignedPoints(batches) => ( DataType::Unsigned, batches .into_iter() .map(|Batch { timestamps, values }| Frame { data: Some(Data::UnsignedPoints(UnsignedPointsFrame { timestamps, values, })), }) .collect(), ), series::Data::BooleanPoints(batches) => ( DataType::Boolean, batches .into_iter() .map(|Batch { timestamps, values }| Frame { data: Some(Data::BooleanPoints(BooleanPointsFrame { timestamps, values, })), }) .collect(), ), series::Data::StringPoints(batches) => ( DataType::String, batches .into_iter() .map(|Batch { timestamps, values }| Frame { data: Some(Data::StringPoints(StringPointsFrame { timestamps, values })), }) .collect(), ), }; futures::stream::iter( std::iter::once(Frame { data: Some(Data::Series(SeriesFrame { tags: convert_tags(tags, tag_key_binary_format), data_type: data_type.into(), })), }) .chain(data_frames.into_iter()), ) } /// Converts a [`series::Group`] into a storage gRPC `GroupFrame` /// format that can be returned to the client. fn group_to_frame(group: series::Group) -> Frame { let series::Group { tag_keys, partition_key_vals, } = group; let group_frame = GroupFrame { tag_keys: arcs_to_bytes(tag_keys), partition_key_vals: arcs_to_bytes(partition_key_vals), }; let data = Data::Group(group_frame); Frame { data: Some(data) } } /// Convert the `tag=value` pairs from `Arc<str>` to `Vec<u8>` for gRPC transport fn convert_tags(tags: Vec<series::Tag>, tag_key_binary_format: bool) -> Vec<Tag> { let mut res: Vec<Tag> = tags .into_iter() .map(|series::Tag { key, value }| Tag { key: match tag_key_binary_format { true => match key.as_ref() { MEASUREMENT_COLUMN_NAME => vec![0_u8], FIELD_COLUMN_NAME => vec![255_u8], _ => key.bytes().collect(), }, false => key.bytes().collect(), }, value: value.bytes().collect(), }) .collect(); // tags must be returned in lexicographical order; when we rename the tags // to use the binary encoding, we fiddle with the existing ordering and need to re-sort. if tag_key_binary_format { res.sort_unstable_by(|a, b| a.key.cmp(&b.key)); } res } fn arcs_to_bytes(s: Vec<Arc<str>>) -> Vec<Vec<u8>> { s.into_iter().map(|s| s.bytes().collect()).collect() } /// Translates FieldList into the gRPC format pub fn fieldlist_to_measurement_fields_response( fieldlist: FieldList, ) -> Result<MeasurementFieldsResponse> { let fields = fieldlist .fields .into_iter() .map(|f| { Ok(MessageField { key: f.name, r#type: datatype_to_measurement_field_enum(&f.data_type)? as i32, timestamp: f.last_timestamp, }) }) .collect::<Result<Vec<_>>>()?; Ok(MeasurementFieldsResponse { fields }) } fn datatype_to_measurement_field_enum(data_type: &ArrowDataType) -> Result<FieldType> { match data_type { ArrowDataType::Float64 => Ok(FieldType::Float), ArrowDataType::Int64 => Ok(FieldType::Integer), ArrowDataType::UInt64 => Ok(FieldType::Unsigned), ArrowDataType::Utf8 => Ok(FieldType::String), ArrowDataType::Boolean => Ok(FieldType::Boolean), _ => UnsupportedFieldTypeSnafu { data_type: data_type.clone(), } .fail(), } } #[cfg(test)] mod tests { use std::fmt; use arrow::{ array::{ ArrayRef, BooleanArray, Float64Array, Int64Array, StringArray, TimestampNanosecondArray, UInt64Array, }, datatypes::DataType as ArrowDataType, record_batch::RecordBatch, }; use futures::TryStreamExt; use iox_query::exec::{ field::FieldIndexes, fieldlist::Field, seriesset::{ series::{Group, Series}, SeriesSet, }, }; use super::*; #[test] fn test_tag_keys_to_byte_vecs() { fn convert_keys(tag_keys: &[&str]) -> Vec<Vec<u8>> { let tag_keys = tag_keys .iter() .map(|s| s.to_string()) .collect::<BTreeSet<_>>(); tag_keys_to_byte_vecs(Arc::new(tag_keys)) } assert_eq!(convert_keys(&[]), vec![[0].to_vec(), [255].to_vec()]); assert_eq!( convert_keys(&["key_a"]), vec![[0].to_vec(), b"key_a".to_vec(), [255].to_vec()] ); assert_eq!( convert_keys(&["key_a", "key_b"]), vec![ [0].to_vec(), b"key_a".to_vec(), b"key_b".to_vec(), [255].to_vec() ] ); } #[tokio::test] async fn test_series_set_conversion() { let series_set = SeriesSet { table_name: Arc::from("the_table"), tags: vec![(Arc::from("tag1"), Arc::from("val1"))], field_indexes: FieldIndexes::from_timestamp_and_value_indexes(5, &[0, 1, 2, 3, 4]), start_row: 1, num_rows: 4, batch: make_record_batch(), }; let series: Vec<Series> = series_set .try_into_series(3) .expect("Correctly converted series set"); let series: Vec<Either> = series.into_iter().map(|s| s.into()).collect(); let frames = series_or_groups_to_frames::<_, ()>( futures::stream::iter(series.clone()).map(Ok), false, ) .try_collect::<Vec<_>>() .await .unwrap(); let dumped_frames = dump_frames(&frames); let expected_frames = vec![ "SeriesFrame, tags: _field=string_field,_measurement=the_table,tag1=val1, type: 4", "StringPointsFrame, timestamps: [2000, 3000, 4000], values: bar,baz,bar", "StringPointsFrame, timestamps: [5000], values: baz", "SeriesFrame, tags: _field=int_field,_measurement=the_table,tag1=val1, type: 1", "IntegerPointsFrame, timestamps: [2000, 3000, 4000], values: \"2,2,3\"", "IntegerPointsFrame, timestamps: [5000], values: \"3\"", "SeriesFrame, tags: _field=uint_field,_measurement=the_table,tag1=val1, type: 2", "UnsignedPointsFrame, timestamps: [2000, 3000, 4000], values: \"22,22,33\"", "UnsignedPointsFrame, timestamps: [5000], values: \"33\"", "SeriesFrame, tags: _field=float_field,_measurement=the_table,tag1=val1, type: 0", "FloatPointsFrame, timestamps: [2000, 3000, 4000], values: \"20.1,21.1,30.1\"", "FloatPointsFrame, timestamps: [5000], values: \"31.1\"", "SeriesFrame, tags: _field=boolean_field,_measurement=the_table,tag1=val1, type: 3", "BooleanPointsFrame, timestamps: [2000, 3000, 4000], values: false,false,true", "BooleanPointsFrame, timestamps: [5000], values: true", ]; assert_eq!( dumped_frames, expected_frames, "Expected:\n{expected_frames:#?}\nActual:\n{dumped_frames:#?}" ); // // Convert using binary tag key format. // let frames = series_or_groups_to_frames::<_, ()>(futures::stream::iter(series).map(Ok), true) .try_collect::<Vec<_>>() .await .unwrap(); let dumped_frames = dump_frames(&frames); let expected_frames = vec![ "SeriesFrame, tags: \0=the_table,tag1=val1,�=string_field, type: 4", "StringPointsFrame, timestamps: [2000, 3000, 4000], values: bar,baz,bar", "StringPointsFrame, timestamps: [5000], values: baz", "SeriesFrame, tags: \0=the_table,tag1=val1,�=int_field, type: 1", "IntegerPointsFrame, timestamps: [2000, 3000, 4000], values: \"2,2,3\"", "IntegerPointsFrame, timestamps: [5000], values: \"3\"", "SeriesFrame, tags: \0=the_table,tag1=val1,�=uint_field, type: 2", "UnsignedPointsFrame, timestamps: [2000, 3000, 4000], values: \"22,22,33\"", "UnsignedPointsFrame, timestamps: [5000], values: \"33\"", "SeriesFrame, tags: \0=the_table,tag1=val1,�=float_field, type: 0", "FloatPointsFrame, timestamps: [2000, 3000, 4000], values: \"20.1,21.1,30.1\"", "FloatPointsFrame, timestamps: [5000], values: \"31.1\"", "SeriesFrame, tags: \0=the_table,tag1=val1,�=boolean_field, type: 3", "BooleanPointsFrame, timestamps: [2000, 3000, 4000], values: false,false,true", "BooleanPointsFrame, timestamps: [5000], values: true", ]; assert_eq!( dumped_frames, expected_frames, "Expected:\n{expected_frames:#?}\nActual:\n{dumped_frames:#?}" ); } #[tokio::test] async fn test_group_group_conversion() { let group = Group { tag_keys: vec![ Arc::from("_field"), Arc::from("_measurement"), Arc::from("tag1"), Arc::from("tag2"), ], partition_key_vals: vec![Arc::from("val1"), Arc::from("val2")], }; let frames = series_or_groups_to_frames::<_, ()>( futures::stream::iter([group.into()]).map(Ok), false, ) .try_collect::<Vec<_>>() .await .unwrap(); let dumped_frames = dump_frames(&frames); let expected_frames = vec![ "GroupFrame, tag_keys: _field,_measurement,tag1,tag2, partition_key_vals: val1,val2", ]; assert_eq!( dumped_frames, expected_frames, "Expected:\n{expected_frames:#?}\nActual:\n{dumped_frames:#?}" ); } #[test] fn test_field_list_conversion() { let input = FieldList { fields: vec![ Field { name: "float".into(), data_type: ArrowDataType::Float64, last_timestamp: 1000, }, Field { name: "int".into(), data_type: ArrowDataType::Int64, last_timestamp: 2000, }, Field { name: "uint".into(), data_type: ArrowDataType::UInt64, last_timestamp: 3000, }, Field { name: "string".into(), data_type: ArrowDataType::Utf8, last_timestamp: 4000, }, Field { name: "bool".into(), data_type: ArrowDataType::Boolean, last_timestamp: 5000, }, ], }; let expected = MeasurementFieldsResponse { fields: vec![ MessageField { key: "float".into(), r#type: FieldType::Float as i32, timestamp: 1000, }, MessageField { key: "int".into(), r#type: FieldType::Integer as i32, timestamp: 2000, }, MessageField { key: "uint".into(), r#type: FieldType::Unsigned as i32, timestamp: 3000, }, MessageField { key: "string".into(), r#type: FieldType::String as i32, timestamp: 4000, }, MessageField { key: "bool".into(), r#type: FieldType::Boolean as i32, timestamp: 5000, }, ], }; let actual = fieldlist_to_measurement_fields_response(input).unwrap(); assert_eq!( actual, expected, "Expected:\n{expected:#?}\nActual:\n{actual:#?}" ); } #[test] fn test_field_list_conversion_error() { let input = FieldList { fields: vec![Field { name: "unsupported".into(), data_type: ArrowDataType::Int8, last_timestamp: 1000, }], }; let result = fieldlist_to_measurement_fields_response(input); match result { Ok(r) => panic!("Unexpected success: {r:?}"), Err(e) => { let expected = "Unsupported field data type in gRPC data translation: Int8"; let actual = format!("{e}"); assert!( actual.contains(expected), "Could not find expected '{expected}' in actual '{actual}'" ); } } } fn make_record_batch() -> RecordBatch { let string_array: ArrayRef = Arc::new(StringArray::from(vec![ "foo", "bar", "baz", "bar", "baz", "foo", ])); let int_array: ArrayRef = Arc::new(Int64Array::from(vec![1, 2, 2, 3, 3, 4])); let uint_array: ArrayRef = Arc::new(UInt64Array::from(vec![11, 22, 22, 33, 33, 44])); let float_array: ArrayRef = Arc::new(Float64Array::from(vec![10.1, 20.1, 21.1, 30.1, 31.1, 40.1])); let bool_array: ArrayRef = Arc::new(BooleanArray::from(vec![ true, false, false, true, true, false, ])); let timestamp_array: ArrayRef = Arc::new(TimestampNanosecondArray::from(vec![ 1000, 2000, 3000, 4000, 5000, 6000, ])); RecordBatch::try_from_iter_with_nullable(vec![ ("string_field", string_array, true), ("int_field", int_array, true), ("uint_field", uint_array, true), ("float_field", float_array, true), ("boolean_field", bool_array, true), ("time", timestamp_array, true), ]) .expect("created new record batch") } /// Wrapper struture that implements [`std::fmt::Display`] for a slice /// of `Frame`s struct DisplayableFrames<'a> { frames: &'a [Frame], } impl<'a> DisplayableFrames<'a> { fn new(frames: &'a [Frame]) -> Self { Self { frames } } } impl<'a> fmt::Display for DisplayableFrames<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { self.frames.iter().try_for_each(|frame| { format_frame(frame, f)?; writeln!(f) }) } } fn dump_frames(frames: &[Frame]) -> Vec<String> { DisplayableFrames::new(frames) .to_string() .trim() .split('\n') .map(|s| s.to_string()) .collect() } fn format_frame(frame: &Frame, f: &mut fmt::Formatter<'_>) -> fmt::Result { let data = &frame.data; match data { Some(Data::Series(SeriesFrame { tags, data_type })) => write!( f, "SeriesFrame, tags: {}, type: {:?}", dump_tags(tags), data_type ), Some(Data::FloatPoints(FloatPointsFrame { timestamps, values })) => write!( f, "FloatPointsFrame, timestamps: {:?}, values: {:?}", timestamps, dump_values(values) ), Some(Data::IntegerPoints(IntegerPointsFrame { timestamps, values })) => write!( f, "IntegerPointsFrame, timestamps: {:?}, values: {:?}", timestamps, dump_values(values) ), Some(Data::UnsignedPoints(UnsignedPointsFrame { timestamps, values })) => write!( f, "UnsignedPointsFrame, timestamps: {:?}, values: {:?}", timestamps, dump_values(values) ), Some(Data::BooleanPoints(BooleanPointsFrame { timestamps, values })) => write!( f, "BooleanPointsFrame, timestamps: {:?}, values: {}", timestamps, dump_values(values) ), Some(Data::StringPoints(StringPointsFrame { timestamps, values })) => write!( f, "StringPointsFrame, timestamps: {:?}, values: {}", timestamps, dump_values(values) ), Some(Data::Group(GroupFrame { tag_keys, partition_key_vals, })) => write!( f, "GroupFrame, tag_keys: {}, partition_key_vals: {}", dump_u8_vec(tag_keys), dump_u8_vec(partition_key_vals) ), None => write!(f, "<NO data field>"), } } fn dump_values<T>(v: &[T]) -> String where T: std::fmt::Display, { v.iter() .map(|item| format!("{item}")) .collect::<Vec<_>>() .join(",") } fn dump_u8_vec(encoded_strings: &[Vec<u8>]) -> String { encoded_strings .iter() .map(|b| String::from_utf8_lossy(b)) .collect::<Vec<_>>() .join(",") } fn dump_tags(tags: &[Tag]) -> String { tags.iter() .map(|tag| { format!( "{}={}", String::from_utf8_lossy(&tag.key), String::from_utf8_lossy(&tag.value), ) }) .collect::<Vec<_>>() .join(",") } }
//! The BSD sockets API requires us to read the `ss_family` field before //! we can interpret the rest of a `sockaddr` produced by the kernel. use super::addr::SocketAddrStorage; #[cfg(unix)] use super::addr::SocketAddrUnix; use super::ext::{in6_addr_new, in_addr_new, sockaddr_in6_new}; use crate::backend::c; use crate::net::{SocketAddrAny, SocketAddrV4, SocketAddrV6}; use core::mem::size_of; pub(crate) unsafe fn write_sockaddr( addr: &SocketAddrAny, storage: *mut SocketAddrStorage, ) -> usize { match addr { SocketAddrAny::V4(v4) => write_sockaddr_v4(v4, storage), SocketAddrAny::V6(v6) => write_sockaddr_v6(v6, storage), #[cfg(unix)] SocketAddrAny::Unix(unix) => write_sockaddr_unix(unix, storage), } } pub(crate) unsafe fn encode_sockaddr_v4(v4: &SocketAddrV4) -> c::sockaddr_in { c::sockaddr_in { #[cfg(any(bsd, target_os = "espidf", target_os = "haiku", target_os = "nto"))] sin_len: size_of::<c::sockaddr_in>() as _, sin_family: c::AF_INET as _, sin_port: u16::to_be(v4.port()), sin_addr: in_addr_new(u32::from_ne_bytes(v4.ip().octets())), #[cfg(not(target_os = "haiku"))] sin_zero: [0; 8_usize], #[cfg(target_os = "haiku")] sin_zero: [0; 24_usize], } } unsafe fn write_sockaddr_v4(v4: &SocketAddrV4, storage: *mut SocketAddrStorage) -> usize { let encoded = encode_sockaddr_v4(v4); core::ptr::write(storage.cast(), encoded); size_of::<c::sockaddr_in>() } pub(crate) unsafe fn encode_sockaddr_v6(v6: &SocketAddrV6) -> c::sockaddr_in6 { #[cfg(any(bsd, target_os = "espidf", target_os = "haiku", target_os = "nto"))] { sockaddr_in6_new( size_of::<c::sockaddr_in6>() as _, c::AF_INET6 as _, u16::to_be(v6.port()), u32::to_be(v6.flowinfo()), in6_addr_new(v6.ip().octets()), v6.scope_id(), ) } #[cfg(not(any(bsd, target_os = "espidf", target_os = "haiku", target_os = "nto")))] { sockaddr_in6_new( c::AF_INET6 as _, u16::to_be(v6.port()), u32::to_be(v6.flowinfo()), in6_addr_new(v6.ip().octets()), v6.scope_id(), ) } } unsafe fn write_sockaddr_v6(v6: &SocketAddrV6, storage: *mut SocketAddrStorage) -> usize { let encoded = encode_sockaddr_v6(v6); core::ptr::write(storage.cast(), encoded); size_of::<c::sockaddr_in6>() } #[cfg(unix)] unsafe fn write_sockaddr_unix(unix: &SocketAddrUnix, storage: *mut SocketAddrStorage) -> usize { core::ptr::write(storage.cast(), unix.unix); unix.len() }
use crate::{list, List}; // conversions macro_rules! ListIdent { [] => { $crate::list::base::Nil }; [$name:ident $(, $names:ident)* $(,)?] => { $crate::list::base::Cons { head: $name, tail: ListIdent![$($names),*] } }; } macro_rules! impl_convert_tuple_list { ($($generics:ident),+ ; $($vars:ident),+) => { impl<$($generics),*> From<($($generics),* ,)> for List![$($generics),*] { fn from(($($vars),* ,): ($($generics),* ,)) -> Self { ListIdent![$($vars),*] } } impl<$($generics),*> From<List![$($generics),*]> for ($($generics),* ,) { fn from(ListIdent![$($vars),*]: List![$($generics),*]) -> Self { ($($vars),* ,) } } } } impl From<()> for List![] { fn from(_: ()) -> Self { list![] } } impl_convert_tuple_list! (E1; e1); impl_convert_tuple_list! (E1, E2; e1, e2); impl_convert_tuple_list! (E1, E2, E3; e1, e2, e3); impl_convert_tuple_list! (E1, E2, E3, E4; e1, e2, e3, e4); impl_convert_tuple_list! (E1, E2, E3, E4, E5; e1, e2, e3, e4, e5); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6; e1, e2, e3, e4, e5, e6); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7; e1, e2, e3, e4, e5, e6, e7); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7, E8; e1, e2, e3, e4, e5, e6, e7, e8); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7, E8, E9; e1, e2, e3, e4, e5, e6, e7, e8, e9); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7, E8, E9, E10; e1, e2, e3, e4, e5, e6, e7, e8, e9, e10); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11; e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12; e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13; e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14; e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15; e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15); impl_convert_tuple_list! (E1, E2, E3, E4, E5, E6, E7, E8, E9, E10, E11, E12, E13, E14, E15, E16; e1, e2, e3, e4, e5, e6, e7, e8, e9, e10, e11, e12, e13, e14, e15, e16);
extern crate failure; #[macro_use] extern crate failure_derive; use failure::{Backtrace, Fail}; #[derive(Fail, Debug)] #[fail(display = "Error code: {}", code)] struct BacktraceError { backtrace: Backtrace, code: u32, } #[test] fn backtrace_error() { let err = BacktraceError { backtrace: Backtrace::new(), code: 7, }; let s = format!("{}", err); assert_eq!(&s[..], "Error code: 7"); assert!(err.backtrace().is_some()); } #[derive(Fail, Debug)] #[fail(display = "An error has occurred.")] struct BacktraceTupleError(Backtrace); #[test] fn backtrace_tuple_error() { let err = BacktraceTupleError(Backtrace::new()); let s = format!("{}", err); assert_eq!(&s[..], "An error has occurred."); assert!(err.backtrace().is_some()); } #[derive(Fail, Debug)] enum BacktraceEnumError { #[fail(display = "Error code: {}", code)] StructVariant { code: i32, backtrace: Backtrace }, #[fail(display = "Error: {}", _0)] TupleVariant(&'static str, Backtrace), #[fail(display = "An error has occurred.")] UnitVariant, } #[test] fn backtrace_enum_error() { let err = BacktraceEnumError::StructVariant { code: 2, backtrace: Backtrace::new(), }; let s = format!("{}", err); assert_eq!(&s[..], "Error code: 2"); assert!(err.backtrace().is_some()); let err = BacktraceEnumError::TupleVariant("foobar", Backtrace::new()); let s = format!("{}", err); assert_eq!(&s[..], "Error: foobar"); assert!(err.backtrace().is_some()); let err = BacktraceEnumError::UnitVariant; let s = format!("{}", err); assert_eq!(&s[..], "An error has occurred."); assert!(err.backtrace().is_none()); }
pub struct BinaryIndexedTree<T, U> { data: Vec<T>, calc: U } impl<T, U> BinaryIndexedTree<T, U> where T: Copy, U: Fn(T, T) -> T { pub fn new(size: usize, e: T, calc: U) -> BinaryIndexedTree<T,U> { let data = vec![e; size+1]; BinaryIndexedTree{ data, calc } } pub fn add(&mut self, index: usize, num: T) { if index >= self.data.len() { panic!("index out of range: {}", self.data.len()/2); } self.add_rec(index + 1, num); } fn add_rec(&mut self, index: usize, num: T) { if index < self.data.len() { self.data[index] = (self.calc)(self.data[index], num); self.add_rec(index + (index & (!index + 1)) , num); } } // index以下の総和を返す pub fn get(&self, index: usize) -> T { if index >= self.data.len() { panic!("index out of range: {}", self.data.len()/2); } self.get_rec(index + 1) } fn get_rec(&self, index: usize) -> T { if index == 0 { self.data[0] }else{ let c = index & (!index + 1); (self.calc)(self.data[index], self.get(index - c)) } } pub fn debug(&self) -> Vec<T> { self.data.clone() } } #[test] fn add_test() { let mut bit = BinaryIndexedTree::new(6, 0, |x, y| x + y); assert_eq!(bit.debug(), vec![0,0,0,0,0,0,0]); bit.add(3, 2); assert_eq!(bit.debug(), vec![0,0,0,0,2,0,0]); bit.add(1, 3); assert_eq!(bit.debug(), vec![0,0,3,0,5,0,0]); bit.add(0, 1); assert_eq!(bit.debug(), vec![0,1,4,0,6,0,0]); bit.add(4, 1); assert_eq!(bit.debug(), vec![0,1,4,0,6,1,1]); } #[test] fn get_test() { let mut bit = BinaryIndexedTree::new(6, 0, |x, y| x + y); assert_eq!(bit.debug(), vec![0,0,0,0,0,0,0]); bit.add(3, 2); assert_eq!(bit.get(3), 0); // assert_eq!(bit.get(3), 2); // assert_eq!(bit.get(4), 2); assert_eq!(bit.debug(), vec![0,0,0,0,2,0,0]); bit.add(1, 3); assert_eq!(bit.debug(), vec![0,0,3,0,5,0,0]); bit.add(0, 1); assert_eq!(bit.debug(), vec![0,1,4,0,6,0,0]); bit.add(4, 1); assert_eq!(bit.debug(), vec![0,1,4,0,6,1,1]); }
use std::iter; use super::{List, Node, Stack}; #[cfg(test)] mod test; impl<T> List<T> { pub fn iter(&self) -> Iter<T> { Iter { next: self.head.as_ref().map(|head| &**head) , len: self.len } } pub fn iter_mut(&mut self) -> IterMut<T> { IterMut { next: self.head.as_mut().map(|head| &mut **head) , len: self.len } } pub fn into_iter(self) -> IntoIter<T> { IntoIter(self) } } pub struct Iter<'a, T: 'a>{ next: Option<&'a Node<T>> , len: usize } impl<'a, T> Iterator for Iter<'a, T> where T: 'a { type Item = &'a T; fn next(&mut self) -> Option<Self::Item> { self.next.map(|node| { self.next = node.next.as_ref() .map(|next| &**next); self.len -= 1; &node.elem }) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.len, Some(self.len)) } } impl<'a, T> iter::ExactSizeIterator for Iter<'a, T> { #[inline] fn len(&self) -> usize { self.len } } pub struct IterMut<'a, T: 'a>{ next: Option<&'a mut Node<T>> , len: usize } impl<'a, T> Iterator for IterMut<'a, T> where T: 'a { type Item = &'a mut T; fn next(&mut self) -> Option<Self::Item> { self.next.take().map(|node| { self.next = node.next.as_mut() .map(|next| &mut **next); self.len -= 1; &mut node.elem }) } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.len, Some(self.len)) } } impl<'a, T> iter::ExactSizeIterator for IterMut<'a, T> { #[inline] fn len(&self) -> usize { self.len } } pub struct IntoIter<T>(List<T>); impl<T> Iterator for IntoIter<T> { type Item = T; #[inline] fn next(&mut self) -> Option<Self::Item> { self.0.pop() } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { (self.0.len, Some(self.0.len)) } } impl<T> iter::ExactSizeIterator for IntoIter<T> { #[inline] fn len(&self) -> usize { self.0.len } }
use amethyst::{ input::is_close_requested, winit::{Event, KeyboardInput, ModifiersState, VirtualKeyCode, WindowEvent}, }; /// Detect whether the program has been requested to close or if macOS quit /// event has been entered. pub fn is_exit_program(event: &Event) -> bool { is_close_requested(&event) || is_macos_quit(&event) } #[cfg(not(target_os = "macos"))] fn is_macos_quit(_event: &Event) -> bool { false } /// Capture the canonical macOS "CMD+Q" shortcut to exit an application. /// /// This function is necessary because Amethyst does not recognize CMD+Q on /// macOS. #[cfg(target_os = "macos")] fn is_macos_quit(event: &Event) -> bool { match event { Event::WindowEvent { event: WindowEvent::KeyboardInput { input: KeyboardInput { virtual_keycode: Some(VirtualKeyCode::Q), modifiers: ModifiersState { logo: true, .. }, .. }, .. }, .. } => true, _ => false, } }
extern crate iron; extern crate mount; #[macro_use] extern crate juniper; extern crate juniper_iron; use std::env; use mount::Mount; use iron::prelude::*; use juniper_iron::{GraphQLHandler, GraphiQLHandler}; use juniper::EmptyMutation; mod models; mod schema; use models::{ System, DiskInformation, LoadAverage, MemoryInformation, ByteUnit, CycleUnit, BootTime }; fn context_factory(_: &mut Request) -> System { System::new() } fn main() { let mut mount = Mount::new(); let graphql_endpoint = GraphQLHandler::new( context_factory, System::new(), EmptyMutation::<System>::new() ); let graphiql_endpoint = GraphiQLHandler::new("/graphql"); mount.mount("/", graphiql_endpoint); mount.mount("/graphql", graphql_endpoint); // TODO: Use cli argument instead of env var? let host = env::var("SYS_GQL_HOST").unwrap_or("localhost:5000".to_owned()); match Iron::new(mount).http(&host) { Ok(_) => println!("Server started on {}", host), Err(e) => println!("Error starting server: {}", e) }; }
use aes_gcm_siv::aead::consts::U32; use aes_gcm_siv::aead::heapless::{consts::U128, Vec}; use aes_gcm_siv::aead::{generic_array::GenericArray, AeadInPlace, NewAead}; use crate::serial_log; use aes_gcm_siv::Aes256GcmSiv; pub fn test_encrypt() -> &'static str { // Not implemented because I'm stupid serial_log("Prekey gen"); let key: GenericArray<u8, U32> = *GenericArray::from_slice(b"an example very very secret key."); serial_log("Pre cipher gen"); let cipher = Aes256GcmSiv::new(&key); //gets stuck here forever serial_log("pre nonce"); let nonce = GenericArray::from_slice(b"unique nonce"); // 96-bits; unique per message let mut buffer: Vec<u8, U128> = Vec::new(); let buf_result = buffer.extend_from_slice(b"plaintext message"); // match buf_result { // Ok(()) => { // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext cipher .encrypt_in_place(nonce, b"", &mut buffer) .expect("encryption failure!"); // `buffer` now contains the message ciphertext assert_ne!(&buffer, b"plaintext message"); // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext cipher .decrypt_in_place(nonce, b"", &mut buffer) .expect("decryption failure!"); assert_eq!(&buffer, b"plaintext message"); return "ok"; /* } Err(_e) => return "Encryption Failure", }*/ return "ERROR: ENCRYPTION NOT POSSIBLE"; } pub fn encrypt() {}
use pine::libs; use pine::runtime::data_src::{Callback, DataSrc}; use pine::types::Float; use pyo3::exceptions; use pyo3::prelude::*; use pyo3::types::PyList; use pyo3::wrap_pyfunction; use std::collections::HashMap; struct PyCallbackObj<'p> { pyobj: PyObject, py: Python<'p>, } impl<'p> Callback for PyCallbackObj<'p> { fn print(&self, _str: String) { let print_method = self.pyobj.getattr(self.py, "print"); let result = print_method.unwrap().call(self.py, (_str,), None).unwrap(); } fn plot(&self, floats: Vec<f64>) { let plot_method = self.pyobj.getattr(self.py, "plot"); let result = plot_method.unwrap().call(self.py, (floats,), None).unwrap(); } } #[pyfunction] /// Formats the sum of two numbers as string fn load_script(py: Python, script: String, close: Vec<f64>, callbacks: PyObject) -> PyResult<()> { let mut script_block = pine::parse_all(&script).unwrap(); let inner_vars = libs::declare_vars(); let callback = PyCallbackObj { pyobj: callbacks, py, }; let mut datasrc = DataSrc::new(&mut script_block, inner_vars, &callback); let mut data = HashMap::new(); let close_val: Vec<Float> = close.into_iter().map(|s| Some(s)).collect(); data.insert("close", close_val); match datasrc.run(data) { Ok(_) => Ok(()), Err(err) => Err(PyErr::new::<exceptions::TypeError, _>(format!( "Err {:?}", err ))), } } /// This module is a python module implemented in Rust. #[pymodule] fn pine_py(py: Python, m: &PyModule) -> PyResult<()> { m.add_wrapped(wrap_pyfunction!(load_script))?; Ok(()) }
use serde::{Deserialize, Serialize}; use serde_json::Result; use std::cell::Cell; use std::collections::HashMap; use std::fs::File; use std::io::Read; use string_template::Template; thread_local!(static OPTION_ID: Cell<usize> = Cell::new(0)); fn next_option_id() -> usize { OPTION_ID.with(|id| { let result = id.get(); id.set(result + 1); result }) } #[derive(Serialize, Deserialize, Debug, Clone, Default)] pub struct GrunnerChoiceType { #[serde(skip, default = "next_option_id")] pub id: usize, pub label: String, #[serde(default)] pub args: Vec<String>, #[serde(default)] pub replacements: HashMap<String, String>, } #[derive(Serialize, Deserialize, Debug, Clone)] #[serde(tag = "type", rename_all = "lowercase")] pub struct GrunnerOption { pub(crate) name: String, pub(crate) choices: Vec<GrunnerChoiceType>, #[serde(skip)] pub(crate) selected: Option<usize>, } impl GrunnerOption { pub fn get_choice(&self) -> GrunnerChoiceType { if let Some(idx) = self.selected { self.choices[idx].clone() } else { GrunnerChoiceType::default() } } pub fn get_choices(&self) -> &Vec<GrunnerChoiceType> { &self.choices } pub fn get_arg(&self) -> Vec<String> { self.get_choice().args } pub fn get_name(&self) -> &str { self.name.as_str() } pub fn get_replacements(&self) -> HashMap<String, String> { self.get_choice().replacements } } #[derive(Serialize, Deserialize, Debug, Clone)] pub struct GrunnerAction { pub name: String, pub execute: String, #[serde(default)] pub args: Vec<String>, #[serde(default)] pub use_options: Vec<String>, #[serde(default)] pub success_sound: Option<String>, #[serde(default)] pub fail_sound: Option<String>, #[serde(skip)] pub options: Vec<String>, #[serde(skip)] pub gui_state: iced::button::State, } impl GrunnerAction { pub fn set_selected_options(&mut self, opts: Vec<String>) { self.options = opts; } pub fn apply_replacement_map(&mut self, reps: &HashMap<String, String>) { // Format necessary strings based on selected options let fixed_map: HashMap<&str, &str> = reps .iter() .map(|(k, v)| (k.as_str(), v.as_str())) .collect::<HashMap<&str, &str>>(); let template = Template::new(&self.execute); let new_execute = template.render(&fixed_map); self.execute = new_execute; for arg in self.args.iter_mut() { let arg_template = Template::new(arg); let new_arg = arg_template.render(&fixed_map); *arg = new_arg; } } } #[derive(Serialize, Deserialize, Debug)] pub struct GrunnerSection { pub label: String, #[serde(default)] pub options: Vec<GrunnerOption>, pub actions: Vec<GrunnerAction>, } #[derive(Serialize, Deserialize, Debug)] pub struct GrunnerConfig { pub sections: Vec<GrunnerSection>, } pub fn load_grunner_config<S>(path: S) -> Result<GrunnerConfig> where S: Into<String>, { let mut file = File::open(path.into()).unwrap(); let mut data = String::new(); file.read_to_string(&mut data).unwrap(); let config: GrunnerConfig = serde_json::from_str(&data).unwrap(); Ok(config) }
//! # Naia Server //! A server that uses either UDP or WebRTC communication to send/receive events //! to/from connected clients, and syncs registered actors to clients to whom //! those actors are in-scope. #![deny( missing_docs, trivial_casts, trivial_numeric_casts, unsafe_code, unstable_features, unused_import_braces )] #[macro_use] extern crate log; #[macro_use] extern crate slotmap; #[cfg(all(feature = "use-udp", feature = "use-webrtc"))] compile_error!("Naia Server can only use UDP or WebRTC, you must pick one"); #[cfg(all(not(feature = "use-udp"), not(feature = "use-webrtc")))] compile_error!("Naia Server requires either the 'use-udp' or 'use-webrtc' feature to be enabled, you must pick one."); pub use naia_shared::{ find_my_ip_address, Actor, ActorType, LinkConditionerConfig, Random, SharedConfig, }; mod actors; mod client_connection; mod command_receiver; mod error; mod interval; mod naia_server; mod ping_manager; mod room; mod server_config; mod server_event; mod server_packet_writer; mod server_tick_manager; mod user; pub use actors::actor_key::actor_key::ActorKey; pub use naia_server::{NaiaServer, ServerAddresses}; pub use room::room_key::RoomKey; pub use server_config::ServerConfig; pub use server_event::ServerEvent; pub use user::user_key::UserKey;
extern crate reqwest; extern crate serde_json; use std::fs::File; use std::io::{BufReader, BufRead}; fn main() { let key = read_file("accessKey.txt"); let group = read_file("groupNumber.txt"); let url = format!("https://api.groupme.com/v3/groups/{}", group); let name = "eric"; let id = get_user_id(&url, &key, name); println!("{:?}", id); } fn read_file(filename: &str) -> String { let file = File::open(filename).unwrap(); let buffered = BufReader::new(file); let mut contents = String::new(); for line in buffered.lines() { contents = contents + line.unwrap().as_str(); } contents } fn get_user_id(url: &String, key: &String, name: &str) -> String{ let res = reqwest::get(&format!("{}?token={}", url, key)).unwrap().text().unwrap(); let values: serde_json::Value = serde_json::from_str(res.as_str()).unwrap(); let values: Vec<_> = values["response"]["members"].as_array().unwrap().iter().filter(|person| { let val = person["nickname"].as_str().unwrap().to_lowercase().contains(name); println!("{}", val); val }).collect(); println!("{:?}", values); String::from(values[0]["id"].as_str().unwrap()) } fn try_to_remove(url: &String, key: &String, id: &str) { let client = reqwest::Client::new(); let response = ""; }
extern crate matrix; use matrix::prelude::*; use std::collections::VecDeque; use std::vec::Vec; // Implements a breadth-first search traversal of a given graph // Input: Graph g = <v, e> // Output: Graph g with its vertices marked with consecutive integers in the // order they are visited by the BFS traversal fn breadth_first_search(g: &Compressed<u8>) -> Compressed<u8> { let mut c = Compressed::<u8>::zero((g.rows(), g.columns())); let mut count = 0; let mut vertices = vec![0; g.rows()]; for i in 0..g.rows() { if vertices[i] == 0 { breadth_first_search_vertex(g, &mut c, &mut vertices, i, &mut count); } } c } // Visits all the unvisited vertices connected to vertex v by a path and // numbers them in the order they are visited via global variable count fn breadth_first_search_vertex(g: &Compressed<u8>, g_f: &mut Compressed<u8>, v_set: &mut Vec<u8>, v: usize, count: &mut u8) { *count = *count + 1; v_set[v] = *count; let mut q = VecDeque::<u8>::new(); q.push_back(v as u8); while !q.is_empty() { let front = *q.front().unwrap() as usize; for i in 0..g.columns() { if g.get((front, i)) == 1 && v_set[i] == 0 { g_f.set((front, i), 1); *count = *count + 1; v_set[i] = *count; q.push_back(i as u8); } } q.pop_front(); } } fn main() { // use example graph from book (Figure 3.11) // represent graph with adjacency matrix let mut graph = Compressed::<u8>::zero((10, 10)); // a graph.set((0, 2), 1); graph.set((0, 3), 1); graph.set((0, 4), 1); // b graph.set((1, 4), 1); graph.set((1, 5), 1); // c graph.set((2, 0), 1); graph.set((2, 3), 1); graph.set((2, 5), 1); // d graph.set((3, 0), 1); graph.set((3, 2), 1); // e graph.set((4, 0), 1); graph.set((4, 1), 1); graph.set((4, 5), 1); // f graph.set((5, 1), 1); graph.set((5, 2), 1); graph.set((5, 4), 1); // g graph.set((6, 7), 1); graph.set((6, 9), 1); // h graph.set((7, 6), 1); graph.set((7, 8), 1); // i graph.set((8, 7), 1); graph.set((8, 9), 1); // j graph.set((9, 6), 1); graph.set((9, 8), 1); let final_graph = breadth_first_search(&graph); println!("Edges in BFS Forest:"); for x in 0..10 { for y in 0..10 { if final_graph.get((x, y)) == 1 { println!("\t {} to {}", x, y); } } } }
pub mod binomial; pub mod digits; pub mod factorial; pub mod fibonacci; pub mod fraction; pub mod helper; pub mod modulo; pub mod partition; pub mod permutation; pub mod primes; pub mod square_roots;
// Generated by ./import-tests.sh mod unittest; mod unittest_arena; mod unittest_drop_unknown_fields; mod unittest_embed_optimize_for; mod unittest_import; mod unittest_import_lite; mod unittest_import_public; mod unittest_import_public_lite; mod unittest_lite; mod unittest_lite_imports_nonlite; mod unittest_mset; mod unittest_mset_wire_format; mod unittest_no_arena; mod unittest_no_arena_import; mod unittest_no_arena_lite; mod unittest_no_field_presence; mod unittest_no_generic_services; mod unittest_optimize_for; mod unittest_preserve_unknown_enum; mod unittest_preserve_unknown_enum2; mod unittest_proto3_arena; mod unittest_proto3_arena_lite; mod unittest_proto3_lite; mod unittest_well_known_types;
/// Contoh implementasi alternative overloading method di rust /// yaitu dengan menggunakan generik trait /// // buat struk kosongan struct Detector; // buat generic trait trait Detect<T> { fn detect(input: T); } // implementasi trait untuk tipe integer 32 impl Detect<i32> for Detector { fn detect(input: i32) { println!("{} is i32", input); } } // implementasi trait untuk tipe string impl Detect<&'static str> for Detector { fn detect(input: &'static str) { println!("{} is &str", input); } } fn main() { Detector::detect(10); Detector::detect("Hello"); }
extern crate dotenv; #[macro_use] extern crate diesel; #[macro_use] extern crate serde; use std::io; use dotenv::dotenv; use actix_web::{middleware, web, App, HttpServer}; use diesel_migrations::run_pending_migrations; mod db; mod schema; mod schema_graphql; mod models; mod handlers; use crate::db::establish_connection; use crate::schema_graphql::create_schema; use crate::models::key::Key; use crate::handlers::graphql::{playground, graphql}; #[actix_rt::main] async fn main() -> io::Result<()> { // load .env variables dotenv().ok(); let host = std::env::var("HOST").expect("Missing `HOST` env variable"); let port = std::env::var("PORT").expect("Missing `PORT` env variable"); let key = std::env::var("API_KEY").expect("Missing `API_KEY` env variable"); let key = Key::new(key); // configure logging std::env::set_var("RUST_LOG", "actix_web=info"); env_logger::init(); // create Juniper schema let schema = std::sync::Arc::new(create_schema()); // database connection pool let db_pool = establish_connection(); // run pending migrations let connection = db_pool.get().unwrap(); run_pending_migrations(&connection).map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?; // start http server HttpServer::new(move || { App::new() .data(db_pool.clone()) .data(schema.clone()) .data(key.clone()) .wrap(middleware::Logger::default()) .service(web::resource("/graphql").route(web::post().to(graphql))) .service(web::resource("/playground").route(web::get().to(playground))) }) .bind(format!("{}:{}", host, port))? .run() .await }
use serde_derive::{Deserialize, Serialize}; #[derive(Debug, PartialEq, Eq, Serialize, Deserialize, Copy, Clone)] pub enum AccountType { Assets, Liabilities, Equities, Revenue, Expenses, Gains, Losses, } impl AccountType { pub fn from_i32(value: i32) -> AccountType { match value { 0 => AccountType::Assets, 1 => AccountType::Liabilities, 2 => AccountType::Equities, 3 => AccountType::Revenue, 4 => AccountType::Expenses, 5 => AccountType::Gains, 6 => AccountType::Losses, _ => panic!("Unknown value: {}", value), } } } #[derive(Debug, Serialize)] pub struct Account { pub id: i32, pub acc_type: AccountType, pub name: String, pub currency: String, } impl Account { pub fn currency_compatible(&self, other: &Account) -> bool { if self.currency != other.currency { return false; } true } } #[derive(Debug, Serialize)] pub struct DetailedAccount { pub id: i32, pub acc_type: AccountType, pub name: String, pub balance: i32, pub currency: String, } #[derive(Debug, Serialize, Deserialize)] pub struct NewAccount { pub acc_type: i32, pub name: String, pub currency: String, } #[cfg(test)] mod tests { use super::*; #[test] fn accounttype_correctly_types() { let asset = AccountType::from_i32(0); let liabilities = AccountType::from_i32(1); let equities = AccountType::from_i32(2); let revenue = AccountType::from_i32(3); let expenses = AccountType::from_i32(4); let gains = AccountType::from_i32(5); let losses = AccountType::from_i32(6); assert_eq!(asset, AccountType::Assets); assert_eq!(liabilities, AccountType::Liabilities); assert_eq!(equities, AccountType::Equities); assert_eq!(revenue, AccountType::Revenue); assert_eq!(expenses, AccountType::Expenses); assert_eq!(gains, AccountType::Gains); assert_eq!(losses, AccountType::Losses) } }
#[macro_use] extern crate failure; extern crate fnv; #[macro_use] extern crate lazy_static; extern crate num_traits; #[macro_use] extern crate gc_arena; pub mod compiler; pub mod conversion; pub mod function; pub mod lexer; pub mod opcode; pub mod operators; pub mod parser; pub mod state; pub mod string; pub mod table; pub mod thread; pub mod value; #[cfg(test)] mod tests;
//! Functions for stuff use std::cmp::Ordering::*; use std::f32; use std::str::from_utf8_unchecked; use crate::evaluate; use crate::hamming::*; use crate::xor; /// Finds the key for a cipher text that was encrypted with a one-byte key. pub fn single_xor(encrypted: &[u8]) -> (String, u8, f32) { let mut best_value: String = String::new(); let mut best_key: u8 = 0; let mut best_score: f32 = f32::INFINITY; for i in 0..255 as u8 { let key = vec![i; encrypted.len()]; let result = xor::xor(encrypted, &key); let score = evaluate::evaluate(&result); let str_result = unsafe { from_utf8_unchecked(&result).to_string() }; if score < best_score { best_score = score; best_key = i; best_value = str_result; } } (best_value, best_key, best_score) } pub fn best_repeating_xor_keys(buffer: &[u8]) -> Vec<Box<[u8]>> { let key_sizes = guess_key_size(buffer); let mut keys: Vec<Box<[u8]>> = Vec::new(); for key_size in key_sizes.iter() { let transposed = transpose_blocks(buffer, *key_size); let best_keys = transposed .iter() .map(|col| find_best_single_key(&col)) .collect::<Vec<u8>>() .into_boxed_slice(); keys.push(best_keys); } keys } /// Finds the most likely key sizes in a cipher text (between 2 and 40). Returns the 3 most likely /// values. /// /// Compares the hamming distance between the first few blocks for a range of possibilities. fn guess_key_size(buffer: &[u8]) -> Box<[usize]> { const N_BLOCKS: usize = 4; const MAX_KEY_SIZE: usize = 40; if buffer.len() < MAX_KEY_SIZE * N_BLOCKS { panic!("Buffer too short to determine key size"); } let score = |key_size: usize| { let mut total_distance = 0; let first_block = &buffer[0..key_size]; for i in 1..N_BLOCKS { let second_block = &buffer[i * key_size..(i + 1) * key_size]; total_distance += bit_hamming(first_block, second_block); } total_distance as f64 / (key_size as f64) }; let mut res = (2_usize..MAX_KEY_SIZE) .map(|i| (i, score(i))) .collect::<Vec<(usize, f64)>>(); res.sort_by(|(_i, si), (_j, sj)| si.partial_cmp(sj).unwrap_or(Equal)); res.iter() .map(|(i, _si)| *i) .take(3) .collect::<Vec<usize>>() .into_boxed_slice() } /// Helper function to return the best single key fn find_best_single_key(encrypted: &[u8]) -> u8 { let (_val, key, _score) = single_xor(encrypted); key } fn transpose_blocks(buffer: &[u8], key_length: usize) -> Vec<Vec<u8>> { let mut transposed: Vec<Vec<u8>> = Vec::with_capacity(key_length); for _i in 0..key_length { transposed.push(Vec::new()); } for (i, c) in buffer.iter().enumerate() { let block = i % key_length; transposed[block].push(*c); } transposed } #[cfg(test)] mod test { use super::*; use crate::hex_io::*; use std::str::from_utf8; #[test] fn test_transpose() { assert_eq!( transpose_blocks(&[0, 1, 2, 3, 4], 2), vec![vec![0, 2, 4], vec![1, 3]] ) } const CHALLENGE_3_DATA: &'static str = "1b37373331363f78151b7f2b783431333d78397828372d363c78373e783a393b3736"; #[test] fn challenge_3() { let (res, key, _score) = single_xor(&hex_string_to_bytes(CHALLENGE_3_DATA).unwrap()); assert_eq!(key, 88); assert_eq!(&res, "Cooking MC's like a pound of bacon"); } #[test] fn challenge_4() { let lines = read_hex_file("data/4.txt").unwrap(); let (best_result, _best_key, _best_score) = lines .into_iter() .map(|l| single_xor(&l)) .min_by(|(_v1, _k1, s1), (_v2, _k2, s2)| s1.partial_cmp(s2).unwrap_or(Equal)) .unwrap(); assert_eq!(&best_result, "Now that the party is jumping\n"); } #[test] fn challenge_6_2() { let test_data = load_b64_from_file("data/6.txt").unwrap(); let best_keys = best_repeating_xor_keys(&test_data); let mut decoded: Vec<Box<[u8]>> = Vec::new(); for key in best_keys { decoded.push(xor::rep_key_xor(&test_data, &key)); } let best = decoded .iter() .map(|d| (d, evaluate::evaluate(&d))) .min_by(|(_a, sa), (_b, sb)| sa.partial_cmp(sb).unwrap_or(Equal)) .unwrap(); let expected_result = "I\'m back and I\'m ringin\' the bell"; assert_eq!( &from_utf8(best.0).unwrap()[0..expected_result.len()], expected_result ); } }
use std::fs; use std::env; use std::path::Path; fn main() { let tmp = match env::var("TEMP") { Ok(name) => name, Err(_e) => r#"C:\Users\susilo\AppData\Local\Temp"#.to_owned(), }; let hello_rust = format!("{}\\hello_rust", tmp); let _ = fs::create_dir(&hello_rust); if Path::new(&hello_rust).exists() { println!("Folder exist"); } else { println!("Folder tidak ada!"); } }
use crate::tile::Tile; use crate::tile::TileType; use std::slice::IterMut; use std::slice::Iter; pub struct World { tiles: Vec::<Tile>, width: usize, height: usize } impl World { pub fn new(width: usize, height: usize) -> World { let mut tiles: Vec<Tile> = Vec::new(); for i in 0..(width*height) { tiles.push(Tile::new((i % width) as i32, (i / width) as i32, TileType::Dirt)); } World { tiles: tiles, width: width, height: height } } pub fn iter(&self) -> Iter<Tile> { self.tiles.iter() } pub fn iter_mut(&mut self) -> IterMut<Tile> { self.tiles.iter_mut() } //XXX range checks pub fn tile_at(&self, x: usize, y: usize) -> &Tile { &self.tiles.as_slice()[y*self.width + x] } pub fn tile_at_mut(&mut self, x: usize, y: usize) -> &mut Tile { &mut self.tiles.as_mut_slice()[y*self.width + x] } }
use anyhow::{bail, Context, Result}; use flate2::read::GzDecoder; use fs_err::File; use mailparse::parse_mail; use regex::Regex; use std::io::{BufReader, Read}; use std::path::{Path, PathBuf}; use zip::ZipArchive; fn filename_from_file(path: impl AsRef<Path>) -> Result<String> { Ok(path .as_ref() .file_name() .context("Missing filename")? .to_str() .context("Expected a utf-8 filename")? .to_string()) } /// Read the email format into key value pairs fn metadata_from_bytes(metadata_email: &mut Vec<u8>) -> Result<Vec<(String, String)>> { let metadata_email = parse_mail(&metadata_email).context("Failed to parse METADATA")?; let mut metadata = Vec::new(); for header in &metadata_email.headers { metadata.push((header.get_key().to_string(), header.get_value().to_string())); } let body = metadata_email .get_body() .context("Failed to parse METADATA")?; if !body.trim().is_empty() { metadata.push(("Description".into(), body)); } Ok(metadata) } /// Port of pip's `canonicalize_name` /// https://github.com/pypa/pip/blob/b33e791742570215f15663410c3ed987d2253d5b/src/pip/_vendor/packaging/utils.py#L18-L25 fn canonicalize_name(name: &str) -> String { Regex::new("[-_.]+") .unwrap() .replace(name, "-") .to_lowercase() } /// Reads the METADATA file in the .dist-info directory of a wheel, returning /// the metadata (https://packaging.python.org/specifications/core-metadata/) /// as key value pairs fn read_metadata_for_wheel(path: impl AsRef<Path>) -> Result<Vec<(String, String)>> { let filename = filename_from_file(&path)? .strip_suffix(".whl") // We checked that before entering this function .unwrap() .to_string(); let parts: Vec<_> = filename.split('-').collect(); let dist_name_version = match parts.as_slice() { [name, version, _python_tag, _abi_tag, _platform_tag] => format!("{}-{}", name, version), _ => bail!("The wheel name is invalid: {}", filename), }; let reader = BufReader::new(File::open(path.as_ref())?); let mut archive = ZipArchive::new(reader).context("Failed to read file as zip")?; // The METADATA format is an email (RFC 822) // pip's implementation: https://github.com/pypa/pip/blob/b33e791742570215f15663410c3ed987d2253d5b/src/pip/_internal/utils/wheel.py#L109-L144 // twine's implementation: https://github.com/pypa/twine/blob/534385596820129b41cbcdcc83d34aa8788067f1/twine/wheel.py#L52-L56 // We mostly follow pip let name = format!("{}.dist-info/METADATA", dist_name_version); let mut metadata_email = Vec::new(); // Find the metadata file let metadata_files: Vec<_> = archive .file_names() .filter(|i| canonicalize_name(i) == canonicalize_name(&name)) .map(ToString::to_string) .collect(); match &metadata_files.as_slice() { [] => bail!( "This wheel does not contain a METADATA matching {}, which is mandatory for wheels", name ), [metadata_file] => archive .by_name(&metadata_file) .context(format!("Failed to read METADATA file {}", metadata_file))? .read_to_end(&mut metadata_email) .context(format!("Failed to read METADATA file {}", metadata_file))?, files => bail!( "Found more than one metadata file matching {}: {:?}", name, files ), }; metadata_from_bytes(&mut metadata_email) } /// Returns the metadata for a source distribution (.tar.gz). /// Only parses the filename since dist-info is not part of source /// distributions fn read_metadata_for_source_distribution(path: impl AsRef<Path>) -> Result<Vec<(String, String)>> { let mut reader = tar::Archive::new(GzDecoder::new(BufReader::new(File::open(path.as_ref())?))); // Unlike for wheels, in source distributions the metadata is stored in a file called PKG-INFO // try_find would be ideal here, but it's nightly only let mut entry = reader .entries()? .map(|entry| -> Result<_> { let entry = entry?; if entry.path()? == PathBuf::from("PKG-INFO") { Ok(Some(entry)) } else { Ok(None) } }) .find_map(|x| x.transpose()) .context(format!( "Source distribution {:?} does not contain a PKG-INFO, but it should", path.as_ref() ))? .context(format!("Failed to read {:?}", path.as_ref()))?; let mut metadata_email = Vec::new(); entry .read_to_end(&mut metadata_email) .context(format!("Failed to read {:?}", path.as_ref()))?; metadata_from_bytes(&mut metadata_email) } /// Returns the metadata as key value pairs for a wheel or a source distribution pub fn get_metadata_for_distribution(path: &Path) -> Result<Vec<(String, String)>> { let filename = filename_from_file(path)?; if filename.ends_with(".whl") { read_metadata_for_wheel(path) .context(format!("Failed to read metadata from wheel at {:?}", path)) } else if filename.ends_with(".tar.gz") { read_metadata_for_source_distribution(path).context(format!( "Failed to read metadata from source distribution at {:?}", path )) } else { bail!("File has an unknown extension: {:?}", path) } } #[cfg(test)] mod test { use super::*; #[test] fn test_source_distribution() { let metadata = get_metadata_for_distribution(Path::new("test-data/pyo3_mixed-2.1.1.tar.gz")).unwrap(); let expected: Vec<_> = [ ("Metadata-Version", "2.1"), ("Name", "pyo3-mixed"), ("Version", "2.1.1"), ("Summary", "Implements a dummy function combining rust and python"), ("Author", "konstin <konstin@mailbox.org>"), ("Author-Email", "konstin <konstin@mailbox.org>"), ("Description-Content-Type", "text/markdown; charset=UTF-8; variant=GFM"), ("Description", "# pyo3-mixed\n\nA package for testing maturin with a mixed pyo3/python project.\n\n"), ].iter().map(|(k,v)| (k.to_string(), v.to_string())).collect(); assert_eq!(metadata, expected); } #[test] fn test_wheel() { let metadata = get_metadata_for_distribution(Path::new( "test-data/pyo3_mixed-2.1.1-cp38-cp38-manylinux1_x86_64.whl", )) .unwrap(); assert_eq!( metadata.iter().map(|x| &x.0).collect::<Vec::<&String>>(), vec![ "Metadata-Version", "Name", "Version", "Summary", "Author", "Author-Email", "Description-Content-Type", "Description" ] ); // Check the description assert!(metadata[7].1.starts_with("# pyo3-mixed")); assert!(metadata[7].1.ends_with("tox.ini\n\n")); } }
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT. pub fn parse_http_generic_error( response: &http::Response<bytes::Bytes>, ) -> Result<smithy_types::Error, smithy_json::deserialize::Error> { crate::json_errors::parse_generic_error(response.body(), response.headers()) } pub fn deser_structure_conflict_exceptionjson_err( input: &[u8], mut builder: crate::error::conflict_exception::Builder, ) -> Result<crate::error::conflict_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_connector_authentication_exceptionjson_err( input: &[u8], mut builder: crate::error::connector_authentication_exception::Builder, ) -> Result< crate::error::connector_authentication_exception::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_internal_server_exceptionjson_err( input: &[u8], mut builder: crate::error::internal_server_exception::Builder, ) -> Result<crate::error::internal_server_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_service_quota_exceeded_exceptionjson_err( input: &[u8], mut builder: crate::error::service_quota_exceeded_exception::Builder, ) -> Result<crate::error::service_quota_exceeded_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_validation_exceptionjson_err( input: &[u8], mut builder: crate::error::validation_exception::Builder, ) -> Result<crate::error::validation_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_create_connector_profile( input: &[u8], mut builder: crate::output::create_connector_profile_output::Builder, ) -> Result<crate::output::create_connector_profile_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "connectorProfileArn" => { builder = builder.set_connector_profile_arn( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_connector_server_exceptionjson_err( input: &[u8], mut builder: crate::error::connector_server_exception::Builder, ) -> Result<crate::error::connector_server_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_resource_not_found_exceptionjson_err( input: &[u8], mut builder: crate::error::resource_not_found_exception::Builder, ) -> Result<crate::error::resource_not_found_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_create_flow( input: &[u8], mut builder: crate::output::create_flow_output::Builder, ) -> Result<crate::output::create_flow_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "flowArn" => { builder = builder.set_flow_arn( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "flowStatus" => { builder = builder.set_flow_status( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::FlowStatus::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_connector_entity( input: &[u8], mut builder: crate::output::describe_connector_entity_output::Builder, ) -> Result<crate::output::describe_connector_entity_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "connectorEntityFields" => { builder = builder.set_connector_entity_fields( crate::json_deser::deser_list_connector_entity_field_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_connector_profiles( input: &[u8], mut builder: crate::output::describe_connector_profiles_output::Builder, ) -> Result< crate::output::describe_connector_profiles_output::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "connectorProfileDetails" => { builder = builder.set_connector_profile_details( crate::json_deser::deser_list_connector_profile_detail_list(tokens)?, ); } "nextToken" => { builder = builder.set_next_token( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_connectors( input: &[u8], mut builder: crate::output::describe_connectors_output::Builder, ) -> Result<crate::output::describe_connectors_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "connectorConfigurations" => { builder = builder.set_connector_configurations( crate::json_deser::deser_map_connector_configurations_map(tokens)?, ); } "nextToken" => { builder = builder.set_next_token( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_flow( input: &[u8], mut builder: crate::output::describe_flow_output::Builder, ) -> Result<crate::output::describe_flow_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "createdAt" => { builder = builder.set_created_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "createdBy" => { builder = builder.set_created_by( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "description" => { builder = builder.set_description( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destinationFlowConfigList" => { builder = builder.set_destination_flow_config_list( crate::json_deser::deser_list_destination_flow_config_list(tokens)?, ); } "flowArn" => { builder = builder.set_flow_arn( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "flowName" => { builder = builder.set_flow_name( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "flowStatus" => { builder = builder.set_flow_status( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::FlowStatus::from(u.as_ref())) }) .transpose()?, ); } "flowStatusMessage" => { builder = builder.set_flow_status_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "kmsArn" => { builder = builder.set_kms_arn( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "lastRunExecutionDetails" => { builder = builder.set_last_run_execution_details( crate::json_deser::deser_structure_execution_details(tokens)?, ); } "lastUpdatedAt" => { builder = builder.set_last_updated_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "lastUpdatedBy" => { builder = builder.set_last_updated_by( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "sourceFlowConfig" => { builder = builder.set_source_flow_config( crate::json_deser::deser_structure_source_flow_config(tokens)?, ); } "tags" => { builder = builder.set_tags(crate::json_deser::deser_map_tag_map(tokens)?); } "tasks" => { builder = builder.set_tasks(crate::json_deser::deser_list_tasks(tokens)?); } "triggerConfig" => { builder = builder.set_trigger_config( crate::json_deser::deser_structure_trigger_config(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_describe_flow_execution_records( input: &[u8], mut builder: crate::output::describe_flow_execution_records_output::Builder, ) -> Result< crate::output::describe_flow_execution_records_output::Builder, smithy_json::deserialize::Error, > { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "flowExecutions" => { builder = builder.set_flow_executions( crate::json_deser::deser_list_flow_execution_list(tokens)?, ); } "nextToken" => { builder = builder.set_next_token( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_list_connector_entities( input: &[u8], mut builder: crate::output::list_connector_entities_output::Builder, ) -> Result<crate::output::list_connector_entities_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "connectorEntityMap" => { builder = builder.set_connector_entity_map( crate::json_deser::deser_map_connector_entity_map(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_list_flows( input: &[u8], mut builder: crate::output::list_flows_output::Builder, ) -> Result<crate::output::list_flows_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "flows" => { builder = builder.set_flows(crate::json_deser::deser_list_flow_list(tokens)?); } "nextToken" => { builder = builder.set_next_token( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_list_tags_for_resource( input: &[u8], mut builder: crate::output::list_tags_for_resource_output::Builder, ) -> Result<crate::output::list_tags_for_resource_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "tags" => { builder = builder.set_tags(crate::json_deser::deser_map_tag_map(tokens)?); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_start_flow( input: &[u8], mut builder: crate::output::start_flow_output::Builder, ) -> Result<crate::output::start_flow_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "executionId" => { builder = builder.set_execution_id( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "flowArn" => { builder = builder.set_flow_arn( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "flowStatus" => { builder = builder.set_flow_status( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::FlowStatus::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_structure_unsupported_operation_exceptionjson_err( input: &[u8], mut builder: crate::error::unsupported_operation_exception::Builder, ) -> Result<crate::error::unsupported_operation_exception::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "message" => { builder = builder.set_message( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_stop_flow( input: &[u8], mut builder: crate::output::stop_flow_output::Builder, ) -> Result<crate::output::stop_flow_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "flowArn" => { builder = builder.set_flow_arn( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "flowStatus" => { builder = builder.set_flow_status( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::FlowStatus::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_update_connector_profile( input: &[u8], mut builder: crate::output::update_connector_profile_output::Builder, ) -> Result<crate::output::update_connector_profile_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "connectorProfileArn" => { builder = builder.set_connector_profile_arn( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn deser_operation_update_flow( input: &[u8], mut builder: crate::output::update_flow_output::Builder, ) -> Result<crate::output::update_flow_output::Builder, smithy_json::deserialize::Error> { let mut tokens_owned = smithy_json::deserialize::json_token_iter(crate::json_deser::or_empty_doc(input)) .peekable(); let tokens = &mut tokens_owned; smithy_json::deserialize::token::expect_start_object(tokens.next())?; loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "flowStatus" => { builder = builder.set_flow_status( smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::FlowStatus::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } if tokens.next().is_some() { return Err(smithy_json::deserialize::Error::custom( "found more JSON tokens after completing parsing", )); } Ok(builder) } pub fn or_empty_doc(data: &[u8]) -> &[u8] { if data.is_empty() { b"{}" } else { data } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_connector_entity_field_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::ConnectorEntityField>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_connector_entity_field(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_connector_profile_detail_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::ConnectorProfile>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_connector_profile(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_connector_configurations_map<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option< std::collections::HashMap< crate::model::ConnectorType, crate::model::ConnectorConfiguration, >, >, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key .to_unescaped() .map(|u| crate::model::ConnectorType::from(u.as_ref()))?; let value = crate::json_deser::deser_structure_connector_configuration(tokens)?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_destination_flow_config_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::DestinationFlowConfig>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_destination_flow_config(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_execution_details<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ExecutionDetails>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ExecutionDetails::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "mostRecentExecutionMessage" => { builder = builder.set_most_recent_execution_message( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "mostRecentExecutionTime" => { builder = builder.set_most_recent_execution_time( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "mostRecentExecutionStatus" => { builder = builder.set_most_recent_execution_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ExecutionStatus::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_source_flow_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SourceFlowConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SourceFlowConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "connectorType" => { builder = builder.set_connector_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ConnectorType::from(u.as_ref())) }) .transpose()?, ); } "connectorProfileName" => { builder = builder.set_connector_profile_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "sourceConnectorProperties" => { builder = builder.set_source_connector_properties( crate::json_deser::deser_structure_source_connector_properties( tokens, )?, ); } "incrementalPullConfig" => { builder = builder.set_incremental_pull_config( crate::json_deser::deser_structure_incremental_pull_config( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_tag_map<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<std::string::String, std::string::String>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key.to_unescaped().map(|u| u.into_owned())?; let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_tasks<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Task>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_task(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_trigger_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TriggerConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TriggerConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "triggerType" => { builder = builder.set_trigger_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::TriggerType::from(u.as_ref())) }) .transpose()?, ); } "triggerProperties" => { builder = builder.set_trigger_properties( crate::json_deser::deser_structure_trigger_properties(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_flow_execution_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::ExecutionRecord>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_execution_record(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_connector_entity_map<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option< std::collections::HashMap< std::string::String, std::vec::Vec<crate::model::ConnectorEntity>, >, >, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key.to_unescaped().map(|u| u.into_owned())?; let value = crate::json_deser::deser_list_connector_entity_list(tokens)?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_flow_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::FlowDefinition>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_flow_definition(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_connector_entity_field<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ConnectorEntityField>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ConnectorEntityField::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "identifier" => { builder = builder.set_identifier( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "label" => { builder = builder.set_label( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "supportedFieldTypeDetails" => { builder = builder.set_supported_field_type_details( crate::json_deser::deser_structure_supported_field_type_details(tokens)? ); } "description" => { builder = builder.set_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "sourceProperties" => { builder = builder.set_source_properties( crate::json_deser::deser_structure_source_field_properties( tokens, )?, ); } "destinationProperties" => { builder = builder.set_destination_properties( crate::json_deser::deser_structure_destination_field_properties(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_connector_profile<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ConnectorProfile>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ConnectorProfile::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "connectorProfileArn" => { builder = builder.set_connector_profile_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "connectorProfileName" => { builder = builder.set_connector_profile_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "connectorType" => { builder = builder.set_connector_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ConnectorType::from(u.as_ref())) }) .transpose()?, ); } "connectionMode" => { builder = builder.set_connection_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ConnectionMode::from(u.as_ref())) }) .transpose()?, ); } "credentialsArn" => { builder = builder.set_credentials_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "connectorProfileProperties" => { builder = builder.set_connector_profile_properties( crate::json_deser::deser_structure_connector_profile_properties(tokens)? ); } "createdAt" => { builder = builder.set_created_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "lastUpdatedAt" => { builder = builder.set_last_updated_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "privateConnectionProvisioningState" => { builder = builder.set_private_connection_provisioning_state( crate::json_deser::deser_structure_private_connection_provisioning_state(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_connector_configuration<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ConnectorConfiguration>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ConnectorConfiguration::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "canUseAsSource" => { builder = builder.set_can_use_as_source( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "canUseAsDestination" => { builder = builder.set_can_use_as_destination( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "supportedDestinationConnectors" => { builder = builder.set_supported_destination_connectors( crate::json_deser::deser_list_connector_type_list(tokens)?, ); } "supportedSchedulingFrequencies" => { builder = builder.set_supported_scheduling_frequencies( crate::json_deser::deser_list_scheduling_frequency_type_list( tokens, )?, ); } "isPrivateLinkEnabled" => { builder = builder.set_is_private_link_enabled( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "isPrivateLinkEndpointUrlRequired" => { builder = builder.set_is_private_link_endpoint_url_required( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "supportedTriggerTypes" => { builder = builder.set_supported_trigger_types( crate::json_deser::deser_list_trigger_type_list(tokens)?, ); } "connectorMetadata" => { builder = builder.set_connector_metadata( crate::json_deser::deser_structure_connector_metadata(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_destination_flow_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DestinationFlowConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DestinationFlowConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "connectorType" => { builder = builder.set_connector_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ConnectorType::from(u.as_ref())) }) .transpose()?, ); } "connectorProfileName" => { builder = builder.set_connector_profile_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "destinationConnectorProperties" => { builder = builder.set_destination_connector_properties( crate::json_deser::deser_structure_destination_connector_properties(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_source_connector_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SourceConnectorProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SourceConnectorProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Amplitude" => { builder = builder.set_amplitude( crate::json_deser::deser_structure_amplitude_source_properties( tokens, )?, ); } "Datadog" => { builder = builder.set_datadog( crate::json_deser::deser_structure_datadog_source_properties( tokens, )?, ); } "Dynatrace" => { builder = builder.set_dynatrace( crate::json_deser::deser_structure_dynatrace_source_properties( tokens, )?, ); } "GoogleAnalytics" => { builder = builder.set_google_analytics( crate::json_deser::deser_structure_google_analytics_source_properties(tokens)? ); } "InforNexus" => { builder = builder.set_infor_nexus( crate::json_deser::deser_structure_infor_nexus_source_properties(tokens)? ); } "Marketo" => { builder = builder.set_marketo( crate::json_deser::deser_structure_marketo_source_properties( tokens, )?, ); } "S3" => { builder = builder.set_s3( crate::json_deser::deser_structure_s3_source_properties( tokens, )?, ); } "Salesforce" => { builder = builder.set_salesforce( crate::json_deser::deser_structure_salesforce_source_properties(tokens)? ); } "ServiceNow" => { builder = builder.set_service_now( crate::json_deser::deser_structure_service_now_source_properties(tokens)? ); } "Singular" => { builder = builder.set_singular( crate::json_deser::deser_structure_singular_source_properties( tokens, )?, ); } "Slack" => { builder = builder.set_slack( crate::json_deser::deser_structure_slack_source_properties( tokens, )?, ); } "Trendmicro" => { builder = builder.set_trendmicro( crate::json_deser::deser_structure_trendmicro_source_properties(tokens)? ); } "Veeva" => { builder = builder.set_veeva( crate::json_deser::deser_structure_veeva_source_properties( tokens, )?, ); } "Zendesk" => { builder = builder.set_zendesk( crate::json_deser::deser_structure_zendesk_source_properties( tokens, )?, ); } "SAPOData" => { builder = builder.set_sapo_data( crate::json_deser::deser_structure_sapo_data_source_properties( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_incremental_pull_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::IncrementalPullConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::IncrementalPullConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "datetimeTypeFieldName" => { builder = builder.set_datetime_type_field_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_task<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::Task>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::Task::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "sourceFields" => { builder = builder.set_source_fields( crate::json_deser::deser_list_source_fields(tokens)?, ); } "connectorOperator" => { builder = builder.set_connector_operator( crate::json_deser::deser_structure_connector_operator(tokens)?, ); } "destinationField" => { builder = builder.set_destination_field( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "taskType" => { builder = builder.set_task_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::TaskType::from(u.as_ref())) }) .transpose()?, ); } "taskProperties" => { builder = builder.set_task_properties( crate::json_deser::deser_map_task_properties_map(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_trigger_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TriggerProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TriggerProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Scheduled" => { builder = builder.set_scheduled( crate::json_deser::deser_structure_scheduled_trigger_properties(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_execution_record<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ExecutionRecord>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ExecutionRecord::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "executionId" => { builder = builder.set_execution_id( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "executionStatus" => { builder = builder.set_execution_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ExecutionStatus::from(u.as_ref()) }) }) .transpose()?, ); } "executionResult" => { builder = builder.set_execution_result( crate::json_deser::deser_structure_execution_result(tokens)?, ); } "startedAt" => { builder = builder.set_started_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "lastUpdatedAt" => { builder = builder.set_last_updated_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "dataPullStartTime" => { builder = builder.set_data_pull_start_time( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "dataPullEndTime" => { builder = builder.set_data_pull_end_time( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_connector_entity_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::ConnectorEntity>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = crate::json_deser::deser_structure_connector_entity(tokens)?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_flow_definition<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::FlowDefinition>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::FlowDefinition::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "flowArn" => { builder = builder.set_flow_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "description" => { builder = builder.set_description( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "flowName" => { builder = builder.set_flow_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "flowStatus" => { builder = builder.set_flow_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::FlowStatus::from(u.as_ref())) }) .transpose()?, ); } "sourceConnectorType" => { builder = builder.set_source_connector_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ConnectorType::from(u.as_ref())) }) .transpose()?, ); } "destinationConnectorType" => { builder = builder.set_destination_connector_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::ConnectorType::from(u.as_ref())) }) .transpose()?, ); } "triggerType" => { builder = builder.set_trigger_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::TriggerType::from(u.as_ref())) }) .transpose()?, ); } "createdAt" => { builder = builder.set_created_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "lastUpdatedAt" => { builder = builder.set_last_updated_at( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "createdBy" => { builder = builder.set_created_by( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "lastUpdatedBy" => { builder = builder.set_last_updated_by( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "tags" => { builder = builder.set_tags(crate::json_deser::deser_map_tag_map(tokens)?); } "lastRunExecutionDetails" => { builder = builder.set_last_run_execution_details( crate::json_deser::deser_structure_execution_details(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_supported_field_type_details<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SupportedFieldTypeDetails>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SupportedFieldTypeDetails::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "v1" => { builder = builder.set_v1( crate::json_deser::deser_structure_field_type_details(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_source_field_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SourceFieldProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SourceFieldProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "isRetrievable" => { builder = builder.set_is_retrievable( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "isQueryable" => { builder = builder.set_is_queryable( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_destination_field_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DestinationFieldProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DestinationFieldProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "isCreatable" => { builder = builder.set_is_creatable( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "isNullable" => { builder = builder.set_is_nullable( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "isUpsertable" => { builder = builder.set_is_upsertable( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "isUpdatable" => { builder = builder.set_is_updatable( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "supportedWriteOperations" => { builder = builder.set_supported_write_operations( crate::json_deser::deser_list_supported_write_operation_list( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ConnectorProfileProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Amplitude" => { builder = builder.set_amplitude( crate::json_deser::deser_structure_amplitude_connector_profile_properties(tokens)? ); } "Datadog" => { builder = builder.set_datadog( crate::json_deser::deser_structure_datadog_connector_profile_properties(tokens)? ); } "Dynatrace" => { builder = builder.set_dynatrace( crate::json_deser::deser_structure_dynatrace_connector_profile_properties(tokens)? ); } "GoogleAnalytics" => { builder = builder.set_google_analytics( crate::json_deser::deser_structure_google_analytics_connector_profile_properties(tokens)? ); } "Honeycode" => { builder = builder.set_honeycode( crate::json_deser::deser_structure_honeycode_connector_profile_properties(tokens)? ); } "InforNexus" => { builder = builder.set_infor_nexus( crate::json_deser::deser_structure_infor_nexus_connector_profile_properties(tokens)? ); } "Marketo" => { builder = builder.set_marketo( crate::json_deser::deser_structure_marketo_connector_profile_properties(tokens)? ); } "Redshift" => { builder = builder.set_redshift( crate::json_deser::deser_structure_redshift_connector_profile_properties(tokens)? ); } "Salesforce" => { builder = builder.set_salesforce( crate::json_deser::deser_structure_salesforce_connector_profile_properties(tokens)? ); } "ServiceNow" => { builder = builder.set_service_now( crate::json_deser::deser_structure_service_now_connector_profile_properties(tokens)? ); } "Singular" => { builder = builder.set_singular( crate::json_deser::deser_structure_singular_connector_profile_properties(tokens)? ); } "Slack" => { builder = builder.set_slack( crate::json_deser::deser_structure_slack_connector_profile_properties(tokens)? ); } "Snowflake" => { builder = builder.set_snowflake( crate::json_deser::deser_structure_snowflake_connector_profile_properties(tokens)? ); } "Trendmicro" => { builder = builder.set_trendmicro( crate::json_deser::deser_structure_trendmicro_connector_profile_properties(tokens)? ); } "Veeva" => { builder = builder.set_veeva( crate::json_deser::deser_structure_veeva_connector_profile_properties(tokens)? ); } "Zendesk" => { builder = builder.set_zendesk( crate::json_deser::deser_structure_zendesk_connector_profile_properties(tokens)? ); } "SAPOData" => { builder = builder.set_sapo_data( crate::json_deser::deser_structure_sapo_data_connector_profile_properties(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_private_connection_provisioning_state<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::PrivateConnectionProvisioningState>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::PrivateConnectionProvisioningState::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "status" => { builder = builder.set_status( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::PrivateConnectionProvisioningStatus::from( u.as_ref(), ) }) }) .transpose()?, ); } "failureMessage" => { builder = builder.set_failure_message( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "failureCause" => { builder = builder.set_failure_cause( smithy_json::deserialize::token::expect_string_or_null(tokens.next())?.map(|s| s.to_unescaped().map(|u| crate::model::PrivateConnectionProvisioningFailureCause::from(u.as_ref()) ) ).transpose()? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_connector_type_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::ConnectorType>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::ConnectorType::from(u.as_ref())) }) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_scheduling_frequency_type_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::vec::Vec<crate::model::ScheduleFrequencyType>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped().map(|u| { crate::model::ScheduleFrequencyType::from(u.as_ref()) }) }) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_trigger_type_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::TriggerType>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::TriggerType::from(u.as_ref())) }) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_connector_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ConnectorMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ConnectorMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Amplitude" => { builder = builder.set_amplitude( crate::json_deser::deser_structure_amplitude_metadata(tokens)?, ); } "Datadog" => { builder = builder.set_datadog( crate::json_deser::deser_structure_datadog_metadata(tokens)?, ); } "Dynatrace" => { builder = builder.set_dynatrace( crate::json_deser::deser_structure_dynatrace_metadata(tokens)?, ); } "GoogleAnalytics" => { builder = builder.set_google_analytics( crate::json_deser::deser_structure_google_analytics_metadata( tokens, )?, ); } "InforNexus" => { builder = builder.set_infor_nexus( crate::json_deser::deser_structure_infor_nexus_metadata( tokens, )?, ); } "Marketo" => { builder = builder.set_marketo( crate::json_deser::deser_structure_marketo_metadata(tokens)?, ); } "Redshift" => { builder = builder.set_redshift( crate::json_deser::deser_structure_redshift_metadata(tokens)?, ); } "S3" => { builder = builder.set_s3( crate::json_deser::deser_structure_s3_metadata(tokens)?, ); } "Salesforce" => { builder = builder.set_salesforce( crate::json_deser::deser_structure_salesforce_metadata(tokens)?, ); } "ServiceNow" => { builder = builder.set_service_now( crate::json_deser::deser_structure_service_now_metadata( tokens, )?, ); } "Singular" => { builder = builder.set_singular( crate::json_deser::deser_structure_singular_metadata(tokens)?, ); } "Slack" => { builder = builder.set_slack( crate::json_deser::deser_structure_slack_metadata(tokens)?, ); } "Snowflake" => { builder = builder.set_snowflake( crate::json_deser::deser_structure_snowflake_metadata(tokens)?, ); } "Trendmicro" => { builder = builder.set_trendmicro( crate::json_deser::deser_structure_trendmicro_metadata(tokens)?, ); } "Veeva" => { builder = builder.set_veeva( crate::json_deser::deser_structure_veeva_metadata(tokens)?, ); } "Zendesk" => { builder = builder.set_zendesk( crate::json_deser::deser_structure_zendesk_metadata(tokens)?, ); } "EventBridge" => { builder = builder.set_event_bridge( crate::json_deser::deser_structure_event_bridge_metadata( tokens, )?, ); } "Upsolver" => { builder = builder.set_upsolver( crate::json_deser::deser_structure_upsolver_metadata(tokens)?, ); } "CustomerProfiles" => { builder = builder.set_customer_profiles( crate::json_deser::deser_structure_customer_profiles_metadata( tokens, )?, ); } "Honeycode" => { builder = builder.set_honeycode( crate::json_deser::deser_structure_honeycode_metadata(tokens)?, ); } "SAPOData" => { builder = builder.set_sapo_data( crate::json_deser::deser_structure_sapo_data_metadata(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_destination_connector_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DestinationConnectorProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DestinationConnectorProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Redshift" => { builder = builder.set_redshift( crate::json_deser::deser_structure_redshift_destination_properties(tokens)? ); } "S3" => { builder = builder.set_s3( crate::json_deser::deser_structure_s3_destination_properties( tokens, )?, ); } "Salesforce" => { builder = builder.set_salesforce( crate::json_deser::deser_structure_salesforce_destination_properties(tokens)? ); } "Snowflake" => { builder = builder.set_snowflake( crate::json_deser::deser_structure_snowflake_destination_properties(tokens)? ); } "EventBridge" => { builder = builder.set_event_bridge( crate::json_deser::deser_structure_event_bridge_destination_properties(tokens)? ); } "LookoutMetrics" => { builder = builder.set_lookout_metrics( crate::json_deser::deser_structure_lookout_metrics_destination_properties(tokens)? ); } "Upsolver" => { builder = builder.set_upsolver( crate::json_deser::deser_structure_upsolver_destination_properties(tokens)? ); } "Honeycode" => { builder = builder.set_honeycode( crate::json_deser::deser_structure_honeycode_destination_properties(tokens)? ); } "CustomerProfiles" => { builder = builder.set_customer_profiles( crate::json_deser::deser_structure_customer_profiles_destination_properties(tokens)? ); } "Zendesk" => { builder = builder.set_zendesk( crate::json_deser::deser_structure_zendesk_destination_properties(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_amplitude_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AmplitudeSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AmplitudeSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_datadog_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DatadogSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DatadogSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_dynatrace_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DynatraceSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DynatraceSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_google_analytics_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::GoogleAnalyticsSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::GoogleAnalyticsSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_infor_nexus_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::InforNexusSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::InforNexusSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_marketo_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MarketoSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MarketoSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_s3_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::S3SourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::S3SourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bucketName" => { builder = builder.set_bucket_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketPrefix" => { builder = builder.set_bucket_prefix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_salesforce_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SalesforceSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SalesforceSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "enableDynamicFieldUpdate" => { builder = builder.set_enable_dynamic_field_update( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "includeDeletedRecords" => { builder = builder.set_include_deleted_records( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_service_now_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ServiceNowSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ServiceNowSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_singular_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SingularSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SingularSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_slack_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SlackSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SlackSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_trendmicro_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TrendmicroSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TrendmicroSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_veeva_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::VeevaSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::VeevaSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "documentType" => { builder = builder.set_document_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "includeSourceFiles" => { builder = builder.set_include_source_files( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "includeRenditions" => { builder = builder.set_include_renditions( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "includeAllVersions" => { builder = builder.set_include_all_versions( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_zendesk_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ZendeskSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ZendeskSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_sapo_data_source_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SapoDataSourceProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SapoDataSourceProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "objectPath" => { builder = builder.set_object_path( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_source_fields<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_connector_operator<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ConnectorOperator>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ConnectorOperator::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "Amplitude" => { builder = builder.set_amplitude( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AmplitudeConnectorOperator::from( u.as_ref(), ) }) }) .transpose()?, ); } "Datadog" => { builder = builder.set_datadog( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DatadogConnectorOperator::from(u.as_ref()) }) }) .transpose()?, ); } "Dynatrace" => { builder = builder.set_dynatrace( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::DynatraceConnectorOperator::from( u.as_ref(), ) }) }) .transpose()?, ); } "GoogleAnalytics" => { builder = builder.set_google_analytics( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::GoogleAnalyticsConnectorOperator::from( u.as_ref(), ) }) }) .transpose()?, ); } "InforNexus" => { builder = builder.set_infor_nexus( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::InforNexusConnectorOperator::from( u.as_ref(), ) }) }) .transpose()?, ); } "Marketo" => { builder = builder.set_marketo( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::MarketoConnectorOperator::from(u.as_ref()) }) }) .transpose()?, ); } "S3" => { builder = builder.set_s3( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::S3ConnectorOperator::from(u.as_ref()) }) }) .transpose()?, ); } "Salesforce" => { builder = builder.set_salesforce( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::SalesforceConnectorOperator::from( u.as_ref(), ) }) }) .transpose()?, ); } "ServiceNow" => { builder = builder.set_service_now( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ServiceNowConnectorOperator::from( u.as_ref(), ) }) }) .transpose()?, ); } "Singular" => { builder = builder.set_singular( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::SingularConnectorOperator::from( u.as_ref(), ) }) }) .transpose()?, ); } "Slack" => { builder = builder.set_slack( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::SlackConnectorOperator::from(u.as_ref()) }) }) .transpose()?, ); } "Trendmicro" => { builder = builder.set_trendmicro( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::TrendmicroConnectorOperator::from( u.as_ref(), ) }) }) .transpose()?, ); } "Veeva" => { builder = builder.set_veeva( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::VeevaConnectorOperator::from(u.as_ref()) }) }) .transpose()?, ); } "Zendesk" => { builder = builder.set_zendesk( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::ZendeskConnectorOperator::from(u.as_ref()) }) }) .transpose()?, ); } "SAPOData" => { builder = builder.set_sapo_data( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::SapoDataConnectorOperator::from( u.as_ref(), ) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_map_task_properties_map<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<std::collections::HashMap<crate::model::OperatorPropertiesKeys, std::string::String>>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { let mut map = std::collections::HashMap::new(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { let key = key .to_unescaped() .map(|u| crate::model::OperatorPropertiesKeys::from(u.as_ref()))?; let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { map.insert(key, value); } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(map)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_scheduled_trigger_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ScheduledTriggerProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ScheduledTriggerProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "scheduleExpression" => { builder = builder.set_schedule_expression( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "dataPullMode" => { builder = builder.set_data_pull_mode( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::DataPullMode::from(u.as_ref())) }) .transpose()?, ); } "scheduleStartTime" => { builder = builder.set_schedule_start_time( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "scheduleEndTime" => { builder = builder.set_schedule_end_time( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } "timezone" => { builder = builder.set_timezone( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "scheduleOffset" => { builder = builder.set_schedule_offset( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } "firstExecutionFrom" => { builder = builder.set_first_execution_from( smithy_json::deserialize::token::expect_timestamp_or_null( tokens.next(), smithy_types::instant::Format::EpochSeconds, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_execution_result<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ExecutionResult>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ExecutionResult::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "errorInfo" => { builder = builder.set_error_info( crate::json_deser::deser_structure_error_info(tokens)?, ); } "bytesProcessed" => { builder = builder.set_bytes_processed( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } "bytesWritten" => { builder = builder.set_bytes_written( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } "recordsProcessed" => { builder = builder.set_records_processed( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_connector_entity<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ConnectorEntity>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ConnectorEntity::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "name" => { builder = builder.set_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "label" => { builder = builder.set_label( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "hasNestedEntities" => { builder = builder.set_has_nested_entities( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_field_type_details<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::FieldTypeDetails>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::FieldTypeDetails::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "fieldType" => { builder = builder.set_field_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "filterOperators" => { builder = builder.set_filter_operators( crate::json_deser::deser_list_filter_operator_list(tokens)?, ); } "supportedValues" => { builder = builder.set_supported_values( crate::json_deser::deser_list_supported_value_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_supported_write_operation_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::WriteOperationType>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::WriteOperationType::from(u.as_ref())) }) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_amplitude_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::AmplitudeConnectorProfileProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AmplitudeConnectorProfileProperties::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_datadog_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DatadogConnectorProfileProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DatadogConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "instanceUrl" => { builder = builder.set_instance_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_dynatrace_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::DynatraceConnectorProfileProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DynatraceConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "instanceUrl" => { builder = builder.set_instance_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_google_analytics_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::GoogleAnalyticsConnectorProfileProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::GoogleAnalyticsConnectorProfileProperties::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_honeycode_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::HoneycodeConnectorProfileProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HoneycodeConnectorProfileProperties::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_infor_nexus_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::InforNexusConnectorProfileProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::InforNexusConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "instanceUrl" => { builder = builder.set_instance_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_marketo_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MarketoConnectorProfileProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MarketoConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "instanceUrl" => { builder = builder.set_instance_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_redshift_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::RedshiftConnectorProfileProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::RedshiftConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "databaseUrl" => { builder = builder.set_database_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketName" => { builder = builder.set_bucket_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketPrefix" => { builder = builder.set_bucket_prefix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "roleArn" => { builder = builder.set_role_arn( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_salesforce_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::SalesforceConnectorProfileProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SalesforceConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "instanceUrl" => { builder = builder.set_instance_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "isSandboxEnvironment" => { builder = builder.set_is_sandbox_environment( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_service_now_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::ServiceNowConnectorProfileProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ServiceNowConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "instanceUrl" => { builder = builder.set_instance_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_singular_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SingularConnectorProfileProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SingularConnectorProfileProperties::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_slack_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SlackConnectorProfileProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SlackConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "instanceUrl" => { builder = builder.set_instance_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_snowflake_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::SnowflakeConnectorProfileProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SnowflakeConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "warehouse" => { builder = builder.set_warehouse( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "stage" => { builder = builder.set_stage( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketName" => { builder = builder.set_bucket_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketPrefix" => { builder = builder.set_bucket_prefix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "privateLinkServiceName" => { builder = builder.set_private_link_service_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "accountName" => { builder = builder.set_account_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "region" => { builder = builder.set_region( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_trendmicro_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::TrendmicroConnectorProfileProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TrendmicroConnectorProfileProperties::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_veeva_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::VeevaConnectorProfileProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::VeevaConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "instanceUrl" => { builder = builder.set_instance_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_zendesk_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ZendeskConnectorProfileProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ZendeskConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "instanceUrl" => { builder = builder.set_instance_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_sapo_data_connector_profile_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SapoDataConnectorProfileProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SapoDataConnectorProfileProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "applicationHostUrl" => { builder = builder.set_application_host_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "applicationServicePath" => { builder = builder.set_application_service_path( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "portNumber" => { builder = builder.set_port_number( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i32()), ); } "clientNumber" => { builder = builder.set_client_number( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "logonLanguage" => { builder = builder.set_logon_language( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "privateLinkServiceName" => { builder = builder.set_private_link_service_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "oAuthProperties" => { builder = builder.set_o_auth_properties( crate::json_deser::deser_structure_o_auth_properties(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_amplitude_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AmplitudeMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AmplitudeMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_datadog_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DatadogMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DatadogMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_dynatrace_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::DynatraceMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::DynatraceMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_google_analytics_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::GoogleAnalyticsMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::GoogleAnalyticsMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "oAuthScopes" => { builder = builder.set_o_auth_scopes( crate::json_deser::deser_list_o_auth_scope_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_infor_nexus_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::InforNexusMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::InforNexusMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_marketo_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::MarketoMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::MarketoMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_redshift_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::RedshiftMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::RedshiftMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_s3_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::S3Metadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::S3Metadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_salesforce_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SalesforceMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SalesforceMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "oAuthScopes" => { builder = builder.set_o_auth_scopes( crate::json_deser::deser_list_o_auth_scope_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_service_now_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ServiceNowMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ServiceNowMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_singular_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SingularMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SingularMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_slack_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SlackMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SlackMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "oAuthScopes" => { builder = builder.set_o_auth_scopes( crate::json_deser::deser_list_o_auth_scope_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_snowflake_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SnowflakeMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SnowflakeMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "supportedRegions" => { builder = builder.set_supported_regions( crate::json_deser::deser_list_region_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_trendmicro_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::TrendmicroMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::TrendmicroMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_veeva_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::VeevaMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::VeevaMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_zendesk_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ZendeskMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ZendeskMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "oAuthScopes" => { builder = builder.set_o_auth_scopes( crate::json_deser::deser_list_o_auth_scope_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_event_bridge_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::EventBridgeMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EventBridgeMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_upsolver_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::UpsolverMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::UpsolverMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_customer_profiles_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::CustomerProfilesMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CustomerProfilesMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_honeycode_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::HoneycodeMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HoneycodeMetadata::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "oAuthScopes" => { builder = builder.set_o_auth_scopes( crate::json_deser::deser_list_o_auth_scope_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_sapo_data_metadata<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SapoDataMetadata>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SapoDataMetadata::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_redshift_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::RedshiftDestinationProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::RedshiftDestinationProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "intermediateBucketName" => { builder = builder.set_intermediate_bucket_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketPrefix" => { builder = builder.set_bucket_prefix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "errorHandlingConfig" => { builder = builder.set_error_handling_config( crate::json_deser::deser_structure_error_handling_config( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_s3_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::S3DestinationProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::S3DestinationProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bucketName" => { builder = builder.set_bucket_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketPrefix" => { builder = builder.set_bucket_prefix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "s3OutputFormatConfig" => { builder = builder.set_s3_output_format_config( crate::json_deser::deser_structure_s3_output_format_config( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_salesforce_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SalesforceDestinationProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SalesforceDestinationProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "idFieldNames" => { builder = builder.set_id_field_names( crate::json_deser::deser_list_id_field_name_list(tokens)?, ); } "errorHandlingConfig" => { builder = builder.set_error_handling_config( crate::json_deser::deser_structure_error_handling_config( tokens, )?, ); } "writeOperationType" => { builder = builder.set_write_operation_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::WriteOperationType::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_snowflake_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::SnowflakeDestinationProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::SnowflakeDestinationProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "intermediateBucketName" => { builder = builder.set_intermediate_bucket_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketPrefix" => { builder = builder.set_bucket_prefix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "errorHandlingConfig" => { builder = builder.set_error_handling_config( crate::json_deser::deser_structure_error_handling_config( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_event_bridge_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::EventBridgeDestinationProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::EventBridgeDestinationProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "errorHandlingConfig" => { builder = builder.set_error_handling_config( crate::json_deser::deser_structure_error_handling_config( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_lookout_metrics_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::LookoutMetricsDestinationProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::LookoutMetricsDestinationProperties::builder(); smithy_json::deserialize::token::skip_to_end(tokens)?; Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_upsolver_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::UpsolverDestinationProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::UpsolverDestinationProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "bucketName" => { builder = builder.set_bucket_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketPrefix" => { builder = builder.set_bucket_prefix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "s3OutputFormatConfig" => { builder = builder.set_s3_output_format_config( crate::json_deser::deser_structure_upsolver_s3_output_format_config(tokens)? ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_honeycode_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::HoneycodeDestinationProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::HoneycodeDestinationProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "errorHandlingConfig" => { builder = builder.set_error_handling_config( crate::json_deser::deser_structure_error_handling_config( tokens, )?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_customer_profiles_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result< Option<crate::model::CustomerProfilesDestinationProperties>, smithy_json::deserialize::Error, > where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::CustomerProfilesDestinationProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "domainName" => { builder = builder.set_domain_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "objectTypeName" => { builder = builder.set_object_type_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_zendesk_destination_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ZendeskDestinationProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ZendeskDestinationProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "object" => { builder = builder.set_object( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "idFieldNames" => { builder = builder.set_id_field_names( crate::json_deser::deser_list_id_field_name_list(tokens)?, ); } "errorHandlingConfig" => { builder = builder.set_error_handling_config( crate::json_deser::deser_structure_error_handling_config( tokens, )?, ); } "writeOperationType" => { builder = builder.set_write_operation_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::WriteOperationType::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_error_info<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ErrorInfo>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ErrorInfo::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "putFailuresCount" => { builder = builder.set_put_failures_count( smithy_json::deserialize::token::expect_number_or_null( tokens.next(), )? .map(|v| v.to_i64()), ); } "executionMessage" => { builder = builder.set_execution_message( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_filter_operator_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<crate::model::Operator>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| { s.to_unescaped() .map(|u| crate::model::Operator::from(u.as_ref())) }) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_supported_value_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_o_auth_properties<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::OAuthProperties>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::OAuthProperties::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "tokenUrl" => { builder = builder.set_token_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "authCodeUrl" => { builder = builder.set_auth_code_url( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "oAuthScopes" => { builder = builder.set_o_auth_scopes( crate::json_deser::deser_list_o_auth_scope_list(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_o_auth_scope_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_region_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_error_handling_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::ErrorHandlingConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::ErrorHandlingConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "failOnFirstDestinationError" => { builder = builder.set_fail_on_first_destination_error( smithy_json::deserialize::token::expect_bool_or_null( tokens.next(), )?, ); } "bucketPrefix" => { builder = builder.set_bucket_prefix( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } "bucketName" => { builder = builder.set_bucket_name( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_s3_output_format_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::S3OutputFormatConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::S3OutputFormatConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "fileType" => { builder = builder.set_file_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::FileType::from(u.as_ref())) }) .transpose()?, ); } "prefixConfig" => { builder = builder.set_prefix_config( crate::json_deser::deser_structure_prefix_config(tokens)?, ); } "aggregationConfig" => { builder = builder.set_aggregation_config( crate::json_deser::deser_structure_aggregation_config(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } #[allow(clippy::type_complexity, non_snake_case)] pub fn deser_list_id_field_name_list<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<std::vec::Vec<std::string::String>>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartArray { .. }) => { let mut items = Vec::new(); loop { match tokens.peek() { Some(Ok(smithy_json::deserialize::Token::EndArray { .. })) => { tokens.next().transpose().unwrap(); break; } _ => { let value = smithy_json::deserialize::token::expect_string_or_null(tokens.next())? .map(|s| s.to_unescaped().map(|u| u.into_owned())) .transpose()?; if let Some(value) = value { items.push(value); } } } } Ok(Some(items)) } _ => Err(smithy_json::deserialize::Error::custom( "expected start array or null", )), } } pub fn deser_structure_upsolver_s3_output_format_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::UpsolverS3OutputFormatConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::UpsolverS3OutputFormatConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "fileType" => { builder = builder.set_file_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::FileType::from(u.as_ref())) }) .transpose()?, ); } "prefixConfig" => { builder = builder.set_prefix_config( crate::json_deser::deser_structure_prefix_config(tokens)?, ); } "aggregationConfig" => { builder = builder.set_aggregation_config( crate::json_deser::deser_structure_aggregation_config(tokens)?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_prefix_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::PrefixConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::PrefixConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "prefixType" => { builder = builder.set_prefix_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::PrefixType::from(u.as_ref())) }) .transpose()?, ); } "prefixFormat" => { builder = builder.set_prefix_format( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped() .map(|u| crate::model::PrefixFormat::from(u.as_ref())) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } } pub fn deser_structure_aggregation_config<'a, I>( tokens: &mut std::iter::Peekable<I>, ) -> Result<Option<crate::model::AggregationConfig>, smithy_json::deserialize::Error> where I: Iterator< Item = Result<smithy_json::deserialize::Token<'a>, smithy_json::deserialize::Error>, >, { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::ValueNull { .. }) => Ok(None), Some(smithy_json::deserialize::Token::StartObject { .. }) => { #[allow(unused_mut)] let mut builder = crate::model::AggregationConfig::builder(); loop { match tokens.next().transpose()? { Some(smithy_json::deserialize::Token::EndObject { .. }) => break, Some(smithy_json::deserialize::Token::ObjectKey { key, .. }) => { match key.to_unescaped()?.as_ref() { "aggregationType" => { builder = builder.set_aggregation_type( smithy_json::deserialize::token::expect_string_or_null( tokens.next(), )? .map(|s| { s.to_unescaped().map(|u| { crate::model::AggregationType::from(u.as_ref()) }) }) .transpose()?, ); } _ => smithy_json::deserialize::token::skip_value(tokens)?, } } _ => { return Err(smithy_json::deserialize::Error::custom( "expected object key or end object", )) } } } Ok(Some(builder.build())) } _ => Err(smithy_json::deserialize::Error::custom( "expected start object or null", )), } }
#![macro_use] #[macro_export] macro_rules! handle { (_ in $init:expr, $exit:expr, {$($impl:tt)*}) => { #[derive(Debug)] pub struct Handle(()); static INITIALIZED: ::std::sync::atomic::AtomicBool = ::std::sync::atomic::AtomicBool::new(false); impl Drop for Handle { fn drop(&mut self) { unsafe { $exit; }; } } impl Handle { pub fn new() -> Option<Self> { if !INITIALIZED.swap(true, ::std::sync::atomic::Ordering::SeqCst) { unsafe { $init; }; Some(Handle(())) } else { None } } $($impl)* } }; ($ok:pat in $init:expr, $exit:expr, {$($impl:tt)*}) => { #[derive(Debug)] pub struct Handle(()); static INITIALIZED: ::std::sync::atomic::AtomicBool = ::std::sync::atomic::AtomicBool::new(false); impl Drop for Handle { fn drop(&mut self) { unsafe { $exit; }; } } impl Handle { pub fn new() -> Option<Result<Self, u32>> { if !INITIALIZED.swap(true, ::std::sync::atomic::Ordering::SeqCst) { let res = unsafe { $init }; match res as u32 { $ok => Some(Ok(Handle(()))), err => Some(Err(err as u32)), } } else { None } } $($impl)* } }; }
use proconio::input; fn main() { input! { a:i32, } println!("{}", a + (a * a) + (a * a * a)); }
#[macro_use] extern crate serde_derive; extern crate bincode; extern crate hex_database; #[cfg(target_arch = "wasm32")] extern crate wasm_bindgen; #[cfg(target_arch = "wasm32")] #[macro_use] extern crate cfg_if; pub mod error; pub mod objects; #[cfg(target_arch = "wasm32")] cfg_if! { // When the `wee_alloc` feature is enabled, use `wee_alloc` as the global // allocator. if #[cfg(feature = "wee_alloc")] { extern crate wee_alloc; #[global_allocator] static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT; } } #[cfg(target_arch = "wasm32")] pub mod wasm; pub use objects::{Request, Answer, RequestAction, AnswerAction, PacketId}; pub use error::Error;
use std::io; use std::path::{Path, PathBuf}; use std::process::Output; use serde_json::json; use rnc_test_utils::{temp_file_with, Jsonl}; fn expand(id_file: &Path, json_file: &Path, output: &Path) -> io::Result<Output> { test_bin::get_test_bin("expand-urs") .arg(id_file) .arg(json_file) .arg(output) .output() } #[test] fn simple_expanding_test() -> Result<(), Box<dyn std::error::Error>> { let id_file = temp_file_with(vec![ "URS0000762A36_9606", ])?; let json_file = temp_file_with(vec![ r#"{"urs": "URS0000762A36", "value": "2"}"#, ])?; let output = PathBuf::from("-"); let result = expand(id_file.path(), json_file.path(), &output)?; assert_eq!(String::from_utf8_lossy(&result.stderr), ""); assert_eq!( result.jsonl()?, vec![ json!({"id": "URS0000762A36_9606", "urs": "URS0000762A36", "value": "2"}), ] ); assert_eq!(result.status.success(), true); Ok(()) }
use super::*; #[derive(Clone, PartialEq, Default)] pub struct PropertyKey { pub fmtid: GUID, pub pid: u32, } impl PropertyKey { pub fn from_attributes<I: IntoIterator<Item = Attribute>>(attributes: I) -> Option<Self> { attributes.into_iter().find(|attribute| attribute.name() == "PropertyKeyAttribute").map(|attribute| { let args = attribute.args(); Self { fmtid: GUID::from_args(&args), pid: args[11].1.unwrap_u32() } }) } }
use crate::api::Rest; use crate::api::API; use crate::client::*; use crate::errors::*; use crate::model::*; #[derive(Clone)] pub struct Market { pub client: Client, } impl Market { pub fn get_all_pairs(&self) -> Result<Pair> { self.client.get(API::SerumRest(Rest::Pairs), None) } pub fn get_trades_for_market(&self, market_name: String) -> Result<Trade> { self.client .get(API::SerumRest(Rest::Trades(market_name)), None) } pub fn get_trades_for_market_address(&self, market_address: String) -> Result<Trade> { self.client .get(API::SerumRest(Rest::AddressTrade(market_address)), None) } pub fn get_all_24hr_trades(&self) -> Result<Trade> { self.client.get(API::SerumRest(Rest::AllRecentTrades), None) } pub fn get_volumes_for_market(&self, market_name: String) -> Result<Volume> { self.client .get(API::SerumRest(Rest::Volumes(market_name)), None) } pub fn get_order_books_for_market(&self, market_name: String) -> Result<OrderBook> { self.client .get(API::SerumRest(Rest::OrderBooks(market_name)), None) } }
use std::io::prelude::*; use std::str::FromStr; fn ans(mut t:Vec<i32>,i:Vec<(i32,i32)>) -> Vec<i32> { for ii in i { let a : usize = ii.0 as usize; let b : usize = ii.1 as usize; let s = t[a-1]; t[a-1] = t[b-1]; t[b-1] = s; } t } fn main() { let stdin = std::io::stdin(); let mut lines = stdin.lock().lines(); let mut wn : Vec<i32> = Vec::new(); for _ in 0..2 { let l = lines.next().unwrap().unwrap(); wn.push(i32::from_str(&l).unwrap()); } let t : Vec<i32> = (1..wn[0]+1).collect(); let mut i : Vec<(i32,i32)> = Vec::new(); for _ in 0 .. wn[1] { let d : Vec<i32> = lines.next().unwrap().unwrap().split(',').map(|x| i32::from_str(x).unwrap()).collect(); i.push( (d[0],d[1]) ); } let o = ans(t,i); for oo in o.iter() { println!("{}",oo); } }
//! The team namespace is responsible for the state of the team and for holding //! the players in the game. use std::collections::BTreeSet; use world::world::Id; use event::event::Event; use traits::StateMachine; #[derive(Debug, Clone, Hash)] pub struct Team<'a> { pub roster: BTreeSet<&'a Id>, pub lineup: BTreeSet<&'a Id>, pub current_batter: &'a Id, } impl<'a> StateMachine for Team<'a> { fn next(&self, _event: &Event) -> Team<'a> { self.clone() } } // ================================================================================================= // Test helpers // ================================================================================================= #[cfg(test)] impl<'a> Team<'a> { fn base() {} }
pub enum UserInput { NumberInput(usize), AbortCommand, InvalidInput, } impl UserInput { pub fn from_stdin() -> UserInput { use std::io::stdin; let mut number = String::new(); stdin().read_line(&mut number) .expect("Failed to read line"); let number = number.trim(); if number == "a" { UserInput::AbortCommand } else { match number.parse() { Ok(num) => UserInput::NumberInput(num), Err(_) => UserInput::InvalidInput, } } } }
#[cfg(all(not(target_arch = "wasm32"), test))] mod test; use anyhow::*; use liblumen_alloc::erts::exception; use liblumen_alloc::erts::process::Process; use liblumen_alloc::erts::term::prelude::*; #[native_implemented::function(erlang:byte_size/1)] pub fn result(process: &Process, bitstring: Term) -> exception::Result<Term> { let option_total_byte_len = match bitstring.decode().unwrap() { TypedTerm::HeapBinary(heap_binary) => Some(heap_binary.total_byte_len()), TypedTerm::ProcBin(process_binary) => Some(process_binary.total_byte_len()), TypedTerm::SubBinary(subbinary) => Some(subbinary.total_byte_len()), _ => None, }; match option_total_byte_len { Some(total_byte_len) => Ok(process.integer(total_byte_len)), None => Err(TypeError) .context(format!("bitstring ({}) is not a bitstring", bitstring)) .map_err(From::from), } }
// Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 // // Portions Copyright 2017 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the THIRD-PARTY file. /// The vsock `EpollHandler` implements the runtime logic of our vsock device: /// 1. Respond to TX queue events by wrapping virtio buffers into `VsockPacket`s, then sending those /// packets to the `VsockBackend`; /// 2. Forward backend FD event notifications to the `VsockBackend`; /// 3. Fetch incoming packets from the `VsockBackend` and place them into the virtio RX queue; /// 4. Whenever we have processed some virtio buffers (either TX or RX), let the driver know by /// raising our assigned IRQ. /// /// In a nutshell, the `EpollHandler` logic looks like this: /// - on TX queue event: /// - fetch all packets from the TX queue and send them to the backend; then /// - if the backend has queued up any incoming packets, fetch them into any available RX buffers. /// - on RX queue event: /// - fetch any incoming packets, queued up by the backend, into newly available RX buffers. /// - on backend event: /// - forward the event to the backend; then /// - again, attempt to fetch any incoming packets queued by the backend into virtio RX buffers. use std::result; use std::sync::atomic::{AtomicUsize, Ordering}; use std::sync::Arc; use utils::eventfd::EventFd; use vm_memory::GuestMemory; use super::super::super::{DeviceEventT, Error as DeviceError}; use super::super::queue::Queue as VirtQueue; use super::super::VIRTIO_MMIO_INT_VRING; use super::defs; use super::packet::VsockPacket; use super::{EpollHandler, VsockBackend}; // TODO: Detect / handle queue deadlock: // 1. If the driver halts RX queue processing, we'll need to notify `self.backend`, so that it // can unregister any EPOLLIN listeners, since otherwise it will keep spinning, unable to consume // its EPOLLIN events. pub struct VsockEpollHandler<B: VsockBackend + 'static> { pub rxvq: VirtQueue, pub rxvq_evt: EventFd, pub txvq: VirtQueue, pub txvq_evt: EventFd, pub evvq: VirtQueue, pub evvq_evt: EventFd, pub cid: u64, pub mem: GuestMemory, pub interrupt_status: Arc<AtomicUsize>, pub interrupt_evt: EventFd, pub backend: B, } impl<B> VsockEpollHandler<B> where B: VsockBackend + 'static, { /// Signal the guest driver that we've used some virtio buffers that it had previously made /// available. fn signal_used_queue(&self) -> result::Result<(), DeviceError> { debug!("vsock: raising IRQ"); self.interrupt_status .fetch_or(VIRTIO_MMIO_INT_VRING as usize, Ordering::SeqCst); self.interrupt_evt.write(1).map_err(|e| { error!("Failed to signal used queue: {:?}", e); DeviceError::FailedSignalingUsedQueue(e) }) } /// Walk the driver-provided RX queue buffers and attempt to fill them up with any data that we /// have pending. fn process_rx(&mut self) -> bool { debug!("vsock: epoll_handler::process_rx()"); let mut have_used = false; while let Some(head) = self.rxvq.pop(&self.mem) { let used_len = match VsockPacket::from_rx_virtq_head(&head) { Ok(mut pkt) => { if self.backend.recv_pkt(&mut pkt).is_ok() { pkt.hdr().len() as u32 + pkt.len() } else { // We are using a consuming iterator over the virtio buffers, so, if we can't // fill in this buffer, we'll need to undo the last iterator step. self.rxvq.undo_pop(); break; } } Err(e) => { warn!("vsock: RX queue error: {:?}", e); 0 } }; have_used = true; self.rxvq.add_used(&self.mem, head.index, used_len); } have_used } /// Walk the driver-provided TX queue buffers, package them up as vsock packets, and send them to /// the backend for processing. fn process_tx(&mut self) -> bool { debug!("vsock: epoll_handler::process_tx()"); let mut have_used = false; while let Some(head) = self.txvq.pop(&self.mem) { let pkt = match VsockPacket::from_tx_virtq_head(&head) { Ok(pkt) => pkt, Err(e) => { error!("vsock: error reading TX packet: {:?}", e); have_used = true; self.txvq.add_used(&self.mem, head.index, 0); continue; } }; if self.backend.send_pkt(&pkt).is_err() { self.txvq.undo_pop(); break; } have_used = true; self.txvq.add_used(&self.mem, head.index, 0); } have_used } } impl<B> EpollHandler for VsockEpollHandler<B> where B: VsockBackend, { /// Respond to a new event, coming from the main epoll loop (implemented by the VMM). fn handle_event( &mut self, device_event: DeviceEventT, evset: epoll::Events, ) -> result::Result<(), DeviceError> { let mut raise_irq = false; match device_event { defs::RXQ_EVENT => { debug!("vsock: RX queue event"); if let Err(e) = self.rxvq_evt.read() { error!("Failed to get rx queue event: {:?}", e); return Err(DeviceError::FailedReadingQueue { event_type: "rx queue event", underlying: e, }); } else if self.backend.has_pending_rx() { raise_irq |= self.process_rx(); } } defs::TXQ_EVENT => { debug!("vsock: TX queue event"); if let Err(e) = self.txvq_evt.read() { error!("Failed to get tx queue event: {:?}", e); return Err(DeviceError::FailedReadingQueue { event_type: "tx queue event", underlying: e, }); } else { raise_irq |= self.process_tx(); // The backend may have queued up responses to the packets we sent during TX queue // processing. If that happened, we need to fetch those responses and place them // into RX buffers. if self.backend.has_pending_rx() { raise_irq |= self.process_rx(); } } } defs::EVQ_EVENT => { debug!("vsock: event queue event"); if let Err(e) = self.evvq_evt.read() { error!("Failed to consume evq event: {:?}", e); return Err(DeviceError::FailedReadingQueue { event_type: "ev queue event", underlying: e, }); } } defs::BACKEND_EVENT => { debug!("vsock: backend event"); self.backend.notify(evset); // After the backend has been kicked, it might've freed up some resources, so we // can attempt to send it more data to process. // In particular, if `self.backend.send_pkt()` halted the TX queue processing (by // reurning an error) at some point in the past, now is the time to try walking the // TX queue again. raise_irq |= self.process_tx(); if self.backend.has_pending_rx() { raise_irq |= self.process_rx(); } } other => { return Err(DeviceError::UnknownEvent { device: "vsock", event: other, }); } } if raise_irq { self.signal_used_queue().unwrap_or_default(); } Ok(()) } } #[cfg(test)] mod tests { use super::super::tests::TestContext; use super::super::*; use super::*; use crate::virtio::vsock::defs::{BACKEND_EVENT, EVQ_EVENT, RXQ_EVENT, TXQ_EVENT}; use crate::virtio::vsock::packet::VSOCK_PKT_HDR_SIZE; use vm_memory::Bytes; #[test] fn test_irq() { // Test case: successful IRQ signaling. { let test_ctx = TestContext::new(); let ctx = test_ctx.create_epoll_handler_context(); ctx.handler.signal_used_queue().unwrap(); assert_eq!( ctx.handler.interrupt_status.load(Ordering::SeqCst), VIRTIO_MMIO_INT_VRING as usize ); assert_eq!(ctx.handler.interrupt_evt.read().unwrap(), 1); } // Test case: error (a real stretch) - the event counter is full. // { let test_ctx = TestContext::new(); let ctx = test_ctx.create_epoll_handler_context(); ctx.handler.interrupt_evt.write(std::u64::MAX - 1).unwrap(); match ctx.handler.signal_used_queue() { Err(DeviceError::FailedSignalingUsedQueue(_)) => (), other => panic!("{:?}", other), } } } #[test] fn test_txq_event() { // Test case: // - the driver has something to send (there's data in the TX queue); and // - the backend has no pending RX data. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); ctx.handler.backend.set_pending_rx(false); ctx.signal_txq_event(); // The available TX descriptor should have been used. assert_eq!(ctx.guest_txvq.used.idx.get(), 1); // The available RX descriptor should be untouched. assert_eq!(ctx.guest_rxvq.used.idx.get(), 0); } // Test case: // - the driver has something to send (there's data in the TX queue); and // - the backend also has some pending RX data. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); ctx.handler.backend.set_pending_rx(true); ctx.signal_txq_event(); // Both available RX and TX descriptors should have been used. assert_eq!(ctx.guest_txvq.used.idx.get(), 1); assert_eq!(ctx.guest_rxvq.used.idx.get(), 1); } // Test case: // - the driver has something to send (there's data in the TX queue); and // - the backend errors out and cannot process the TX queue. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); ctx.handler.backend.set_pending_rx(false); ctx.handler.backend.set_tx_err(Some(VsockError::NoData)); ctx.signal_txq_event(); // Both RX and TX queues should be untouched. assert_eq!(ctx.guest_txvq.used.idx.get(), 0); assert_eq!(ctx.guest_rxvq.used.idx.get(), 0); } // Test case: // - the driver supplied a malformed TX buffer. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); // Invalidate the packet header descriptor, by setting its length to 0. ctx.guest_txvq.dtable[0].len.set(0); ctx.signal_txq_event(); // The available descriptor should have been consumed, but no packet should have // reached the backend. assert_eq!(ctx.guest_txvq.used.idx.get(), 1); assert_eq!(ctx.handler.backend.tx_ok_cnt, 0); } // Test case: spurious TXQ_EVENT. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); match ctx.handler.handle_event(TXQ_EVENT, epoll::Events::EPOLLIN) { Err(DeviceError::FailedReadingQueue { .. }) => (), other => panic!("{:?}", other), } } } #[test] fn test_rxq_event() { // Test case: // - there is pending RX data in the backend; and // - the driver makes RX buffers available; and // - the backend successfully places its RX data into the queue. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); ctx.handler.backend.set_pending_rx(true); ctx.handler.backend.set_rx_err(Some(VsockError::NoData)); ctx.signal_rxq_event(); // The available RX buffer should've been left untouched. assert_eq!(ctx.guest_rxvq.used.idx.get(), 0); } // Test case: // - there is pending RX data in the backend; and // - the driver makes RX buffers available; and // - the backend errors out, when attempting to receive data. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); ctx.handler.backend.set_pending_rx(true); ctx.signal_rxq_event(); // The available RX buffer should have been used. assert_eq!(ctx.guest_rxvq.used.idx.get(), 1); } // Test case: the driver provided a malformed RX descriptor chain. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); // Invalidate the packet header descriptor, by setting its length to 0. ctx.guest_rxvq.dtable[0].len.set(0); // The chain should've been processed, without employing the backend. assert_eq!(ctx.handler.process_rx(), true); assert_eq!(ctx.guest_rxvq.used.idx.get(), 1); assert_eq!(ctx.handler.backend.rx_ok_cnt, 0); } // Test case: spurious RXQ_EVENT. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); ctx.handler.backend.set_pending_rx(false); match ctx.handler.handle_event(RXQ_EVENT, epoll::Events::EPOLLIN) { Err(DeviceError::FailedReadingQueue { .. }) => (), other => panic!("{:?}", other), } } } #[test] fn test_evq_event() { // Test case: spurious EVQ_EVENT. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); ctx.handler.backend.set_pending_rx(false); match ctx.handler.handle_event(EVQ_EVENT, epoll::Events::EPOLLIN) { Err(DeviceError::FailedReadingQueue { .. }) => (), other => panic!("{:?}", other), } } } #[test] fn test_backend_event() { // Test case: // - a backend event is received; and // - the backend has pending RX data. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); ctx.handler.backend.set_pending_rx(true); ctx.handler .handle_event(BACKEND_EVENT, epoll::Events::EPOLLIN) .unwrap(); // The backend should've received this event. assert_eq!(ctx.handler.backend.evset, Some(epoll::Events::EPOLLIN)); // TX queue processing should've been triggered. assert_eq!(ctx.guest_txvq.used.idx.get(), 1); // RX queue processing should've been triggered. assert_eq!(ctx.guest_rxvq.used.idx.get(), 1); } // Test case: // - a backend event is received; and // - the backend doesn't have any pending RX data. { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); ctx.handler.backend.set_pending_rx(false); ctx.handler .handle_event(BACKEND_EVENT, epoll::Events::EPOLLIN) .unwrap(); // The backend should've received this event. assert_eq!(ctx.handler.backend.evset, Some(epoll::Events::EPOLLIN)); // TX queue processing should've been triggered. assert_eq!(ctx.guest_txvq.used.idx.get(), 1); // The RX queue should've been left untouched. assert_eq!(ctx.guest_rxvq.used.idx.get(), 0); } } #[test] fn test_unknown_event() { let test_ctx = TestContext::new(); let mut ctx = test_ctx.create_epoll_handler_context(); match ctx.handler.handle_event(0xff, epoll::Events::EPOLLIN) { Err(DeviceError::UnknownEvent { .. }) => (), other => panic!("{:?}", other), } } // Creates an epoll handler context and attempts to assemble a VsockPkt from the descriptor // chains available on the rx and tx virtqueues, but first it will set the addr and len // of the descriptor specified by desc_idx to the provided values. We are only using this // function for testing error cases, so the asserts always expect is_err() to be true. When // desc_idx = 0 we are altering the header (first descriptor in the chain), and when // desc_idx = 1 we are altering the packet buffer. fn vsock_bof_helper(test_ctx: &mut TestContext, desc_idx: usize, addr: u64, len: u32) { use vm_memory::GuestAddress; assert!(desc_idx <= 1); { let mut ctx = test_ctx.create_epoll_handler_context(); ctx.guest_rxvq.dtable[desc_idx].addr.set(addr); ctx.guest_rxvq.dtable[desc_idx].len.set(len); // If the descriptor chain is already declared invalid, there's no reason to assemble // a packet. if let Some(rx_desc) = ctx.handler.rxvq.pop(&test_ctx.mem) { assert!(VsockPacket::from_rx_virtq_head(&rx_desc).is_err()); } } { let mut ctx = test_ctx.create_epoll_handler_context(); // When modifiyng the buffer descriptor, make sure the len field is altered in the // vsock packet header descriptor as well. if desc_idx == 1 { // The vsock packet len field has offset 24 in the header. let hdr_len_addr = GuestAddress(ctx.guest_txvq.dtable[0].addr.get() + 24); test_ctx .mem .write_obj(len.to_le_bytes(), hdr_len_addr) .unwrap(); } ctx.guest_txvq.dtable[desc_idx].addr.set(addr); ctx.guest_txvq.dtable[desc_idx].len.set(len); if let Some(tx_desc) = ctx.handler.txvq.pop(&test_ctx.mem) { assert!(VsockPacket::from_tx_virtq_head(&tx_desc).is_err()); } } } #[test] fn test_vsock_bof() { use vm_memory::GuestAddress; const GAP_SIZE: usize = 768 << 20; const FIRST_AFTER_GAP: usize = 1 << 32; const GAP_START_ADDR: usize = FIRST_AFTER_GAP - GAP_SIZE; const MIB: usize = 1 << 20; let mut test_ctx = TestContext::new(); test_ctx.mem = GuestMemory::new(&[ (GuestAddress(0), 8 * MIB), (GuestAddress((GAP_START_ADDR - MIB) as u64), MIB), (GuestAddress(FIRST_AFTER_GAP as u64), MIB), ]) .unwrap(); // The default configured descriptor chains are valid. { let mut ctx = test_ctx.create_epoll_handler_context(); let rx_desc = ctx.handler.rxvq.pop(&test_ctx.mem).unwrap(); assert!(VsockPacket::from_rx_virtq_head(&rx_desc).is_ok()); } { let mut ctx = test_ctx.create_epoll_handler_context(); let tx_desc = ctx.handler.txvq.pop(&test_ctx.mem).unwrap(); assert!(VsockPacket::from_tx_virtq_head(&tx_desc).is_ok()); } // Let's check what happens when the header descriptor is right before the gap. vsock_bof_helper( &mut test_ctx, 0, GAP_START_ADDR as u64 - 1, VSOCK_PKT_HDR_SIZE as u32, ); // Let's check what happens when the buffer descriptor crosses into the gap, but does // not go past its right edge. vsock_bof_helper( &mut test_ctx, 1, GAP_START_ADDR as u64 - 4, GAP_SIZE as u32 + 4, ); // Let's modify the buffer descriptor addr and len such that it crosses over the MMIO gap, // and check we cannot assemble the VsockPkts. vsock_bof_helper( &mut test_ctx, 1, GAP_START_ADDR as u64 - 4, GAP_SIZE as u32 + 100, ); } }
#[doc = "Reader of register PUCRC"] pub type R = crate::R<u32, super::PUCRC>; #[doc = "Writer for register PUCRC"] pub type W = crate::W<u32, super::PUCRC>; #[doc = "Register PUCRC `reset()`'s with value 0"] impl crate::ResetValue for super::PUCRC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `PU15`"] pub type PU15_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PU15`"] pub struct PU15_W<'a> { w: &'a mut W, } impl<'a> PU15_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15); self.w } } #[doc = "Reader of field `PU14`"] pub type PU14_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PU14`"] pub struct PU14_W<'a> { w: &'a mut W, } impl<'a> PU14_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14); self.w } } #[doc = "Reader of field `PU13`"] pub type PU13_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PU13`"] pub struct PU13_W<'a> { w: &'a mut W, } impl<'a> PU13_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13); self.w } } #[doc = "Reader of field `PU7`"] pub type PU7_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PU7`"] pub struct PU7_W<'a> { w: &'a mut W, } impl<'a> PU7_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 << 7)) | (((value as u32) & 0x01) << 7); self.w } } #[doc = "Reader of field `PU6`"] pub type PU6_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PU6`"] pub struct PU6_W<'a> { w: &'a mut W, } impl<'a> PU6_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 << 6)) | (((value as u32) & 0x01) << 6); self.w } } impl R { #[doc = "Bit 15 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu15(&self) -> PU15_R { PU15_R::new(((self.bits >> 15) & 0x01) != 0) } #[doc = "Bit 14 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu14(&self) -> PU14_R { PU14_R::new(((self.bits >> 14) & 0x01) != 0) } #[doc = "Bit 13 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu13(&self) -> PU13_R { PU13_R::new(((self.bits >> 13) & 0x01) != 0) } #[doc = "Bit 7 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu7(&self) -> PU7_R { PU7_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 6 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu6(&self) -> PU6_R { PU6_R::new(((self.bits >> 6) & 0x01) != 0) } } impl W { #[doc = "Bit 15 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu15(&mut self) -> PU15_W { PU15_W { w: self } } #[doc = "Bit 14 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu14(&mut self) -> PU14_W { PU14_W { w: self } } #[doc = "Bit 13 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu13(&mut self) -> PU13_W { PU13_W { w: self } } #[doc = "Bit 7 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu7(&mut self) -> PU7_W { PU7_W { w: self } } #[doc = "Bit 6 - Port C pull-up bit y (y=0..15)"] #[inline(always)] pub fn pu6(&mut self) -> PU6_W { PU6_W { w: self } } }
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. use AlertMethods; use cocoa::appkit::{NSPoint, NSRect, NSSize}; use cocoa::base::{objc_getClass, sel_registerName}; use cocoa::base; use std::mem::{transmute, transmute_copy}; use std::from_str::FromStr; use core_foundation::base::TCFType; use core_foundation::string::CFString; /// The low-level alert type. struct NSAlert; /// The low-level type of a text field. struct NSTextField; /// An alert. pub struct Alert { nsalert: *mut NSAlert, nstextfield: Option<*mut NSTextField>, } impl AlertMethods for Alert { /// Creates a new alert with an OK and Cancel button. fn new(message_text: &str) -> Alert { unsafe { let alert_string: CFString = FromStr::from_str(message_text).unwrap(); let cancel_string = CFString::from_static_string("Cancel"); let empty_string = CFString::from_static_string(""); let class = objc_getClass(transmute(&"NSAlert".as_bytes()[0])); let selector = sel_registerName(transmute(&"alertWithMessageText:defaultButton:\ alternateButton:otherButton:\ informativeTextWithFormat:".as_bytes()[0])); let nsalert = base::invoke_msg_id_id_id_id_id_id(class, selector, transmute_copy(&alert_string), transmute(0u), transmute_copy(&cancel_string), transmute(0u), transmute_copy(&empty_string)); Alert { nsalert: transmute(nsalert), nstextfield: None, } } } fn add_prompt(&mut self) { unsafe { // [NSTextField alloc] let class = objc_getClass(transmute(&"NSTextField".as_bytes()[0])); let selector = sel_registerName(transmute(&"alloc".as_bytes()[0])); let nstextfield = base::invoke_msg_id(class, selector); // [nstextfield initWithFrame: NSMakeRect(0, 0, 200, 24)] let selector = sel_registerName(transmute(&"initWithFrame:".as_bytes()[0])); let frame = NSRect { origin: NSPoint::new(0.0, 0.0), size: NSSize::new(200.0, 24.0), }; let nstextfield = base::invoke_msg_id_NSRect(nstextfield, selector, &frame); // [nsalert setAccessoryView: nstextfield]; let selector = sel_registerName(transmute(&"setAccessoryView:".as_bytes()[0])); base::invoke_msg_void_id(transmute(self.nsalert), selector, nstextfield); // [nsalert layout]; let selector = sel_registerName(transmute(&"layout".as_bytes()[0])); base::invoke_msg_void(transmute(self.nsalert), selector); self.nstextfield = Some(transmute(nstextfield)) } } fn run(&self) { unsafe { let selector = sel_registerName(transmute(&"runModal".as_bytes()[0])); base::invoke_msg_void(transmute(self.nsalert), selector) } } fn prompt_value(&self) -> String { unsafe { // [nstextfield stringValue] let selector = sel_registerName(transmute(&"stringValue".as_bytes()[0])); match self.nstextfield { None => panic!("No prompt!"), Some(nstextfield) => { let string = base::invoke_msg_id(transmute(nstextfield), selector); let result: CFString = TCFType::wrap_under_get_rule(transmute(string)); result.to_string() } } } } }
use std::fs; fn main() { fs::create_dir("test1"); fs::remove_dir_all("test1"); }
use wasm_bindgen::JsCast; use web_sys::{HtmlCanvasElement, WebGlRenderingContext}; use crate::render::render_target::{RenderScene, RenderTarget}; use super::triangles::TriangleScene; pub struct WebglRenderTarget { canvas: HtmlCanvasElement, context: WebGlRenderingContext, } impl WebglRenderTarget { pub fn new(canvas: HtmlCanvasElement) -> WebglRenderTarget { let context = canvas.get_context("webgl").unwrap(); let context = context.unwrap_or_else(|| canvas.get_context("experimental-webgl").unwrap().unwrap()); let context = context.dyn_into::<WebGlRenderingContext>().unwrap(); WebglRenderTarget { canvas, context } } pub fn get_context(&self) -> &WebGlRenderingContext { &self.context } } impl RenderTarget for WebglRenderTarget { type RenderScene<T: RenderScene> = TriangleScene<T>; fn resize(&mut self, width: u32, height: u32) { self.canvas.set_width(width); self.canvas.set_height(height); } fn get_size(&self) -> (u32, u32) { (self.canvas.width(), self.canvas.height()) } fn new_scene<R>(&mut self, scene: R) -> TriangleScene<R> where R: RenderScene, { TriangleScene::new(scene, &self.context) } fn render_one<'a, R>( &'a mut self, scene: &'a mut TriangleScene<R>, scene_context: R::Context<'a>, ) where R: RenderScene, { self.context.viewport( 0, 0, self.canvas.width() as i32, self.canvas.height() as i32, ); scene.render_one(scene_context, &self.context); } }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct BackgroundDownloadProgress { pub BytesReceived: u64, pub TotalBytesToReceive: u64, pub Status: BackgroundTransferStatus, pub HasResponseChanged: bool, pub HasRestarted: bool, } impl BackgroundDownloadProgress {} impl ::core::default::Default for BackgroundDownloadProgress { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for BackgroundDownloadProgress { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("BackgroundDownloadProgress").field("BytesReceived", &self.BytesReceived).field("TotalBytesToReceive", &self.TotalBytesToReceive).field("Status", &self.Status).field("HasResponseChanged", &self.HasResponseChanged).field("HasRestarted", &self.HasRestarted).finish() } } impl ::core::cmp::PartialEq for BackgroundDownloadProgress { fn eq(&self, other: &Self) -> bool { self.BytesReceived == other.BytesReceived && self.TotalBytesToReceive == other.TotalBytesToReceive && self.Status == other.Status && self.HasResponseChanged == other.HasResponseChanged && self.HasRestarted == other.HasRestarted } } impl ::core::cmp::Eq for BackgroundDownloadProgress {} unsafe impl ::windows::core::Abi for BackgroundDownloadProgress { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BackgroundDownloadProgress { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Networking.BackgroundTransfer.BackgroundDownloadProgress;u8;u8;enum(Windows.Networking.BackgroundTransfer.BackgroundTransferStatus;i4);b1;b1)"); } impl ::windows::core::DefaultType for BackgroundDownloadProgress { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BackgroundDownloader(pub ::windows::core::IInspectable); impl BackgroundDownloader { 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<BackgroundDownloader, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(all(feature = "Foundation", feature = "Storage"))] pub fn CreateDownload<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFile>>(&self, uri: Param0, resultfile: Param1) -> ::windows::core::Result<DownloadOperation> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uri.into_param().abi(), resultfile.into_param().abi(), &mut result__).from_abi::<DownloadOperation>(result__) } } #[cfg(all(feature = "Foundation", feature = "Storage"))] pub fn CreateDownloadFromFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFile>, Param2: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFile>>(&self, uri: Param0, resultfile: Param1, requestbodyfile: Param2) -> ::windows::core::Result<DownloadOperation> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), uri.into_param().abi(), resultfile.into_param().abi(), requestbodyfile.into_param().abi(), &mut result__).from_abi::<DownloadOperation>(result__) } } #[cfg(all(feature = "Foundation", feature = "Storage", feature = "Storage_Streams"))] pub fn CreateDownloadAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFile>, Param2: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IInputStream>>(&self, uri: Param0, resultfile: Param1, requestbodystream: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<DownloadOperation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), uri.into_param().abi(), resultfile.into_param().abi(), requestbodystream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<DownloadOperation>>(result__) } } pub fn TransferGroup(&self) -> ::windows::core::Result<BackgroundTransferGroup> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(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::<BackgroundTransferGroup>(result__) } } pub fn SetTransferGroup<'a, Param0: ::windows::core::IntoParam<'a, BackgroundTransferGroup>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "UI_Notifications")] pub fn SuccessToastNotification(&self) -> ::windows::core::Result<super::super::UI::Notifications::ToastNotification> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(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::UI::Notifications::ToastNotification>(result__) } } #[cfg(feature = "UI_Notifications")] pub fn SetSuccessToastNotification<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Notifications::ToastNotification>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "UI_Notifications")] pub fn FailureToastNotification(&self) -> ::windows::core::Result<super::super::UI::Notifications::ToastNotification> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(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::UI::Notifications::ToastNotification>(result__) } } #[cfg(feature = "UI_Notifications")] pub fn SetFailureToastNotification<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Notifications::ToastNotification>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "UI_Notifications")] pub fn SuccessTileNotification(&self) -> ::windows::core::Result<super::super::UI::Notifications::TileNotification> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(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::UI::Notifications::TileNotification>(result__) } } #[cfg(feature = "UI_Notifications")] pub fn SetSuccessTileNotification<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Notifications::TileNotification>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "UI_Notifications")] pub fn FailureTileNotification(&self) -> ::windows::core::Result<super::super::UI::Notifications::TileNotification> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::UI::Notifications::TileNotification>(result__) } } #[cfg(feature = "UI_Notifications")] pub fn SetFailureTileNotification<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Notifications::TileNotification>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn CompletionGroup(&self) -> ::windows::core::Result<BackgroundTransferCompletionGroup> { let this = &::windows::core::Interface::cast::<IBackgroundDownloader3>(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::<BackgroundTransferCompletionGroup>(result__) } } pub fn SetRequestHeader<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, headername: Param0, headervalue: Param1) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), headername.into_param().abi(), headervalue.into_param().abi()).ok() } } #[cfg(feature = "Security_Credentials")] pub fn ServerCredential(&self) -> ::windows::core::Result<super::super::Security::Credentials::PasswordCredential> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(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::Security::Credentials::PasswordCredential>(result__) } } #[cfg(feature = "Security_Credentials")] pub fn SetServerCredential<'a, Param0: ::windows::core::IntoParam<'a, super::super::Security::Credentials::PasswordCredential>>(&self, credential: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), credential.into_param().abi()).ok() } } #[cfg(feature = "Security_Credentials")] pub fn ProxyCredential(&self) -> ::windows::core::Result<super::super::Security::Credentials::PasswordCredential> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Security::Credentials::PasswordCredential>(result__) } } #[cfg(feature = "Security_Credentials")] pub fn SetProxyCredential<'a, Param0: ::windows::core::IntoParam<'a, super::super::Security::Credentials::PasswordCredential>>(&self, credential: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), credential.into_param().abi()).ok() } } pub fn Method(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetMethod<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn Group(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn SetGroup<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn CostPolicy(&self) -> ::windows::core::Result<BackgroundTransferCostPolicy> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { let mut result__: BackgroundTransferCostPolicy = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferCostPolicy>(result__) } } pub fn SetCostPolicy(&self, value: BackgroundTransferCostPolicy) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value).ok() } } pub fn CreateWithCompletionGroup<'a, Param0: ::windows::core::IntoParam<'a, BackgroundTransferCompletionGroup>>(completiongroup: Param0) -> ::windows::core::Result<BackgroundDownloader> { Self::IBackgroundDownloaderFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), completiongroup.into_param().abi(), &mut result__).from_abi::<BackgroundDownloader>(result__) }) } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetCurrentDownloadsAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<DownloadOperation>>> { Self::IBackgroundDownloaderStaticMethods(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<DownloadOperation>>>(result__) }) } #[cfg(feature = "deprecated")] #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetCurrentDownloadsForGroupAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(group: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<DownloadOperation>>> { Self::IBackgroundDownloaderStaticMethods(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), group.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<DownloadOperation>>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetCurrentDownloadsForTransferGroupAsync<'a, Param0: ::windows::core::IntoParam<'a, BackgroundTransferGroup>>(group: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<DownloadOperation>>> { Self::IBackgroundDownloaderStaticMethods2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), group.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<DownloadOperation>>>(result__) }) } #[cfg(feature = "deprecated")] #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn RequestUnconstrainedDownloadsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<DownloadOperation>>>(operations: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<UnconstrainedTransferRequestResult>> { Self::IBackgroundDownloaderUserConsent(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), operations.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<UnconstrainedTransferRequestResult>>(result__) }) } pub fn IBackgroundDownloaderFactory<R, F: FnOnce(&IBackgroundDownloaderFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundDownloader, IBackgroundDownloaderFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IBackgroundDownloaderStaticMethods<R, F: FnOnce(&IBackgroundDownloaderStaticMethods) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundDownloader, IBackgroundDownloaderStaticMethods> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IBackgroundDownloaderStaticMethods2<R, F: FnOnce(&IBackgroundDownloaderStaticMethods2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundDownloader, IBackgroundDownloaderStaticMethods2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IBackgroundDownloaderUserConsent<R, F: FnOnce(&IBackgroundDownloaderUserConsent) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundDownloader, IBackgroundDownloaderUserConsent> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for BackgroundDownloader { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.BackgroundDownloader;{c1c79333-6649-4b1d-a826-a4b3dd234d0b})"); } unsafe impl ::windows::core::Interface for BackgroundDownloader { type Vtable = IBackgroundDownloader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc1c79333_6649_4b1d_a826_a4b3dd234d0b); } impl ::windows::core::RuntimeName for BackgroundDownloader { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.BackgroundDownloader"; } impl ::core::convert::From<BackgroundDownloader> for ::windows::core::IUnknown { fn from(value: BackgroundDownloader) -> Self { value.0 .0 } } impl ::core::convert::From<&BackgroundDownloader> for ::windows::core::IUnknown { fn from(value: &BackgroundDownloader) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BackgroundDownloader { 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 BackgroundDownloader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BackgroundDownloader> for ::windows::core::IInspectable { fn from(value: BackgroundDownloader) -> Self { value.0 } } impl ::core::convert::From<&BackgroundDownloader> for ::windows::core::IInspectable { fn from(value: &BackgroundDownloader) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BackgroundDownloader { 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 BackgroundDownloader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<BackgroundDownloader> for IBackgroundTransferBase { type Error = ::windows::core::Error; fn try_from(value: BackgroundDownloader) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&BackgroundDownloader> for IBackgroundTransferBase { type Error = ::windows::core::Error; fn try_from(value: &BackgroundDownloader) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferBase> for BackgroundDownloader { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferBase> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferBase> for &BackgroundDownloader { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferBase> { ::core::convert::TryInto::<IBackgroundTransferBase>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for BackgroundDownloader {} unsafe impl ::core::marker::Sync for BackgroundDownloader {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct BackgroundTransferBehavior(pub i32); impl BackgroundTransferBehavior { pub const Parallel: BackgroundTransferBehavior = BackgroundTransferBehavior(0i32); pub const Serialized: BackgroundTransferBehavior = BackgroundTransferBehavior(1i32); } impl ::core::convert::From<i32> for BackgroundTransferBehavior { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for BackgroundTransferBehavior { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BackgroundTransferBehavior { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.BackgroundTransfer.BackgroundTransferBehavior;i4)"); } impl ::windows::core::DefaultType for BackgroundTransferBehavior { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BackgroundTransferCompletionGroup(pub ::windows::core::IInspectable); impl BackgroundTransferCompletionGroup { 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<BackgroundTransferCompletionGroup, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(feature = "ApplicationModel_Background")] pub fn Trigger(&self) -> ::windows::core::Result<super::super::ApplicationModel::Background::IBackgroundTrigger> { 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::ApplicationModel::Background::IBackgroundTrigger>(result__) } } pub fn IsEnabled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn Enable(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this)).ok() } } } unsafe impl ::windows::core::RuntimeType for BackgroundTransferCompletionGroup { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.BackgroundTransferCompletionGroup;{2d930225-986b-574d-7950-0add47f5d706})"); } unsafe impl ::windows::core::Interface for BackgroundTransferCompletionGroup { type Vtable = IBackgroundTransferCompletionGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2d930225_986b_574d_7950_0add47f5d706); } impl ::windows::core::RuntimeName for BackgroundTransferCompletionGroup { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.BackgroundTransferCompletionGroup"; } impl ::core::convert::From<BackgroundTransferCompletionGroup> for ::windows::core::IUnknown { fn from(value: BackgroundTransferCompletionGroup) -> Self { value.0 .0 } } impl ::core::convert::From<&BackgroundTransferCompletionGroup> for ::windows::core::IUnknown { fn from(value: &BackgroundTransferCompletionGroup) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BackgroundTransferCompletionGroup { 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 BackgroundTransferCompletionGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BackgroundTransferCompletionGroup> for ::windows::core::IInspectable { fn from(value: BackgroundTransferCompletionGroup) -> Self { value.0 } } impl ::core::convert::From<&BackgroundTransferCompletionGroup> for ::windows::core::IInspectable { fn from(value: &BackgroundTransferCompletionGroup) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BackgroundTransferCompletionGroup { 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 BackgroundTransferCompletionGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BackgroundTransferCompletionGroup {} unsafe impl ::core::marker::Sync for BackgroundTransferCompletionGroup {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BackgroundTransferCompletionGroupTriggerDetails(pub ::windows::core::IInspectable); impl BackgroundTransferCompletionGroupTriggerDetails { #[cfg(feature = "Foundation_Collections")] pub fn Downloads(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<DownloadOperation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVectorView<DownloadOperation>>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Uploads(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<UploadOperation>> { 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::<super::super::Foundation::Collections::IVectorView<UploadOperation>>(result__) } } } unsafe impl ::windows::core::RuntimeType for BackgroundTransferCompletionGroupTriggerDetails { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.BackgroundTransferCompletionGroupTriggerDetails;{7b6be286-6e47-5136-7fcb-fa4389f46f5b})"); } unsafe impl ::windows::core::Interface for BackgroundTransferCompletionGroupTriggerDetails { type Vtable = IBackgroundTransferCompletionGroupTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7b6be286_6e47_5136_7fcb_fa4389f46f5b); } impl ::windows::core::RuntimeName for BackgroundTransferCompletionGroupTriggerDetails { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.BackgroundTransferCompletionGroupTriggerDetails"; } impl ::core::convert::From<BackgroundTransferCompletionGroupTriggerDetails> for ::windows::core::IUnknown { fn from(value: BackgroundTransferCompletionGroupTriggerDetails) -> Self { value.0 .0 } } impl ::core::convert::From<&BackgroundTransferCompletionGroupTriggerDetails> for ::windows::core::IUnknown { fn from(value: &BackgroundTransferCompletionGroupTriggerDetails) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BackgroundTransferCompletionGroupTriggerDetails { 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 BackgroundTransferCompletionGroupTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BackgroundTransferCompletionGroupTriggerDetails> for ::windows::core::IInspectable { fn from(value: BackgroundTransferCompletionGroupTriggerDetails) -> Self { value.0 } } impl ::core::convert::From<&BackgroundTransferCompletionGroupTriggerDetails> for ::windows::core::IInspectable { fn from(value: &BackgroundTransferCompletionGroupTriggerDetails) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BackgroundTransferCompletionGroupTriggerDetails { 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 BackgroundTransferCompletionGroupTriggerDetails { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BackgroundTransferCompletionGroupTriggerDetails {} unsafe impl ::core::marker::Sync for BackgroundTransferCompletionGroupTriggerDetails {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BackgroundTransferContentPart(pub ::windows::core::IInspectable); impl BackgroundTransferContentPart { 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<BackgroundTransferContentPart, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn SetHeader<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, headername: Param0, headervalue: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), headername.into_param().abi(), headervalue.into_param().abi()).ok() } } pub fn SetText<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&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 = "Storage")] pub fn SetFile<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFile>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn CreateWithName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(name: Param0) -> ::windows::core::Result<BackgroundTransferContentPart> { Self::IBackgroundTransferContentPartFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), name.into_param().abi(), &mut result__).from_abi::<BackgroundTransferContentPart>(result__) }) } pub fn CreateWithNameAndFileName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(name: Param0, filename: Param1) -> ::windows::core::Result<BackgroundTransferContentPart> { Self::IBackgroundTransferContentPartFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), name.into_param().abi(), filename.into_param().abi(), &mut result__).from_abi::<BackgroundTransferContentPart>(result__) }) } pub fn IBackgroundTransferContentPartFactory<R, F: FnOnce(&IBackgroundTransferContentPartFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundTransferContentPart, IBackgroundTransferContentPartFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for BackgroundTransferContentPart { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart;{e8e15657-d7d1-4ed8-838e-674ac217ace6})"); } unsafe impl ::windows::core::Interface for BackgroundTransferContentPart { type Vtable = IBackgroundTransferContentPart_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe8e15657_d7d1_4ed8_838e_674ac217ace6); } impl ::windows::core::RuntimeName for BackgroundTransferContentPart { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.BackgroundTransferContentPart"; } impl ::core::convert::From<BackgroundTransferContentPart> for ::windows::core::IUnknown { fn from(value: BackgroundTransferContentPart) -> Self { value.0 .0 } } impl ::core::convert::From<&BackgroundTransferContentPart> for ::windows::core::IUnknown { fn from(value: &BackgroundTransferContentPart) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BackgroundTransferContentPart { 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 BackgroundTransferContentPart { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BackgroundTransferContentPart> for ::windows::core::IInspectable { fn from(value: BackgroundTransferContentPart) -> Self { value.0 } } impl ::core::convert::From<&BackgroundTransferContentPart> for ::windows::core::IInspectable { fn from(value: &BackgroundTransferContentPart) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BackgroundTransferContentPart { 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 BackgroundTransferContentPart { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BackgroundTransferContentPart {} unsafe impl ::core::marker::Sync for BackgroundTransferContentPart {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct BackgroundTransferCostPolicy(pub i32); impl BackgroundTransferCostPolicy { pub const Default: BackgroundTransferCostPolicy = BackgroundTransferCostPolicy(0i32); pub const UnrestrictedOnly: BackgroundTransferCostPolicy = BackgroundTransferCostPolicy(1i32); pub const Always: BackgroundTransferCostPolicy = BackgroundTransferCostPolicy(2i32); } impl ::core::convert::From<i32> for BackgroundTransferCostPolicy { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for BackgroundTransferCostPolicy { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BackgroundTransferCostPolicy { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.BackgroundTransfer.BackgroundTransferCostPolicy;i4)"); } impl ::windows::core::DefaultType for BackgroundTransferCostPolicy { type DefaultType = Self; } pub struct BackgroundTransferError {} impl BackgroundTransferError { #[cfg(feature = "Web")] pub fn GetStatus(hresult: i32) -> ::windows::core::Result<super::super::Web::WebErrorStatus> { Self::IBackgroundTransferErrorStaticMethods(|this| unsafe { let mut result__: super::super::Web::WebErrorStatus = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), hresult, &mut result__).from_abi::<super::super::Web::WebErrorStatus>(result__) }) } pub fn IBackgroundTransferErrorStaticMethods<R, F: FnOnce(&IBackgroundTransferErrorStaticMethods) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundTransferError, IBackgroundTransferErrorStaticMethods> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for BackgroundTransferError { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.BackgroundTransferError"; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct BackgroundTransferFileRange { pub Offset: u64, pub Length: u64, } impl BackgroundTransferFileRange {} impl ::core::default::Default for BackgroundTransferFileRange { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for BackgroundTransferFileRange { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("BackgroundTransferFileRange").field("Offset", &self.Offset).field("Length", &self.Length).finish() } } impl ::core::cmp::PartialEq for BackgroundTransferFileRange { fn eq(&self, other: &Self) -> bool { self.Offset == other.Offset && self.Length == other.Length } } impl ::core::cmp::Eq for BackgroundTransferFileRange {} unsafe impl ::windows::core::Abi for BackgroundTransferFileRange { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BackgroundTransferFileRange { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Networking.BackgroundTransfer.BackgroundTransferFileRange;u8;u8)"); } impl ::windows::core::DefaultType for BackgroundTransferFileRange { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BackgroundTransferGroup(pub ::windows::core::IInspectable); impl BackgroundTransferGroup { pub fn Name(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = self; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn TransferBehavior(&self) -> ::windows::core::Result<BackgroundTransferBehavior> { let this = self; unsafe { let mut result__: BackgroundTransferBehavior = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferBehavior>(result__) } } pub fn SetTransferBehavior(&self, value: BackgroundTransferBehavior) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() } } pub fn CreateGroup<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(name: Param0) -> ::windows::core::Result<BackgroundTransferGroup> { Self::IBackgroundTransferGroupStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), name.into_param().abi(), &mut result__).from_abi::<BackgroundTransferGroup>(result__) }) } pub fn IBackgroundTransferGroupStatics<R, F: FnOnce(&IBackgroundTransferGroupStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundTransferGroup, IBackgroundTransferGroupStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for BackgroundTransferGroup { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.BackgroundTransferGroup;{d8c3e3e4-6459-4540-85eb-aaa1c8903677})"); } unsafe impl ::windows::core::Interface for BackgroundTransferGroup { type Vtable = IBackgroundTransferGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd8c3e3e4_6459_4540_85eb_aaa1c8903677); } impl ::windows::core::RuntimeName for BackgroundTransferGroup { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.BackgroundTransferGroup"; } impl ::core::convert::From<BackgroundTransferGroup> for ::windows::core::IUnknown { fn from(value: BackgroundTransferGroup) -> Self { value.0 .0 } } impl ::core::convert::From<&BackgroundTransferGroup> for ::windows::core::IUnknown { fn from(value: &BackgroundTransferGroup) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BackgroundTransferGroup { 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 BackgroundTransferGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BackgroundTransferGroup> for ::windows::core::IInspectable { fn from(value: BackgroundTransferGroup) -> Self { value.0 } } impl ::core::convert::From<&BackgroundTransferGroup> for ::windows::core::IInspectable { fn from(value: &BackgroundTransferGroup) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BackgroundTransferGroup { 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 BackgroundTransferGroup { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BackgroundTransferGroup {} unsafe impl ::core::marker::Sync for BackgroundTransferGroup {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct BackgroundTransferPriority(pub i32); impl BackgroundTransferPriority { pub const Default: BackgroundTransferPriority = BackgroundTransferPriority(0i32); pub const High: BackgroundTransferPriority = BackgroundTransferPriority(1i32); pub const Low: BackgroundTransferPriority = BackgroundTransferPriority(2i32); } impl ::core::convert::From<i32> for BackgroundTransferPriority { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for BackgroundTransferPriority { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BackgroundTransferPriority { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.BackgroundTransfer.BackgroundTransferPriority;i4)"); } impl ::windows::core::DefaultType for BackgroundTransferPriority { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BackgroundTransferRangesDownloadedEventArgs(pub ::windows::core::IInspectable); impl BackgroundTransferRangesDownloadedEventArgs { pub fn WasDownloadRestarted(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn AddedRanges(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<BackgroundTransferFileRange>> { 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::<super::super::Foundation::Collections::IVector<BackgroundTransferFileRange>>(result__) } } #[cfg(feature = "Foundation")] pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::Foundation::Deferral> { 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::Foundation::Deferral>(result__) } } } unsafe impl ::windows::core::RuntimeType for BackgroundTransferRangesDownloadedEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.BackgroundTransferRangesDownloadedEventArgs;{3ebc7453-bf48-4a88-9248-b0c165184f5c})"); } unsafe impl ::windows::core::Interface for BackgroundTransferRangesDownloadedEventArgs { type Vtable = IBackgroundTransferRangesDownloadedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3ebc7453_bf48_4a88_9248_b0c165184f5c); } impl ::windows::core::RuntimeName for BackgroundTransferRangesDownloadedEventArgs { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.BackgroundTransferRangesDownloadedEventArgs"; } impl ::core::convert::From<BackgroundTransferRangesDownloadedEventArgs> for ::windows::core::IUnknown { fn from(value: BackgroundTransferRangesDownloadedEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&BackgroundTransferRangesDownloadedEventArgs> for ::windows::core::IUnknown { fn from(value: &BackgroundTransferRangesDownloadedEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BackgroundTransferRangesDownloadedEventArgs { 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 BackgroundTransferRangesDownloadedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BackgroundTransferRangesDownloadedEventArgs> for ::windows::core::IInspectable { fn from(value: BackgroundTransferRangesDownloadedEventArgs) -> Self { value.0 } } impl ::core::convert::From<&BackgroundTransferRangesDownloadedEventArgs> for ::windows::core::IInspectable { fn from(value: &BackgroundTransferRangesDownloadedEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BackgroundTransferRangesDownloadedEventArgs { 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 BackgroundTransferRangesDownloadedEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for BackgroundTransferRangesDownloadedEventArgs {} unsafe impl ::core::marker::Sync for BackgroundTransferRangesDownloadedEventArgs {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct BackgroundTransferStatus(pub i32); impl BackgroundTransferStatus { pub const Idle: BackgroundTransferStatus = BackgroundTransferStatus(0i32); pub const Running: BackgroundTransferStatus = BackgroundTransferStatus(1i32); pub const PausedByApplication: BackgroundTransferStatus = BackgroundTransferStatus(2i32); pub const PausedCostedNetwork: BackgroundTransferStatus = BackgroundTransferStatus(3i32); pub const PausedNoNetwork: BackgroundTransferStatus = BackgroundTransferStatus(4i32); pub const Completed: BackgroundTransferStatus = BackgroundTransferStatus(5i32); pub const Canceled: BackgroundTransferStatus = BackgroundTransferStatus(6i32); pub const Error: BackgroundTransferStatus = BackgroundTransferStatus(7i32); pub const PausedRecoverableWebErrorStatus: BackgroundTransferStatus = BackgroundTransferStatus(8i32); pub const PausedSystemPolicy: BackgroundTransferStatus = BackgroundTransferStatus(32i32); } impl ::core::convert::From<i32> for BackgroundTransferStatus { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for BackgroundTransferStatus { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BackgroundTransferStatus { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Networking.BackgroundTransfer.BackgroundTransferStatus;i4)"); } impl ::windows::core::DefaultType for BackgroundTransferStatus { type DefaultType = Self; } #[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)] #[repr(C)] pub struct BackgroundUploadProgress { pub BytesReceived: u64, pub BytesSent: u64, pub TotalBytesToReceive: u64, pub TotalBytesToSend: u64, pub Status: BackgroundTransferStatus, pub HasResponseChanged: bool, pub HasRestarted: bool, } impl BackgroundUploadProgress {} impl ::core::default::Default for BackgroundUploadProgress { fn default() -> Self { unsafe { ::core::mem::zeroed() } } } impl ::core::fmt::Debug for BackgroundUploadProgress { fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result { fmt.debug_struct("BackgroundUploadProgress") .field("BytesReceived", &self.BytesReceived) .field("BytesSent", &self.BytesSent) .field("TotalBytesToReceive", &self.TotalBytesToReceive) .field("TotalBytesToSend", &self.TotalBytesToSend) .field("Status", &self.Status) .field("HasResponseChanged", &self.HasResponseChanged) .field("HasRestarted", &self.HasRestarted) .finish() } } impl ::core::cmp::PartialEq for BackgroundUploadProgress { fn eq(&self, other: &Self) -> bool { self.BytesReceived == other.BytesReceived && self.BytesSent == other.BytesSent && self.TotalBytesToReceive == other.TotalBytesToReceive && self.TotalBytesToSend == other.TotalBytesToSend && self.Status == other.Status && self.HasResponseChanged == other.HasResponseChanged && self.HasRestarted == other.HasRestarted } } impl ::core::cmp::Eq for BackgroundUploadProgress {} unsafe impl ::windows::core::Abi for BackgroundUploadProgress { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for BackgroundUploadProgress { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"struct(Windows.Networking.BackgroundTransfer.BackgroundUploadProgress;u8;u8;u8;u8;enum(Windows.Networking.BackgroundTransfer.BackgroundTransferStatus;i4);b1;b1)"); } impl ::windows::core::DefaultType for BackgroundUploadProgress { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct BackgroundUploader(pub ::windows::core::IInspectable); impl BackgroundUploader { 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<BackgroundUploader, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } #[cfg(all(feature = "Foundation", feature = "Storage"))] pub fn CreateUpload<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFile>>(&self, uri: Param0, sourcefile: Param1) -> ::windows::core::Result<UploadOperation> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), uri.into_param().abi(), sourcefile.into_param().abi(), &mut result__).from_abi::<UploadOperation>(result__) } } #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub fn CreateUploadFromStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IInputStream>>(&self, uri: Param0, sourcestream: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<UploadOperation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), uri.into_param().abi(), sourcestream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<UploadOperation>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn CreateUploadWithFormDataAndAutoBoundaryAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<BackgroundTransferContentPart>>>(&self, uri: Param0, parts: Param1) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<UploadOperation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), uri.into_param().abi(), parts.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<UploadOperation>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn CreateUploadWithSubTypeAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<BackgroundTransferContentPart>>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, uri: Param0, parts: Param1, subtype: Param2) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<UploadOperation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), uri.into_param().abi(), parts.into_param().abi(), subtype.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<UploadOperation>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn CreateUploadWithSubTypeAndBoundaryAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<BackgroundTransferContentPart>>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param3: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>( &self, uri: Param0, parts: Param1, subtype: Param2, boundary: Param3, ) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<UploadOperation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), uri.into_param().abi(), parts.into_param().abi(), subtype.into_param().abi(), boundary.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<UploadOperation>>(result__) } } pub fn SetRequestHeader<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, headername: Param0, headervalue: Param1) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), headername.into_param().abi(), headervalue.into_param().abi()).ok() } } #[cfg(feature = "Security_Credentials")] pub fn ServerCredential(&self) -> ::windows::core::Result<super::super::Security::Credentials::PasswordCredential> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(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::Security::Credentials::PasswordCredential>(result__) } } #[cfg(feature = "Security_Credentials")] pub fn SetServerCredential<'a, Param0: ::windows::core::IntoParam<'a, super::super::Security::Credentials::PasswordCredential>>(&self, credential: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), credential.into_param().abi()).ok() } } #[cfg(feature = "Security_Credentials")] pub fn ProxyCredential(&self) -> ::windows::core::Result<super::super::Security::Credentials::PasswordCredential> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Security::Credentials::PasswordCredential>(result__) } } #[cfg(feature = "Security_Credentials")] pub fn SetProxyCredential<'a, Param0: ::windows::core::IntoParam<'a, super::super::Security::Credentials::PasswordCredential>>(&self, credential: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), credential.into_param().abi()).ok() } } pub fn Method(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetMethod<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn Group(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn SetGroup<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn CostPolicy(&self) -> ::windows::core::Result<BackgroundTransferCostPolicy> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { let mut result__: BackgroundTransferCostPolicy = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferCostPolicy>(result__) } } pub fn SetCostPolicy(&self, value: BackgroundTransferCostPolicy) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferBase>(self)?; unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value).ok() } } pub fn TransferGroup(&self) -> ::windows::core::Result<BackgroundTransferGroup> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(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::<BackgroundTransferGroup>(result__) } } pub fn SetTransferGroup<'a, Param0: ::windows::core::IntoParam<'a, BackgroundTransferGroup>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "UI_Notifications")] pub fn SuccessToastNotification(&self) -> ::windows::core::Result<super::super::UI::Notifications::ToastNotification> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(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::UI::Notifications::ToastNotification>(result__) } } #[cfg(feature = "UI_Notifications")] pub fn SetSuccessToastNotification<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Notifications::ToastNotification>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "UI_Notifications")] pub fn FailureToastNotification(&self) -> ::windows::core::Result<super::super::UI::Notifications::ToastNotification> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(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::UI::Notifications::ToastNotification>(result__) } } #[cfg(feature = "UI_Notifications")] pub fn SetFailureToastNotification<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Notifications::ToastNotification>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "UI_Notifications")] pub fn SuccessTileNotification(&self) -> ::windows::core::Result<super::super::UI::Notifications::TileNotification> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(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::UI::Notifications::TileNotification>(result__) } } #[cfg(feature = "UI_Notifications")] pub fn SetSuccessTileNotification<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Notifications::TileNotification>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "UI_Notifications")] pub fn FailureTileNotification(&self) -> ::windows::core::Result<super::super::UI::Notifications::TileNotification> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::UI::Notifications::TileNotification>(result__) } } #[cfg(feature = "UI_Notifications")] pub fn SetFailureTileNotification<'a, Param0: ::windows::core::IntoParam<'a, super::super::UI::Notifications::TileNotification>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundUploader2>(self)?; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } pub fn CompletionGroup(&self) -> ::windows::core::Result<BackgroundTransferCompletionGroup> { let this = &::windows::core::Interface::cast::<IBackgroundUploader3>(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::<BackgroundTransferCompletionGroup>(result__) } } pub fn CreateWithCompletionGroup<'a, Param0: ::windows::core::IntoParam<'a, BackgroundTransferCompletionGroup>>(completiongroup: Param0) -> ::windows::core::Result<BackgroundUploader> { Self::IBackgroundUploaderFactory(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), completiongroup.into_param().abi(), &mut result__).from_abi::<BackgroundUploader>(result__) }) } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetCurrentUploadsAsync() -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<UploadOperation>>> { Self::IBackgroundUploaderStaticMethods(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<UploadOperation>>>(result__) }) } #[cfg(feature = "deprecated")] #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetCurrentUploadsForGroupAsync<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(group: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<UploadOperation>>> { Self::IBackgroundUploaderStaticMethods(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), group.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<UploadOperation>>>(result__) }) } #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn GetCurrentUploadsForTransferGroupAsync<'a, Param0: ::windows::core::IntoParam<'a, BackgroundTransferGroup>>(group: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<UploadOperation>>> { Self::IBackgroundUploaderStaticMethods2(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), group.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<super::super::Foundation::Collections::IVectorView<UploadOperation>>>(result__) }) } #[cfg(feature = "deprecated")] #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn RequestUnconstrainedUploadsAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<UploadOperation>>>(operations: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<UnconstrainedTransferRequestResult>> { Self::IBackgroundUploaderUserConsent(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), operations.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<UnconstrainedTransferRequestResult>>(result__) }) } pub fn IBackgroundUploaderFactory<R, F: FnOnce(&IBackgroundUploaderFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundUploader, IBackgroundUploaderFactory> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IBackgroundUploaderStaticMethods<R, F: FnOnce(&IBackgroundUploaderStaticMethods) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundUploader, IBackgroundUploaderStaticMethods> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IBackgroundUploaderStaticMethods2<R, F: FnOnce(&IBackgroundUploaderStaticMethods2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundUploader, IBackgroundUploaderStaticMethods2> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IBackgroundUploaderUserConsent<R, F: FnOnce(&IBackgroundUploaderUserConsent) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<BackgroundUploader, IBackgroundUploaderUserConsent> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for BackgroundUploader { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.BackgroundUploader;{c595c9ae-cead-465b-8801-c55ac90a01ce})"); } unsafe impl ::windows::core::Interface for BackgroundUploader { type Vtable = IBackgroundUploader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc595c9ae_cead_465b_8801_c55ac90a01ce); } impl ::windows::core::RuntimeName for BackgroundUploader { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.BackgroundUploader"; } impl ::core::convert::From<BackgroundUploader> for ::windows::core::IUnknown { fn from(value: BackgroundUploader) -> Self { value.0 .0 } } impl ::core::convert::From<&BackgroundUploader> for ::windows::core::IUnknown { fn from(value: &BackgroundUploader) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for BackgroundUploader { 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 BackgroundUploader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<BackgroundUploader> for ::windows::core::IInspectable { fn from(value: BackgroundUploader) -> Self { value.0 } } impl ::core::convert::From<&BackgroundUploader> for ::windows::core::IInspectable { fn from(value: &BackgroundUploader) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for BackgroundUploader { 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 BackgroundUploader { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<BackgroundUploader> for IBackgroundTransferBase { type Error = ::windows::core::Error; fn try_from(value: BackgroundUploader) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&BackgroundUploader> for IBackgroundTransferBase { type Error = ::windows::core::Error; fn try_from(value: &BackgroundUploader) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferBase> for BackgroundUploader { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferBase> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferBase> for &BackgroundUploader { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferBase> { ::core::convert::TryInto::<IBackgroundTransferBase>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for BackgroundUploader {} unsafe impl ::core::marker::Sync for BackgroundUploader {} pub struct ContentPrefetcher {} impl ContentPrefetcher { #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub fn ContentUris() -> ::windows::core::Result<super::super::Foundation::Collections::IVector<super::super::Foundation::Uri>> { Self::IContentPrefetcher(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<super::super::Foundation::Uri>>(result__) }) } #[cfg(feature = "Foundation")] pub fn SetIndirectContentUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(value: Param0) -> ::windows::core::Result<()> { Self::IContentPrefetcher(|this| unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }) } #[cfg(feature = "Foundation")] pub fn IndirectContentUri() -> ::windows::core::Result<super::super::Foundation::Uri> { Self::IContentPrefetcher(|this| 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::Foundation::Uri>(result__) }) } #[cfg(feature = "Foundation")] pub fn LastSuccessfulPrefetchTime() -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Foundation::DateTime>> { Self::IContentPrefetcherTime(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Foundation::DateTime>>(result__) }) } pub fn IContentPrefetcher<R, F: FnOnce(&IContentPrefetcher) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ContentPrefetcher, IContentPrefetcher> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } pub fn IContentPrefetcherTime<R, F: FnOnce(&IContentPrefetcherTime) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<ContentPrefetcher, IContentPrefetcherTime> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } impl ::windows::core::RuntimeName for ContentPrefetcher { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.ContentPrefetcher"; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct DownloadOperation(pub ::windows::core::IInspectable); impl DownloadOperation { #[cfg(feature = "Storage")] pub fn ResultFile(&self) -> ::windows::core::Result<super::super::Storage::IStorageFile> { 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::Storage::IStorageFile>(result__) } } pub fn Progress(&self) -> ::windows::core::Result<BackgroundDownloadProgress> { let this = self; unsafe { let mut result__: BackgroundDownloadProgress = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundDownloadProgress>(result__) } } #[cfg(feature = "Foundation")] pub fn StartAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<DownloadOperation, DownloadOperation>> { 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::Foundation::IAsyncOperationWithProgress<DownloadOperation, DownloadOperation>>(result__) } } #[cfg(feature = "Foundation")] pub fn AttachAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<DownloadOperation, DownloadOperation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<DownloadOperation, DownloadOperation>>(result__) } } pub fn Pause(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this)).ok() } } pub fn Resume(&self) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this)).ok() } } pub fn Guid(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestedUri(&self) -> ::windows::core::Result<super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(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::Foundation::Uri>(result__) } } pub fn Method(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(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__) } } #[cfg(feature = "deprecated")] pub fn Group(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn CostPolicy(&self) -> ::windows::core::Result<BackgroundTransferCostPolicy> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { let mut result__: BackgroundTransferCostPolicy = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferCostPolicy>(result__) } } pub fn SetCostPolicy(&self, value: BackgroundTransferCostPolicy) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Storage_Streams")] pub fn GetResultStreamAt(&self, position: u64) -> ::windows::core::Result<super::super::Storage::Streams::IInputStream> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), position, &mut result__).from_abi::<super::super::Storage::Streams::IInputStream>(result__) } } pub fn GetResponseInformation(&self) -> ::windows::core::Result<ResponseInformation> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(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::<ResponseInformation>(result__) } } pub fn Priority(&self) -> ::windows::core::Result<BackgroundTransferPriority> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperationPriority>(self)?; unsafe { let mut result__: BackgroundTransferPriority = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferPriority>(result__) } } pub fn SetPriority(&self, value: BackgroundTransferPriority) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperationPriority>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn TransferGroup(&self) -> ::windows::core::Result<BackgroundTransferGroup> { let this = &::windows::core::Interface::cast::<IDownloadOperation2>(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::<BackgroundTransferGroup>(result__) } } pub fn IsRandomAccessRequired(&self) -> ::windows::core::Result<bool> { let this = &::windows::core::Interface::cast::<IDownloadOperation3>(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 SetIsRandomAccessRequired(&self, value: bool) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IDownloadOperation3>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Storage_Streams")] pub fn GetResultRandomAccessStreamReference(&self) -> ::windows::core::Result<super::super::Storage::Streams::IRandomAccessStreamReference> { let this = &::windows::core::Interface::cast::<IDownloadOperation3>(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::Storage::Streams::IRandomAccessStreamReference>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn GetDownloadedRanges(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<BackgroundTransferFileRange>> { let this = &::windows::core::Interface::cast::<IDownloadOperation3>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<BackgroundTransferFileRange>>(result__) } } #[cfg(feature = "Foundation")] pub fn RangesDownloaded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::TypedEventHandler<DownloadOperation, BackgroundTransferRangesDownloadedEventArgs>>>(&self, eventhandler: Param0) -> ::windows::core::Result<super::super::Foundation::EventRegistrationToken> { let this = &::windows::core::Interface::cast::<IDownloadOperation3>(self)?; unsafe { let mut result__: super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), eventhandler.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveRangesDownloaded<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::EventRegistrationToken>>(&self, eventcookie: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IDownloadOperation3>(self)?; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), eventcookie.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn SetRequestedUri<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Uri>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IDownloadOperation3>(self)?; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(all(feature = "Foundation_Collections", feature = "Web"))] pub fn RecoverableWebErrorStatuses(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<super::super::Web::WebErrorStatus>> { let this = &::windows::core::Interface::cast::<IDownloadOperation3>(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::super::Foundation::Collections::IVector<super::super::Web::WebErrorStatus>>(result__) } } #[cfg(all(feature = "Foundation", feature = "Web"))] pub fn CurrentWebErrorStatus(&self) -> ::windows::core::Result<super::super::Foundation::IReference<super::super::Web::WebErrorStatus>> { let this = &::windows::core::Interface::cast::<IDownloadOperation3>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IReference<super::super::Web::WebErrorStatus>>(result__) } } pub fn MakeCurrentInTransferGroup(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IDownloadOperation4>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } pub fn SetRequestHeader<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, headername: Param0, headervalue: Param1) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IDownloadOperation5>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), headername.into_param().abi(), headervalue.into_param().abi()).ok() } } pub fn RemoveRequestHeader<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, headername: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IDownloadOperation5>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), headername.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for DownloadOperation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.DownloadOperation;{bd87ebb0-5714-4e09-ba68-bef73903b0d7})"); } unsafe impl ::windows::core::Interface for DownloadOperation { type Vtable = IDownloadOperation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbd87ebb0_5714_4e09_ba68_bef73903b0d7); } impl ::windows::core::RuntimeName for DownloadOperation { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.DownloadOperation"; } impl ::core::convert::From<DownloadOperation> for ::windows::core::IUnknown { fn from(value: DownloadOperation) -> Self { value.0 .0 } } impl ::core::convert::From<&DownloadOperation> for ::windows::core::IUnknown { fn from(value: &DownloadOperation) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for DownloadOperation { 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 DownloadOperation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<DownloadOperation> for ::windows::core::IInspectable { fn from(value: DownloadOperation) -> Self { value.0 } } impl ::core::convert::From<&DownloadOperation> for ::windows::core::IInspectable { fn from(value: &DownloadOperation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for DownloadOperation { 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 DownloadOperation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<DownloadOperation> for IBackgroundTransferOperation { type Error = ::windows::core::Error; fn try_from(value: DownloadOperation) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&DownloadOperation> for IBackgroundTransferOperation { type Error = ::windows::core::Error; fn try_from(value: &DownloadOperation) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferOperation> for DownloadOperation { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferOperation> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferOperation> for &DownloadOperation { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferOperation> { ::core::convert::TryInto::<IBackgroundTransferOperation>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<DownloadOperation> for IBackgroundTransferOperationPriority { type Error = ::windows::core::Error; fn try_from(value: DownloadOperation) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&DownloadOperation> for IBackgroundTransferOperationPriority { type Error = ::windows::core::Error; fn try_from(value: &DownloadOperation) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferOperationPriority> for DownloadOperation { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferOperationPriority> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferOperationPriority> for &DownloadOperation { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferOperationPriority> { ::core::convert::TryInto::<IBackgroundTransferOperationPriority>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for DownloadOperation {} unsafe impl ::core::marker::Sync for DownloadOperation {} #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundDownloader(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundDownloader { type Vtable = IBackgroundDownloader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc1c79333_6649_4b1d_a826_a4b3dd234d0b); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundDownloader_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, resultfile: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage")))] usize, #[cfg(all(feature = "Foundation", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, resultfile: ::windows::core::RawPtr, requestbodyfile: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage")))] usize, #[cfg(all(feature = "Foundation", feature = "Storage", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, resultfile: ::windows::core::RawPtr, requestbodystream: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage", feature = "Storage_Streams")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundDownloader2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundDownloader2 { type Vtable = IBackgroundDownloader2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa94a5847_348d_4a35_890e_8a1ef3798479); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundDownloader2_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 = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundDownloader3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundDownloader3 { type Vtable = IBackgroundDownloader3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd11a8c48_86e8_48e2_b615_6976aabf861d); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundDownloader3_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundDownloaderFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundDownloaderFactory { type Vtable = IBackgroundDownloaderFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x26836c24_d89e_46f4_a29a_4f4d4f144155); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundDownloaderFactory_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, completiongroup: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundDownloaderStaticMethods(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundDownloaderStaticMethods { type Vtable = IBackgroundDownloaderStaticMethods_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x52a65a35_c64e_426c_9919_540d0d21a650); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundDownloaderStaticMethods_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, group: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundDownloaderStaticMethods2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundDownloaderStaticMethods2 { type Vtable = IBackgroundDownloaderStaticMethods2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2faa1327_1ad4_4ca5_b2cd_08dbf0746afe); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundDownloaderStaticMethods2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, group: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundDownloaderUserConsent(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundDownloaderUserConsent { type Vtable = IBackgroundDownloaderUserConsent_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5d14e906_9266_4808_bd71_5925f2a3130a); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundDownloaderUserConsent_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, operations: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IBackgroundTransferBase(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferBase { type Vtable = IBackgroundTransferBase_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2a9da250_c769_458c_afe8_feb8d4d3b2ef); } impl IBackgroundTransferBase { pub fn SetRequestHeader<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, headername: Param0, headervalue: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), headername.into_param().abi(), headervalue.into_param().abi()).ok() } } #[cfg(feature = "Security_Credentials")] pub fn ServerCredential(&self) -> ::windows::core::Result<super::super::Security::Credentials::PasswordCredential> { 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::<super::super::Security::Credentials::PasswordCredential>(result__) } } #[cfg(feature = "Security_Credentials")] pub fn SetServerCredential<'a, Param0: ::windows::core::IntoParam<'a, super::super::Security::Credentials::PasswordCredential>>(&self, credential: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), credential.into_param().abi()).ok() } } #[cfg(feature = "Security_Credentials")] pub fn ProxyCredential(&self) -> ::windows::core::Result<super::super::Security::Credentials::PasswordCredential> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Security::Credentials::PasswordCredential>(result__) } } #[cfg(feature = "Security_Credentials")] pub fn SetProxyCredential<'a, Param0: ::windows::core::IntoParam<'a, super::super::Security::Credentials::PasswordCredential>>(&self, credential: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), credential.into_param().abi()).ok() } } pub fn Method(&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).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn SetMethod<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() } } #[cfg(feature = "deprecated")] pub fn Group(&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).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "deprecated")] pub fn SetGroup<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&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 CostPolicy(&self) -> ::windows::core::Result<BackgroundTransferCostPolicy> { let this = self; unsafe { let mut result__: BackgroundTransferCostPolicy = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferCostPolicy>(result__) } } pub fn SetCostPolicy(&self, value: BackgroundTransferCostPolicy) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for IBackgroundTransferBase { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{2a9da250-c769-458c-afe8-feb8d4d3b2ef}"); } impl ::core::convert::From<IBackgroundTransferBase> for ::windows::core::IUnknown { fn from(value: IBackgroundTransferBase) -> Self { value.0 .0 } } impl ::core::convert::From<&IBackgroundTransferBase> for ::windows::core::IUnknown { fn from(value: &IBackgroundTransferBase) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IBackgroundTransferBase { 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 IBackgroundTransferBase { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IBackgroundTransferBase> for ::windows::core::IInspectable { fn from(value: IBackgroundTransferBase) -> Self { value.0 } } impl ::core::convert::From<&IBackgroundTransferBase> for ::windows::core::IInspectable { fn from(value: &IBackgroundTransferBase) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IBackgroundTransferBase { 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 IBackgroundTransferBase { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferBase_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, headername: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, headervalue: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Security_Credentials")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Security_Credentials"))] usize, #[cfg(feature = "Security_Credentials")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, credential: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Security_Credentials"))] usize, #[cfg(feature = "Security_Credentials")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Security_Credentials"))] usize, #[cfg(feature = "Security_Credentials")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, credential: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Security_Credentials"))] 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, 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, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BackgroundTransferCostPolicy) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: BackgroundTransferCostPolicy) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundTransferCompletionGroup(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferCompletionGroup { type Vtable = IBackgroundTransferCompletionGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2d930225_986b_574d_7950_0add47f5d706); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferCompletionGroup_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 = "ApplicationModel_Background")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "ApplicationModel_Background"))] 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) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundTransferCompletionGroupTriggerDetails(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferCompletionGroupTriggerDetails { type Vtable = IBackgroundTransferCompletionGroupTriggerDetails_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7b6be286_6e47_5136_7fcb_fa4389f46f5b); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferCompletionGroupTriggerDetails_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_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundTransferContentPart(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferContentPart { type Vtable = IBackgroundTransferContentPart_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe8e15657_d7d1_4ed8_838e_674ac217ace6); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferContentPart_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, headername: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, headervalue: ::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 = "Storage")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage"))] usize, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IBackgroundTransferContentPartFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferContentPartFactory { type Vtable = IBackgroundTransferContentPartFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x90ef98a9_7a01_4a0b_9f80_a0b0bb370f8d); } impl IBackgroundTransferContentPartFactory { pub fn CreateWithName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, name: Param0) -> ::windows::core::Result<BackgroundTransferContentPart> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), name.into_param().abi(), &mut result__).from_abi::<BackgroundTransferContentPart>(result__) } } pub fn CreateWithNameAndFileName<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, name: Param0, filename: Param1) -> ::windows::core::Result<BackgroundTransferContentPart> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), name.into_param().abi(), filename.into_param().abi(), &mut result__).from_abi::<BackgroundTransferContentPart>(result__) } } } unsafe impl ::windows::core::RuntimeType for IBackgroundTransferContentPartFactory { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{90ef98a9-7a01-4a0b-9f80-a0b0bb370f8d}"); } impl ::core::convert::From<IBackgroundTransferContentPartFactory> for ::windows::core::IUnknown { fn from(value: IBackgroundTransferContentPartFactory) -> Self { value.0 .0 } } impl ::core::convert::From<&IBackgroundTransferContentPartFactory> for ::windows::core::IUnknown { fn from(value: &IBackgroundTransferContentPartFactory) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IBackgroundTransferContentPartFactory { 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 IBackgroundTransferContentPartFactory { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IBackgroundTransferContentPartFactory> for ::windows::core::IInspectable { fn from(value: IBackgroundTransferContentPartFactory) -> Self { value.0 } } impl ::core::convert::From<&IBackgroundTransferContentPartFactory> for ::windows::core::IInspectable { fn from(value: &IBackgroundTransferContentPartFactory) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IBackgroundTransferContentPartFactory { 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 IBackgroundTransferContentPartFactory { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferContentPartFactory_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, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, filename: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundTransferErrorStaticMethods(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferErrorStaticMethods { type Vtable = IBackgroundTransferErrorStaticMethods_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xaad33b04_1192_4bf4_8b68_39c5add244e2); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferErrorStaticMethods_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 = "Web")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, hresult: i32, result__: *mut super::super::Web::WebErrorStatus) -> ::windows::core::HRESULT, #[cfg(not(feature = "Web"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundTransferGroup(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferGroup { type Vtable = IBackgroundTransferGroup_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd8c3e3e4_6459_4540_85eb_aaa1c8903677); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferGroup_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BackgroundTransferBehavior) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: BackgroundTransferBehavior) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundTransferGroupStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferGroupStatics { type Vtable = IBackgroundTransferGroupStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x02ec50b2_7d18_495b_aa22_32a97d45d3e2); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferGroupStatics_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, name: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IBackgroundTransferOperation(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferOperation { type Vtable = IBackgroundTransferOperation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xded06846_90ca_44fb_8fb1_124154c0d539); } impl IBackgroundTransferOperation { pub fn Guid(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = self; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestedUri(&self) -> ::windows::core::Result<super::super::Foundation::Uri> { 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::<super::super::Foundation::Uri>(result__) } } pub fn Method(&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__) } } #[cfg(feature = "deprecated")] pub fn Group(&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).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn CostPolicy(&self) -> ::windows::core::Result<BackgroundTransferCostPolicy> { let this = self; unsafe { let mut result__: BackgroundTransferCostPolicy = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferCostPolicy>(result__) } } pub fn SetCostPolicy(&self, value: BackgroundTransferCostPolicy) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Storage_Streams")] pub fn GetResultStreamAt(&self, position: u64) -> ::windows::core::Result<super::super::Storage::Streams::IInputStream> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), position, &mut result__).from_abi::<super::super::Storage::Streams::IInputStream>(result__) } } pub fn GetResponseInformation(&self) -> ::windows::core::Result<ResponseInformation> { 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::<ResponseInformation>(result__) } } } unsafe impl ::windows::core::RuntimeType for IBackgroundTransferOperation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{ded06846-90ca-44fb-8fb1-124154c0d539}"); } impl ::core::convert::From<IBackgroundTransferOperation> for ::windows::core::IUnknown { fn from(value: IBackgroundTransferOperation) -> Self { value.0 .0 } } impl ::core::convert::From<&IBackgroundTransferOperation> for ::windows::core::IUnknown { fn from(value: &IBackgroundTransferOperation) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IBackgroundTransferOperation { 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 IBackgroundTransferOperation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IBackgroundTransferOperation> for ::windows::core::IInspectable { fn from(value: IBackgroundTransferOperation) -> Self { value.0 } } impl ::core::convert::From<&IBackgroundTransferOperation> for ::windows::core::IInspectable { fn from(value: &IBackgroundTransferOperation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IBackgroundTransferOperation { 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 IBackgroundTransferOperation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferOperation_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::GUID) -> ::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 ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BackgroundTransferCostPolicy) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: BackgroundTransferCostPolicy) -> ::windows::core::HRESULT, #[cfg(feature = "Storage_Streams")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, position: u64, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage_Streams"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IBackgroundTransferOperationPriority(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferOperationPriority { type Vtable = IBackgroundTransferOperationPriority_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x04854327_5254_4b3a_915e_0aa49275c0f9); } impl IBackgroundTransferOperationPriority { pub fn Priority(&self) -> ::windows::core::Result<BackgroundTransferPriority> { let this = self; unsafe { let mut result__: BackgroundTransferPriority = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferPriority>(result__) } } pub fn SetPriority(&self, value: BackgroundTransferPriority) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } } unsafe impl ::windows::core::RuntimeType for IBackgroundTransferOperationPriority { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{04854327-5254-4b3a-915e-0aa49275c0f9}"); } impl ::core::convert::From<IBackgroundTransferOperationPriority> for ::windows::core::IUnknown { fn from(value: IBackgroundTransferOperationPriority) -> Self { value.0 .0 } } impl ::core::convert::From<&IBackgroundTransferOperationPriority> for ::windows::core::IUnknown { fn from(value: &IBackgroundTransferOperationPriority) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IBackgroundTransferOperationPriority { 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 IBackgroundTransferOperationPriority { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IBackgroundTransferOperationPriority> for ::windows::core::IInspectable { fn from(value: IBackgroundTransferOperationPriority) -> Self { value.0 } } impl ::core::convert::From<&IBackgroundTransferOperationPriority> for ::windows::core::IInspectable { fn from(value: &IBackgroundTransferOperationPriority) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IBackgroundTransferOperationPriority { 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 IBackgroundTransferOperationPriority { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferOperationPriority_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 BackgroundTransferPriority) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: BackgroundTransferPriority) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundTransferRangesDownloadedEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundTransferRangesDownloadedEventArgs { type Vtable = IBackgroundTransferRangesDownloadedEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3ebc7453_bf48_4a88_9248_b0c165184f5c); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundTransferRangesDownloadedEventArgs_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, #[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")] 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 IBackgroundUploader(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundUploader { type Vtable = IBackgroundUploader_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc595c9ae_cead_465b_8801_c55ac90a01ce); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundUploader_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, sourcefile: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage")))] usize, #[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, sourcestream: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, parts: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, parts: ::windows::core::RawPtr, subtype: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uri: ::windows::core::RawPtr, parts: ::windows::core::RawPtr, subtype: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, boundary: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundUploader2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundUploader2 { type Vtable = IBackgroundUploader2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x8e0612ce_0c34_4463_807f_198a1b8bd4ad); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundUploader2_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 = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, #[cfg(feature = "UI_Notifications")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Notifications"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundUploader3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundUploader3 { type Vtable = IBackgroundUploader3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb95e9439_5bf0_4b3a_8c47_2c6199a854b9); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundUploader3_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundUploaderFactory(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundUploaderFactory { type Vtable = IBackgroundUploaderFactory_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x736203c7_10e7_48a0_ac3c_1ac71095ec57); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundUploaderFactory_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, completiongroup: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundUploaderStaticMethods(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundUploaderStaticMethods { type Vtable = IBackgroundUploaderStaticMethods_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf2875cfb_9b05_4741_9121_740a83e247df); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundUploaderStaticMethods_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, group: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundUploaderStaticMethods2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundUploaderStaticMethods2 { type Vtable = IBackgroundUploaderStaticMethods2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe919ac62_ea08_42f0_a2ac_07e467549080); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundUploaderStaticMethods2_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, group: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IBackgroundUploaderUserConsent(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IBackgroundUploaderUserConsent { type Vtable = IBackgroundUploaderUserConsent_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3bb384cb_0760_461d_907f_5138f84d44c1); } #[repr(C)] #[doc(hidden)] pub struct IBackgroundUploaderUserConsent_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, operations: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IContentPrefetcher(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IContentPrefetcher { type Vtable = IContentPrefetcher_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa8d6f754_7dc1_4cd9_8810_2a6aa9417e11); } #[repr(C)] #[doc(hidden)] pub struct IContentPrefetcher_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, #[cfg(all(feature = "Foundation", feature = "Foundation_Collections"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Foundation_Collections")))] 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, #[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 IContentPrefetcherTime(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IContentPrefetcherTime { type Vtable = IContentPrefetcherTime_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe361fd08_132a_4fde_a7cc_fcb0e66523af); } #[repr(C)] #[doc(hidden)] pub struct IContentPrefetcherTime_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 IDownloadOperation(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDownloadOperation { type Vtable = IDownloadOperation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xbd87ebb0_5714_4e09_ba68_bef73903b0d7); } #[repr(C)] #[doc(hidden)] pub struct IDownloadOperation_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")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BackgroundDownloadProgress) -> ::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, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "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)] #[doc(hidden)] pub struct IDownloadOperation2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDownloadOperation2 { type Vtable = IDownloadOperation2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa3cced40_8f9c_4353_9cd4_290dee387c38); } #[repr(C)] #[doc(hidden)] pub struct IDownloadOperation2_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IDownloadOperation3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDownloadOperation3 { type Vtable = IDownloadOperation3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5027351c_7d5e_4adc_b8d3_df5c6031b9cc); } #[repr(C)] #[doc(hidden)] pub struct IDownloadOperation3_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, #[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 = "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")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eventhandler: ::windows::core::RawPtr, result__: *mut super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, eventcookie: super::super::Foundation::EventRegistrationToken) -> ::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, #[cfg(all(feature = "Foundation_Collections", feature = "Web"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation_Collections", feature = "Web")))] usize, #[cfg(all(feature = "Foundation", feature = "Web"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(all(feature = "Foundation", feature = "Web")))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IDownloadOperation4(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDownloadOperation4 { type Vtable = IDownloadOperation4_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0cdaaef4_8cef_404a_966d_f058400bed80); } #[repr(C)] #[doc(hidden)] pub struct IDownloadOperation4_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) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IDownloadOperation5(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IDownloadOperation5 { type Vtable = IDownloadOperation5_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa699a86f_5590_463a_b8d6_1e491a2760a5); } #[repr(C)] #[doc(hidden)] pub struct IDownloadOperation5_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, headername: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, headervalue: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, headername: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IResponseInformation(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IResponseInformation { type Vtable = IResponseInformation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf8bb9a12_f713_4792_8b68_d9d297f91d2e); } #[repr(C)] #[doc(hidden)] pub struct IResponseInformation_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, #[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 u32) -> ::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 IUnconstrainedTransferRequestResult(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IUnconstrainedTransferRequestResult { type Vtable = IUnconstrainedTransferRequestResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4c24b81f_d944_4112_a98e_6a69522b7ebb); } #[repr(C)] #[doc(hidden)] pub struct IUnconstrainedTransferRequestResult_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IUploadOperation(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IUploadOperation { type Vtable = IUploadOperation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3e5624e0_7389_434c_8b35_427fd36bbdae); } #[repr(C)] #[doc(hidden)] pub struct IUploadOperation_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")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Storage"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut BackgroundUploadProgress) -> ::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, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct IUploadOperation2(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IUploadOperation2 { type Vtable = IUploadOperation2_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x556189f2_2774_4df6_9fa5_209f2bfb12f7); } #[repr(C)] #[doc(hidden)] pub struct IUploadOperation2_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, ); #[repr(transparent)] #[doc(hidden)] pub struct IUploadOperation3(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IUploadOperation3 { type Vtable = IUploadOperation3_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x42c92ca3_de39_4546_bc62_3774b4294de3); } #[repr(C)] #[doc(hidden)] pub struct IUploadOperation3_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) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IUploadOperation4(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IUploadOperation4 { type Vtable = IUploadOperation4_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x50edef31_fac5_41ee_b030_dc77caee9faa); } #[repr(C)] #[doc(hidden)] pub struct IUploadOperation4_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, headername: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, headervalue: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, headername: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct ResponseInformation(pub ::windows::core::IInspectable); impl ResponseInformation { pub fn IsResumable(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } #[cfg(feature = "Foundation")] pub fn ActualUri(&self) -> ::windows::core::Result<super::super::Foundation::Uri> { 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::<super::super::Foundation::Uri>(result__) } } pub fn StatusCode(&self) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__) } } #[cfg(feature = "Foundation_Collections")] pub fn Headers(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, ::windows::core::HSTRING>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMapView<::windows::core::HSTRING, ::windows::core::HSTRING>>(result__) } } } unsafe impl ::windows::core::RuntimeType for ResponseInformation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.ResponseInformation;{f8bb9a12-f713-4792-8b68-d9d297f91d2e})"); } unsafe impl ::windows::core::Interface for ResponseInformation { type Vtable = IResponseInformation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf8bb9a12_f713_4792_8b68_d9d297f91d2e); } impl ::windows::core::RuntimeName for ResponseInformation { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.ResponseInformation"; } impl ::core::convert::From<ResponseInformation> for ::windows::core::IUnknown { fn from(value: ResponseInformation) -> Self { value.0 .0 } } impl ::core::convert::From<&ResponseInformation> for ::windows::core::IUnknown { fn from(value: &ResponseInformation) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ResponseInformation { 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 ResponseInformation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<ResponseInformation> for ::windows::core::IInspectable { fn from(value: ResponseInformation) -> Self { value.0 } } impl ::core::convert::From<&ResponseInformation> for ::windows::core::IInspectable { fn from(value: &ResponseInformation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ResponseInformation { 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 ResponseInformation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for ResponseInformation {} unsafe impl ::core::marker::Sync for ResponseInformation {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct UnconstrainedTransferRequestResult(pub ::windows::core::IInspectable); impl UnconstrainedTransferRequestResult { #[cfg(feature = "deprecated")] pub fn IsUnconstrained(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } } unsafe impl ::windows::core::RuntimeType for UnconstrainedTransferRequestResult { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.UnconstrainedTransferRequestResult;{4c24b81f-d944-4112-a98e-6a69522b7ebb})"); } unsafe impl ::windows::core::Interface for UnconstrainedTransferRequestResult { type Vtable = IUnconstrainedTransferRequestResult_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4c24b81f_d944_4112_a98e_6a69522b7ebb); } impl ::windows::core::RuntimeName for UnconstrainedTransferRequestResult { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.UnconstrainedTransferRequestResult"; } impl ::core::convert::From<UnconstrainedTransferRequestResult> for ::windows::core::IUnknown { fn from(value: UnconstrainedTransferRequestResult) -> Self { value.0 .0 } } impl ::core::convert::From<&UnconstrainedTransferRequestResult> for ::windows::core::IUnknown { fn from(value: &UnconstrainedTransferRequestResult) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for UnconstrainedTransferRequestResult { 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 UnconstrainedTransferRequestResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<UnconstrainedTransferRequestResult> for ::windows::core::IInspectable { fn from(value: UnconstrainedTransferRequestResult) -> Self { value.0 } } impl ::core::convert::From<&UnconstrainedTransferRequestResult> for ::windows::core::IInspectable { fn from(value: &UnconstrainedTransferRequestResult) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for UnconstrainedTransferRequestResult { 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 UnconstrainedTransferRequestResult { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for UnconstrainedTransferRequestResult {} unsafe impl ::core::marker::Sync for UnconstrainedTransferRequestResult {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct UploadOperation(pub ::windows::core::IInspectable); impl UploadOperation { #[cfg(feature = "Storage")] pub fn SourceFile(&self) -> ::windows::core::Result<super::super::Storage::IStorageFile> { 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::Storage::IStorageFile>(result__) } } pub fn Progress(&self) -> ::windows::core::Result<BackgroundUploadProgress> { let this = self; unsafe { let mut result__: BackgroundUploadProgress = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundUploadProgress>(result__) } } #[cfg(feature = "Foundation")] pub fn StartAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<UploadOperation, UploadOperation>> { 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::Foundation::IAsyncOperationWithProgress<UploadOperation, UploadOperation>>(result__) } } #[cfg(feature = "Foundation")] pub fn AttachAsync(&self) -> ::windows::core::Result<super::super::Foundation::IAsyncOperationWithProgress<UploadOperation, UploadOperation>> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::IAsyncOperationWithProgress<UploadOperation, UploadOperation>>(result__) } } pub fn Guid(&self) -> ::windows::core::Result<::windows::core::GUID> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { let mut result__: ::windows::core::GUID = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::GUID>(result__) } } #[cfg(feature = "Foundation")] pub fn RequestedUri(&self) -> ::windows::core::Result<super::super::Foundation::Uri> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(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::Foundation::Uri>(result__) } } pub fn Method(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(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__) } } #[cfg(feature = "deprecated")] pub fn Group(&self) -> ::windows::core::Result<::windows::core::HSTRING> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } pub fn CostPolicy(&self) -> ::windows::core::Result<BackgroundTransferCostPolicy> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { let mut result__: BackgroundTransferCostPolicy = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferCostPolicy>(result__) } } pub fn SetCostPolicy(&self, value: BackgroundTransferCostPolicy) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Storage_Streams")] pub fn GetResultStreamAt(&self, position: u64) -> ::windows::core::Result<super::super::Storage::Streams::IInputStream> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(self)?; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), position, &mut result__).from_abi::<super::super::Storage::Streams::IInputStream>(result__) } } pub fn GetResponseInformation(&self) -> ::windows::core::Result<ResponseInformation> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperation>(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::<ResponseInformation>(result__) } } pub fn Priority(&self) -> ::windows::core::Result<BackgroundTransferPriority> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperationPriority>(self)?; unsafe { let mut result__: BackgroundTransferPriority = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<BackgroundTransferPriority>(result__) } } pub fn SetPriority(&self, value: BackgroundTransferPriority) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IBackgroundTransferOperationPriority>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } pub fn TransferGroup(&self) -> ::windows::core::Result<BackgroundTransferGroup> { let this = &::windows::core::Interface::cast::<IUploadOperation2>(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::<BackgroundTransferGroup>(result__) } } pub fn MakeCurrentInTransferGroup(&self) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IUploadOperation3>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this)).ok() } } pub fn SetRequestHeader<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, headername: Param0, headervalue: Param1) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IUploadOperation4>(self)?; unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), headername.into_param().abi(), headervalue.into_param().abi()).ok() } } pub fn RemoveRequestHeader<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, headername: Param0) -> ::windows::core::Result<()> { let this = &::windows::core::Interface::cast::<IUploadOperation4>(self)?; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), headername.into_param().abi()).ok() } } } unsafe impl ::windows::core::RuntimeType for UploadOperation { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Networking.BackgroundTransfer.UploadOperation;{3e5624e0-7389-434c-8b35-427fd36bbdae})"); } unsafe impl ::windows::core::Interface for UploadOperation { type Vtable = IUploadOperation_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3e5624e0_7389_434c_8b35_427fd36bbdae); } impl ::windows::core::RuntimeName for UploadOperation { const NAME: &'static str = "Windows.Networking.BackgroundTransfer.UploadOperation"; } impl ::core::convert::From<UploadOperation> for ::windows::core::IUnknown { fn from(value: UploadOperation) -> Self { value.0 .0 } } impl ::core::convert::From<&UploadOperation> for ::windows::core::IUnknown { fn from(value: &UploadOperation) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for UploadOperation { 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 UploadOperation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<UploadOperation> for ::windows::core::IInspectable { fn from(value: UploadOperation) -> Self { value.0 } } impl ::core::convert::From<&UploadOperation> for ::windows::core::IInspectable { fn from(value: &UploadOperation) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for UploadOperation { 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 UploadOperation { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } impl ::core::convert::TryFrom<UploadOperation> for IBackgroundTransferOperation { type Error = ::windows::core::Error; fn try_from(value: UploadOperation) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&UploadOperation> for IBackgroundTransferOperation { type Error = ::windows::core::Error; fn try_from(value: &UploadOperation) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferOperation> for UploadOperation { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferOperation> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferOperation> for &UploadOperation { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferOperation> { ::core::convert::TryInto::<IBackgroundTransferOperation>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } impl ::core::convert::TryFrom<UploadOperation> for IBackgroundTransferOperationPriority { type Error = ::windows::core::Error; fn try_from(value: UploadOperation) -> ::windows::core::Result<Self> { ::core::convert::TryFrom::try_from(&value) } } impl ::core::convert::TryFrom<&UploadOperation> for IBackgroundTransferOperationPriority { type Error = ::windows::core::Error; fn try_from(value: &UploadOperation) -> ::windows::core::Result<Self> { ::windows::core::Interface::cast(value) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferOperationPriority> for UploadOperation { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferOperationPriority> { ::windows::core::IntoParam::into_param(&self) } } impl<'a> ::windows::core::IntoParam<'a, IBackgroundTransferOperationPriority> for &UploadOperation { fn into_param(self) -> ::windows::core::Param<'a, IBackgroundTransferOperationPriority> { ::core::convert::TryInto::<IBackgroundTransferOperationPriority>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None) } } unsafe impl ::core::marker::Send for UploadOperation {} unsafe impl ::core::marker::Sync for UploadOperation {}
mod de; mod ser; mod shared; include!("../include/pub_from_to.rs");
pub const HEADER_SIZE: u32 = 0x70; pub const STRING_ID_ITEM_SIZE: u32 = 0x04; pub const TYPE_ID_ITEM_SIZE: u32 = 0x04; pub const PROTO_ID_ITEM_SIZE: u32 = 0x0c; pub const FIELD_ID_ITEM_SIZE: u32 = 0x08; pub const METHOD_ID_ITEM_SIZE: u32 = 0x08; pub const CLASS_DEF_ITEM_SIZE: u32 = 0x20; // pub const MAP_ITEM_SIZE: u32 = 12; // pub const TYPE_ITEM_SIZE: u32 = 2; // pub const ANNOTATION_SET_REF_SIZE: u32 = 4; // pub const ANNOTATION_SET_ITEM_SIZE: u32 = 4;
pub mod thompson;
//! Events. /// An event emitted from the contract. #[derive(Clone, Debug, cbor::Encode, cbor::Decode)] pub struct Event { /// Optional module name. #[cbor(optional, default, skip_serializing_if = "String::is_empty")] pub module: String, /// Unique code representing the event for the given module. pub code: u32, /// Arbitrary data associated with the event. #[cbor(optional, default, skip_serializing_if = "Vec::is_empty")] pub data: Vec<u8>, }
use super::Command; use clap::ArgMatches; use log::{error, info}; use std::{io, process}; pub fn run(matches: &ArgMatches, commands: &mut Vec<Command>) { info!("Running DELETE subcommand"); if matches.is_present("all") { println!("Are you sure you want to delete all entries? (y/n)"); let mut input = String::new(); io::stdin() .read_line(&mut input) .expect("Failed to read line"); input = input.trim().to_lowercase(); if input != "y" { println!("Aborting"); process::exit(0); } info!("Clearing all commands"); commands.clear(); } else { let id = matches .value_of("id") .unwrap() .parse::<usize>() .unwrap_or_else(|_| { error!("Not a valid ID"); process::exit(1) }); info!("Deleting ID: {}", id); commands.remove(id); for item in commands.iter_mut().skip(id) { item.id -= 1; } } }
use super::{browser_info, env, Config, Pinboard, Runner, SubCommand, Tag}; use crate::cli::Opt; use std::{thread, time}; use alfred::{Item, ItemBuilder, Modifier}; use alfred_rs::Data; impl<'api, 'pin> Runner<'api, 'pin> { // pub fn list(&self, cmd: SubCommand) { pub fn list(&self, opt: Opt) { let cmd = opt.cmd; let query_item = opt.query_as_item; match cmd { SubCommand::List { tags, suggest, no_existing_page, query, } => self.process(tags, suggest, no_existing_page, query_item, query), _ => unreachable!(), } } #[allow(clippy::too_many_lines)] fn process( &self, tags: bool, suggest: Option<bool>, no_existing_page: bool, query_item: bool, q: Option<String>, ) { debug!("Starting in list::process"); let config = self.config.as_ref().unwrap(); let pinboard = self.pinboard.as_ref().unwrap(); let private_pin = (!config.private_new_pin).to_string(); let toread_pin = config.toread_new_pin.to_string(); let option_subtitle = if config.private_new_pin { "Post the bookmark as PUBLIC." } else { "Post the bookmark as private." }; let control_subtitle = if config.toread_new_pin { "Mark the bookmark as NOT toread." } else { "Mark the bookmark as TOREAD." }; if tags { // Search the tags using the last 'word' in 'q' let queries = q.unwrap_or_default(); // Check if user has entered ';' which indicates they are providing a description. // So no need to search for tags! if queries.contains(';') { let trim_chars: &[_] = &['\t', ' ', '\\', '\n']; let pin_info = queries .splitn(2, ';') .map(|s| s.trim_matches(trim_chars)) .collect::<Vec<&str>>(); debug!(" pin_info: {:?}", pin_info); let mut item = ItemBuilder::new("Hit Return to bookmark the page!") .icon_path("upload.png") .arg(queries.as_str()) .variable("shared", private_pin) .variable("toread", toread_pin) .variable("tags", pin_info[0]) .subtitle_mod(Modifier::Option, option_subtitle) .subtitle_mod(Modifier::Control, control_subtitle); if !pin_info[1].is_empty() { item = item.variable("description", pin_info[1]); } let item = vec![item.into_item()]; if let Err(e) = self.write_output_items(item, Option::<Vec<(&str, &str)>>::None) { error!("list: Couldn't write to Alfred: {:?}", e); } return; } let query_words: Vec<&str> = queries.split_whitespace().collect(); let last_query_word_tag; let mut alfred_items = Vec::with_capacity(config.tags_to_show as usize + 1); // First try to get list of popular tags from Pinboard let tag_suggestion = suggest.unwrap_or(config.suggest_tags); let popular_tags = if tag_suggestion { // if suggest.unwrap_or(config.suggest_tags) { suggest_tags() } else { vec![] }; let last_query_word = query_words.last().unwrap_or(&""); let mut top_items: Vec<Tag> = Vec::with_capacity(2usize); match pinboard.search_list_of_tags(last_query_word) { Err(e) => crate::show_error_alfred(e.to_string()), Ok(results) => { let prev_tags = if query_words.len() > 1 { // User has already searched for other tags, we should include those in the // 'autocomplete' field of the AlfredItem queries.get(0..=queries.rfind(' ').unwrap()).unwrap() } else { "" }; // No result means, we couldn't find a tag using the given query // Some result mean we found tags even though the query was empty as // search_list_of_tags returns all tags for empty queries. last_query_word_tag = Tag::new((*last_query_word).to_string(), 0).set_new(); let mut filter_idx = None; #[allow(clippy::single_match_else)] let items = match results { Some(i) => { debug!("Found {} tags.", i.len()); top_items.insert(0, i[0].clone()); // If user input matches a tag, we will show it as first item if let Some(idx) = i.iter().position(|t| &t.0 == last_query_word) { if idx != 0 { top_items.insert(0, i[idx].clone()); filter_idx = Some(idx - 1); // Substract one since we will be // always skipping the firt tag // from results (i) debug!("Found exact tag: {:?}, {}", i[idx], idx); } } else { // Otherwise we will show the tag with highest frequency matching user // input before popular/suggested tags, unless --query-as-item is set // in which case we create an alfred item with what user has typed top_items.insert(0, last_query_word_tag); if query_item { filter_idx = None; } } i } None => { assert!(!query_words.is_empty()); debug!("Didn't find any tag for `{}`", last_query_word); filter_idx = None; top_items.insert(0, last_query_word_tag); vec![] } }; let prev_tags_len = prev_tags.len(); alfred_items = top_items // Start with top_items, and .iter() .enumerate() .chain(popular_tags.iter().enumerate()) // then add popular_tags // and finally add all tags returned from search, ensuring to remove // items that are in top_results .chain( items.into_iter().skip(1).enumerate().filter(|&(idx, _)| { filter_idx.is_none() || idx != filter_idx.unwrap() }), ) // Remove all tags that are already present in user query list .filter(|&(_, tag)| { if query_words.is_empty() { true } else { let upper = query_words.len() - 1; !query_words.as_slice()[0..upper] .iter() .any(|q| q == &tag.0.as_str()) } }) .take(config.tags_to_show as usize) .map(|(_, tag)| { let mut item_args = String::with_capacity(prev_tags_len + tag.0.len()); item_args.push_str(prev_tags); item_args.push_str(&tag.0); ItemBuilder::new(tag.0.as_str()) .subtitle(tag.1.to_string()) .autocomplete(item_args.clone()) .subtitle_mod(Modifier::Option, option_subtitle) .subtitle_mod(Modifier::Control, control_subtitle) .variable("tags", item_args.clone()) .variable("shared", &private_pin) .variable("toread", &toread_pin) .arg(item_args) .valid(true) .icon_path("tag.png") .into_item() }) .collect::<Vec<Item>>(); } } debug!("alfred_items hast {} entities", alfred_items.len()); if !query_words.is_empty() && alfred_items.is_empty() { alfred_items = vec![ItemBuilder::new("Hit Return to bookmark the page!") .icon_path("upload.png") .arg(queries.as_str()) .subtitle("You may have entered duplicate tags!") .variable("shared", &private_pin) .variable("toread", &toread_pin) .variable("tags", queries.as_str()) .subtitle_mod(Modifier::Option, option_subtitle) .subtitle_mod(Modifier::Control, control_subtitle) .into_item()]; } if !no_existing_page && config.page_is_bookmarked && is_page_bookmarked(pinboard) { let bookmark_present = ItemBuilder::new("You already have the bookmark!") .icon_path("bookmark-delete.png") .into_item(); alfred_items.insert(0, bookmark_present); } if let Err(e) = self.write_output_items(alfred_items, Option::<Vec<(&str, &str)>>::None) { error!("list: Couldn't write to Alfred: {:?}", e); } } else { if q.is_some() && !q.unwrap().is_empty() { warn!( "Ignoring search query, will spit out {} of bookmarks.", config.pins_to_show ); } let items = pinboard .list_bookmarks() .unwrap_or_default() .into_iter() .take(config.pins_to_show as usize) .map(|pin| { ItemBuilder::new(pin.title.as_ref()) .subtitle(pin.url.as_ref()) .arg(pin.url.as_ref()) .into_item() }) .collect::<Vec<Item>>(); if let Err(e) = self.write_output_items(items, Option::<Vec<(&str, &str)>>::None) { error!("list: Couldn't write to Alfred: {:?}", e); } } } } fn is_page_bookmarked(pinboard: &Pinboard) -> bool { let found; let exec_counter = env::var("apr_execution_counter") .unwrap_or_else(|_| "1".to_string()) .parse::<usize>() .unwrap_or(1); debug!("exec_counter: {}", exec_counter); if exec_counter == 1 { let tab_info = browser_info::get(); found = match tab_info { Ok(tab_info) => { debug!("tab_info: {:?}", tab_info); pinboard .find_url(&tab_info.url) .map(|op| { if let Some(vp) = op { assert!(!vp.is_empty()); !vp.is_empty() } else { false } }) .unwrap_or(false) } Err(_) => false, }; let _r = Data::save_to_file("bookmark_exists.json", &found); debug!("bookmark found from browser info: {}", found); } else { found = Data::load_from_file("bookmark_exists.json").unwrap_or(false); debug!("bookmark found from cache info: {}", found); } found } fn suggest_tags() -> Vec<Tag> { use std::sync::mpsc; let mut popular_tags = vec![]; let exec_counter = env::var("apr_execution_counter") .unwrap_or_else(|_| "1".to_string()) .parse::<usize>() .unwrap_or(1); let (tx, rx) = mpsc::channel(); let thread_handle = thread::spawn(move || { warn!("inside spawn thread, about to call get_suggested_tags"); let r = retrieve_popular_tags(exec_counter); if let Ok(pt) = r { let tx_result = tx.send(pt); match tx_result { Ok(_) => warn!("Sent the popular tags from child thread"), Err(e) => warn!("Failed to send popular tags: {:?}", e), } } else { warn!("get_suggested_tags: {:?}", r); } }); if exec_counter == 1 { thread::sleep(time::Duration::from_millis(1000)); } else { thread_handle.join().expect("Child thread terminated"); } if let Ok(pt) = rx.try_recv() { warn!("* received popular tags from child: {:?}", pt); popular_tags = pt; } else { warn!("child didn't produce usable result."); } popular_tags } /// Retrieves popular tags from a Web API call for first run and caches them for subsequent runs. fn retrieve_popular_tags(exec_counter: usize) -> Result<Vec<Tag>, Box<dyn std::error::Error>> { debug!("Starting in get_suggested_tags"); // TODO: Don't create another pinboard instance. use the one list.rs receives to be shared with // the thread that runs this function. // FIXME: If run from outside Alfred (say terminal), // the cache folder for 'config' and 'pinboard' will be different. let config = Config::setup()?; let pinboard = Pinboard::new(config.auth_token, alfred::env::workflow_cache())?; // let ptags_fn = config.cache_dir().join("popular.tags.cache"); let ptags_fn = "popular.tags.cache"; let tags; // let metadata = fs::metadata("foo.txt")?; // if let Ok(time) = metadata.created() { // println!("{:?}", time); // } else { // println!("Not supported on this platform"); // } if exec_counter == 1 { let tab_info = browser_info::get()?; warn!("tab_info.url: {:?}", tab_info.url); tags = match pinboard.popular_tags(&tab_info.url) { Err(e) => vec![format!("ERROR: fetching popular tags: {:?}", e)], Ok(tags) => tags, }; info!("popular tags: {:?}", tags); Data::save_to_file(ptags_fn, &tags)?; } else { warn!( "**** reading suggested tags from cache file: {:?}", ptags_fn ); tags = Data::load_from_file(ptags_fn) .ok_or_else(|| "bad popular tags cache file".to_string())?; } Ok(tags .into_iter() .map(|t| Tag::new(t, 0).set_popular()) .collect::<Vec<Tag>>()) }
use std::pin::Pin; use futures::{future, stream}; use juniper::graphql_subscription; type Stream<'a, I> = Pin<Box<dyn futures::Stream<Item = I> + Send + 'a>>; struct ObjA; #[graphql_subscription] impl ObjA { async fn wrong( &self, #[graphql(default = [true, false, false])] input: [bool; 2], ) -> Stream<'static, bool> { Box::pin(stream::once(future::ready(input[0]))) } } fn main() {}
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your // option. This file may not be copied, modified, or distributed // except according to those terms. // run-pass #![allow(unions_with_drop_fields)] // Some traits can be derived for unions. #![feature(untagged_unions)] #[derive( Copy, Clone, Eq, )] union U { a: u8, b: u16, } impl PartialEq for U { fn eq(&self, rhs: &Self) -> bool { true } } #[derive( Clone, Copy, Eq )] union W<T> { a: T, } impl<T> PartialEq for W<T> { fn eq(&self, rhs: &Self) -> bool { true } } fn main() { let u = U { b: 0 }; let u1 = u; let u2 = u.clone(); assert!(u1 == u2); let w = W { a: 0 }; let w1 = w.clone(); assert!(w == w1); }
use std::path::PathBuf; pub struct PackageUnify {} impl PackageUnify { pub fn from_path(path: PathBuf) -> String { let mut package = "".to_string(); let path_iter = path.iter(); path_iter.for_each(|str| { package = format!("{}.{}", package, str.to_str().expect("error path")); }); package.remove(0); package } pub fn from_rust_import(str: &str, remove_last: bool) -> String { let mut package = "".to_string(); let mut vec = str.split("::").collect::<Vec<&str>>(); if remove_last { vec.remove(vec.len() - 1); } vec.iter().for_each(|sub| { package = format!("{}.{}", package, sub); }); package.remove(0); package } } #[cfg(test)] mod tests { use std::path::PathBuf; use crate::support::package_unify::PackageUnify; #[test] fn should_convert_path_to_package() { let buf = PathBuf::from("../../../src").join("core").join("domain"); assert_eq!(".........src.core.domain".to_string(), PackageUnify::from_path(buf)); } #[test] fn should_convert_rust_import() { let imp = "std::path::PathBuf"; assert_eq!("std.path".to_string(), PackageUnify::from_rust_import(imp, true)); let imp = "std::path"; assert_eq!("std.path".to_string(), PackageUnify::from_rust_import(imp, false)); } }
#![deny(missing_docs)] //! Stringcheck provides functions to check if a given octet sequence matches a ABNF. //! //! The module does not aim to be complete, it should only implement the validators needed for //! parsing HTTP and maybe other protocols in the future. //! //! The Core Rules defined in [RFC5234](http://tools.ietf.org/html/rfc5234#appendix-B.1) are //! all implemented except for `CRLF` and `LWSP`. pub use core::*; pub use http::*; mod core; mod http; #[test] fn test_digit() { assert!(digit(&b'0')); assert!(b"42".iter().all(digit)); } #[test] fn test_token() { assert!(token(b"Content-Length")); assert!(!token(b"")); }
#![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 CoreAppWindowPreview(pub ::windows::core::IInspectable); impl CoreAppWindowPreview { #[cfg(feature = "UI_WindowManagement")] pub fn GetIdFromWindow<'a, Param0: ::windows::core::IntoParam<'a, super::super::WindowManagement::AppWindow>>(window: Param0) -> ::windows::core::Result<i32> { Self::ICoreAppWindowPreviewStatics(|this| unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), window.into_param().abi(), &mut result__).from_abi::<i32>(result__) }) } pub fn ICoreAppWindowPreviewStatics<R, F: FnOnce(&ICoreAppWindowPreviewStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<CoreAppWindowPreview, ICoreAppWindowPreviewStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for CoreAppWindowPreview { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Core.Preview.CoreAppWindowPreview;{a4f6e665-365e-5fde-87a5-9543c3a15aa8})"); } unsafe impl ::windows::core::Interface for CoreAppWindowPreview { type Vtable = ICoreAppWindowPreview_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa4f6e665_365e_5fde_87a5_9543c3a15aa8); } impl ::windows::core::RuntimeName for CoreAppWindowPreview { const NAME: &'static str = "Windows.UI.Core.Preview.CoreAppWindowPreview"; } impl ::core::convert::From<CoreAppWindowPreview> for ::windows::core::IUnknown { fn from(value: CoreAppWindowPreview) -> Self { value.0 .0 } } impl ::core::convert::From<&CoreAppWindowPreview> for ::windows::core::IUnknown { fn from(value: &CoreAppWindowPreview) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CoreAppWindowPreview { 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 CoreAppWindowPreview { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<CoreAppWindowPreview> for ::windows::core::IInspectable { fn from(value: CoreAppWindowPreview) -> Self { value.0 } } impl ::core::convert::From<&CoreAppWindowPreview> for ::windows::core::IInspectable { fn from(value: &CoreAppWindowPreview) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CoreAppWindowPreview { 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 CoreAppWindowPreview { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for CoreAppWindowPreview {} unsafe impl ::core::marker::Sync for CoreAppWindowPreview {} #[repr(transparent)] #[doc(hidden)] pub struct ICoreAppWindowPreview(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreAppWindowPreview { type Vtable = ICoreAppWindowPreview_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa4f6e665_365e_5fde_87a5_9543c3a15aa8); } #[repr(C)] #[doc(hidden)] pub struct ICoreAppWindowPreview_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, ); #[repr(transparent)] #[doc(hidden)] pub struct ICoreAppWindowPreviewStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ICoreAppWindowPreviewStatics { type Vtable = ICoreAppWindowPreviewStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x33ac21be_423b_5db6_8a8e_4dc87353b75b); } #[repr(C)] #[doc(hidden)] pub struct ICoreAppWindowPreviewStatics_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 = "UI_WindowManagement")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, window: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_WindowManagement"))] usize, ); #[repr(transparent)] #[doc(hidden)] pub struct ISystemNavigationCloseRequestedPreviewEventArgs(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISystemNavigationCloseRequestedPreviewEventArgs { type Vtable = ISystemNavigationCloseRequestedPreviewEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x83d00de1_cbe5_4f31_8414_361da046518f); } #[repr(C)] #[doc(hidden)] pub struct ISystemNavigationCloseRequestedPreviewEventArgs_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, #[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 ISystemNavigationManagerPreview(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISystemNavigationManagerPreview { type Vtable = ISystemNavigationManagerPreview_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xec5f0488_6425_4777_a536_cb5634427f0d); } #[repr(C)] #[doc(hidden)] pub struct ISystemNavigationManagerPreview_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, 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 ISystemNavigationManagerPreviewStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for ISystemNavigationManagerPreviewStatics { type Vtable = ISystemNavigationManagerPreviewStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0e971360_df74_4bce_84cb_bd1181ac0a71); } #[repr(C)] #[doc(hidden)] pub struct ISystemNavigationManagerPreviewStatics_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, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SystemNavigationCloseRequestedPreviewEventArgs(pub ::windows::core::IInspectable); impl SystemNavigationCloseRequestedPreviewEventArgs { pub fn Handled(&self) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__) } } pub fn SetHandled(&self, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() } } #[cfg(feature = "Foundation")] pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::super::Foundation::Deferral> { 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::Deferral>(result__) } } } unsafe impl ::windows::core::RuntimeType for SystemNavigationCloseRequestedPreviewEventArgs { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Core.Preview.SystemNavigationCloseRequestedPreviewEventArgs;{83d00de1-cbe5-4f31-8414-361da046518f})"); } unsafe impl ::windows::core::Interface for SystemNavigationCloseRequestedPreviewEventArgs { type Vtable = ISystemNavigationCloseRequestedPreviewEventArgs_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x83d00de1_cbe5_4f31_8414_361da046518f); } impl ::windows::core::RuntimeName for SystemNavigationCloseRequestedPreviewEventArgs { const NAME: &'static str = "Windows.UI.Core.Preview.SystemNavigationCloseRequestedPreviewEventArgs"; } impl ::core::convert::From<SystemNavigationCloseRequestedPreviewEventArgs> for ::windows::core::IUnknown { fn from(value: SystemNavigationCloseRequestedPreviewEventArgs) -> Self { value.0 .0 } } impl ::core::convert::From<&SystemNavigationCloseRequestedPreviewEventArgs> for ::windows::core::IUnknown { fn from(value: &SystemNavigationCloseRequestedPreviewEventArgs) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SystemNavigationCloseRequestedPreviewEventArgs { 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 SystemNavigationCloseRequestedPreviewEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SystemNavigationCloseRequestedPreviewEventArgs> for ::windows::core::IInspectable { fn from(value: SystemNavigationCloseRequestedPreviewEventArgs) -> Self { value.0 } } impl ::core::convert::From<&SystemNavigationCloseRequestedPreviewEventArgs> for ::windows::core::IInspectable { fn from(value: &SystemNavigationCloseRequestedPreviewEventArgs) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SystemNavigationCloseRequestedPreviewEventArgs { 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 SystemNavigationCloseRequestedPreviewEventArgs { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SystemNavigationCloseRequestedPreviewEventArgs {} unsafe impl ::core::marker::Sync for SystemNavigationCloseRequestedPreviewEventArgs {} #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct SystemNavigationManagerPreview(pub ::windows::core::IInspectable); impl SystemNavigationManagerPreview { #[cfg(feature = "Foundation")] pub fn CloseRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventHandler<SystemNavigationCloseRequestedPreviewEventArgs>>>(&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).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveCloseRequested<'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).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() } } pub fn GetForCurrentView() -> ::windows::core::Result<SystemNavigationManagerPreview> { Self::ISystemNavigationManagerPreviewStatics(|this| 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::<SystemNavigationManagerPreview>(result__) }) } pub fn ISystemNavigationManagerPreviewStatics<R, F: FnOnce(&ISystemNavigationManagerPreviewStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<SystemNavigationManagerPreview, ISystemNavigationManagerPreviewStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for SystemNavigationManagerPreview { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Core.Preview.SystemNavigationManagerPreview;{ec5f0488-6425-4777-a536-cb5634427f0d})"); } unsafe impl ::windows::core::Interface for SystemNavigationManagerPreview { type Vtable = ISystemNavigationManagerPreview_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xec5f0488_6425_4777_a536_cb5634427f0d); } impl ::windows::core::RuntimeName for SystemNavigationManagerPreview { const NAME: &'static str = "Windows.UI.Core.Preview.SystemNavigationManagerPreview"; } impl ::core::convert::From<SystemNavigationManagerPreview> for ::windows::core::IUnknown { fn from(value: SystemNavigationManagerPreview) -> Self { value.0 .0 } } impl ::core::convert::From<&SystemNavigationManagerPreview> for ::windows::core::IUnknown { fn from(value: &SystemNavigationManagerPreview) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SystemNavigationManagerPreview { 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 SystemNavigationManagerPreview { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<SystemNavigationManagerPreview> for ::windows::core::IInspectable { fn from(value: SystemNavigationManagerPreview) -> Self { value.0 } } impl ::core::convert::From<&SystemNavigationManagerPreview> for ::windows::core::IInspectable { fn from(value: &SystemNavigationManagerPreview) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SystemNavigationManagerPreview { 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 SystemNavigationManagerPreview { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for SystemNavigationManagerPreview {} unsafe impl ::core::marker::Sync for SystemNavigationManagerPreview {}
fn main() { let x = vec![1, 2, 3]; let y = &x; println!("{:?}", x); println!("{:?}", y); let mut x_mut = vec![1, 2, 3]; let y_mut = &mut x_mut; y_mut.push(4); println!("{:?}", y_mut); // println!("{:?}", x_mut); { let temp = vec![2, 3, 4]; let x = vec![1, 2, 3]; let mut y = &x; let mut z = &mut y; println!("{:?}", z); *z = &temp; println!("{:?}", z); } let mut x_scope = vec![1, 2, 3]; { let y_scope = &mut x_scope; y_scope.push(4); } x_scope.push(5); println!("{:?}", x_scope); // let nope = { // let x = vec![1]; // &x // }; }
const PARENS: [u8; 2] = [b'(', b')']; #[derive(Debug, Copy, Clone, PartialEq)] enum Token { Literal(i64), Op(u8), Paren(u8), } struct Parser<'a> { expr: &'a str } impl Parser<'_> { fn advance(&mut self) -> Token { let bytes = self.expr.as_bytes(); let mut start: usize = 0; while bytes[start] == b' ' { start += 1; } let mut end = start + 1; match bytes[start] { x @ b'(' | x @ b')' => { self.expr = &self.expr[end..]; return Token::Paren(x); } x @ b'+' | x @ b'*' => { self.expr = &self.expr[end..]; return Token::Op(x); } b'0'..=b'9' => { while end < self.expr.len() && bytes[end] != b' ' && !PARENS.contains(&bytes[end]) { end += 1; } let ret = Token::Literal(self.expr[start..end].parse::<i64>().unwrap()); self.expr = &self.expr[end..]; return ret; } x => panic!("Can't parse token {}", x), } } fn peek(&self) -> Token { let bytes = self.expr.as_bytes(); let mut start: usize = 0; while bytes[start] == b' ' { start += 1; } let mut end = start + 1; match bytes[start] { x @ b'(' | x @ b')' => { return Token::Paren(x); } x @ b'+' | x @ b'*' => { return Token::Op(x); } b'0'..=b'9' => { while end < self.expr.len() && bytes[end] != b' ' && !PARENS.contains(&bytes[end]) { end += 1; } return Token::Literal(self.expr[start..end].parse::<i64>().unwrap()); } x => panic!("Can't parse token {}", x), } } fn eval1(&mut self) -> i64 { let lhs = self.advance(); let mut res = match lhs { Token::Paren(b'(') => self.eval1(), Token::Literal(x) => x, token => panic!("Unexpected LHS token {:?}", token), }; while !self.expr.is_empty() { if self.peek() == Token::Paren(b')') { self.advance(); break; } let op = self.advance(); let rhs = self.advance(); let rhs_val = match rhs { Token::Paren(b'(') => self.eval1(), Token::Literal(x) => x, token => panic!("Unexpected RHS token {:?}", token), }; res = match op { Token::Op(b'+') => res + rhs_val, Token::Op(b'*') => res * rhs_val, op => panic!("Unexpected op {:?}", op), }; } return res } fn eval2(&mut self) -> i64 { let lhs = self.advance(); let mut res = match lhs { Token::Paren(b'(') => self.eval2(), Token::Literal(x) => x, token => panic!("Unexpected LHS token {:?}", token), }; while !self.expr.is_empty() { if self.peek() == Token::Paren(b')') { self.advance(); break; } let op = self.advance(); let rhs_val = match op { Token::Op(b'*') => self.eval2(), _ => { let rhs = self.advance(); match rhs { Token::Paren(b'(') => self.eval2(), Token::Literal(x) => x, token => panic!("Unexpected RHS token {:?}", token), } } }; res = match op { Token::Op(b'+') => res + rhs_val, Token::Op(b'*') => res * rhs_val, op => panic!("Unexpected op {:?}", op), }; if op == Token::Op(b'*') { break; } } return res } } fn main() { let mut sum:i64 = 0; let mut sum2:i64 = 0; for line in aoc::file_lines_iter("./day18.txt") { let mut p = Parser{expr: &line}; sum += p.eval1(); let mut p2 = Parser{expr: &line}; sum2 += p2.eval2(); } println!("Part 1: {}", sum); println!("Part 2: {}", sum2); }
use crate::{ linalg::{Mat, Vct}, Deserialize, Flt, Serialize, }; use serde::de::{Deserializer, SeqAccess, Visitor}; use serde::ser::{SerializeSeq, Serializer}; use std::fmt; #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(tag = "type", rename_all = "lowercase")] pub enum TransformType { Shift { x: Flt, y: Flt, z: Flt }, Scale { x: Flt, y: Flt, z: Flt }, Rotate { axis: String, degree: Flt }, RotateRadian { axis: String, radian: Flt }, } #[derive(Clone, Debug, Default)] pub struct Transform { pub seq: Vec<TransformType>, pub value: Mat, pub inv: Mat, } impl Transform { pub fn new(seq: Vec<TransformType>) -> Self { let mut ret = Self { seq, value: Mat::identity(), inv: Mat::identity() }; ret.compute(); ret } pub fn compute(&mut self) { let mut ans = Mat::identity(); self.seq.iter().for_each(|trans| { let m = match trans { TransformType::Shift { x, y, z } => Mat::shift(*x, *y, *z), TransformType::Scale { x, y, z } => Mat::scale(*x, *y, *z), TransformType::Rotate { axis, degree } => Mat::rot_degree(axis, *degree), TransformType::RotateRadian { axis, radian } => Mat::rot(axis, *radian), }; ans = m * ans; }); self.value = ans; let mut ans = Mat::identity(); self.seq.iter().for_each(|trans| { let m = match trans { TransformType::Shift { x, y, z } => Mat::shift(-x, -y, -z), TransformType::Scale { x, y, z } => Mat::scale(1.0 / x, 1.0 / y, 1.0 / z), TransformType::Rotate { axis, degree } => Mat::rot_degree(axis, -degree), TransformType::RotateRadian { axis, radian } => Mat::rot(axis, -radian), }; ans = ans * m; }); self.inv = ans; } pub fn pos(&self) -> Vct { Vct::new(self.value.m03, self.value.m13, self.value.m23) } pub fn x(&self) -> Vct { Vct::new(self.value.m00, self.value.m10, self.value.m20) } pub fn y(&self) -> Vct { Vct::new(self.value.m01, self.value.m11, self.value.m21) } pub fn z(&self) -> Vct { Vct::new(self.value.m02, self.value.m12, self.value.m22) } } impl Serialize for Transform { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { let mut seq = serializer.serialize_seq(Some(self.seq.len()))?; for e in self.seq.iter() { seq.serialize_element(e)?; } seq.end() } } impl<'de> Deserialize<'de> for Transform { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { struct TransformVisitor; impl<'de> Visitor<'de> for TransformVisitor { type Value = Transform; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("a sequence of Transform") } fn visit_seq<S>(self, mut seq: S) -> Result<Transform, S::Error> where S: SeqAccess<'de>, { let mut tmp: Vec<TransformType> = Vec::new(); while let Some(value) = seq.next_element()? { tmp.push(value); } let mut trans = Transform::new(tmp); trans.compute(); Ok(trans) } } deserializer.deserialize_seq(TransformVisitor {}) } }
// this is just a comment line introduced to evaulate git push use a7q3_lib::calculater::probabilty; fn main() { let input: u32 = 7; let output = probabilty::factorial(input); println!("Factorial of {} is {}",input, output); }
pub struct Solution; impl Solution { pub fn product_except_self(nums: Vec<i32>) -> Vec<i32> { let n = nums.len(); let mut res = vec![0; n]; let mut p = 1; for i in 0..n { res[i] = p; p *= nums[i]; } p = 1; for i in (0..n).rev() { res[i] *= p; p *= nums[i]; } res } } #[test] fn test0238() { fn case(nums: Vec<i32>, want: Vec<i32>) { let got = Solution::product_except_self(nums); assert_eq!(got, want); } case(vec![1, 2, 3, 4], vec![24, 12, 8, 6]); }
// Largely translated from this: http://paulbourke.net/geometry/polygonise/ use crate::graphics::{render_target, DrawMode, Drawable}; use crate::particles::{consts, fieldprovider::FieldProvider}; use gl_bindings::{shaders::OurShader, shaders::ShaderAttribute, Buffer, BufferType}; use na::Matrix4; use resources::shaders::{OBJ_FRAGMENT_SHADER, OBJ_VERTEX_SHADER}; use std::{rc::Rc, str}; pub struct MarchingCubes { vertices: Buffer<f32>, shader: Rc<OurShader>, } type Vector3 = (f32, f32, f32); impl Drawable for MarchingCubes { fn get_shader(&self) -> Option<Rc<OurShader>> { Some(self.shader.clone()) } fn draw_transformed(&self, view_matrix: &Matrix4<f32>) { let len = self.vertices.len() as i32 / 6; render_target::draw_vertex_array( DrawMode::TRIANGLES, 0, len, &self.vertices, &self.render_states(), view_matrix, ) } } impl MarchingCubes { /// Sets the direction of the light illuminating the mesh. pub fn set_light_dir(&self, (x, y, z): Vector3) { let dist = (x * x + y * y + z * z).sqrt(); self.shader .uniform3f("lightDir", x / dist, y / dist, z / dist); } /// Sets the transparency of the mesh. /// Argument should be 0.0 <= x <= 1.0. pub fn set_transparency(&self, transparency: f32) { self.shader.uniform1f("u_transparency", transparency); } pub fn marching_cubes(field: &FieldProvider) -> MarchingCubes { let mut vertices = Buffer::<f32>::new(BufferType::Array); const EPSILON: f32 = 0.1; // NOTE: 0.1 to reduce noise in data. const S: usize = 1; // step size let mut verts: [Vector3; 12] = [(0.0, 0.0, 0.0); 12]; // Equivalent to `for x in... for y in... for z in... let iterator = (0..field.width) .step_by(S) .flat_map(|x| (0..field.height).step_by(S).map(move |y| (x, y))) .flat_map(|(x, y)| (0..field.depth).step_by(S).map(move |z| (x, y, z))); for (x, y, z) in iterator { let xs = x + S; let ys = y + S; let zs = z + S; let v1m = field.get_len((x, y, z)); let v2m = field.get_len((xs, y, z)); let v3m = field.get_len((xs, y, zs)); let v4m = field.get_len((x, y, zs)); let v5m = field.get_len((x, ys, z)); let v6m = field.get_len((xs, ys, z)); let v7m = field.get_len((xs, ys, zs)); let v8m = field.get_len((x, ys, zs)); let mut cidx: usize = 0; cidx |= if v1m > EPSILON { 1 } else { 0 }; cidx |= if v2m > EPSILON { 2 } else { 0 }; cidx |= if v3m > EPSILON { 4 } else { 0 }; cidx |= if v4m > EPSILON { 8 } else { 0 }; cidx |= if v5m > EPSILON { 16 } else { 0 }; cidx |= if v6m > EPSILON { 32 } else { 0 }; cidx |= if v7m > EPSILON { 64 } else { 0 }; cidx |= if v8m > EPSILON { 128 } else { 0 }; let edges = consts::MARCHING_CUBES_EDGE_TABLE[cidx]; // This voxel is not on an edge if edges == 0 { continue; } let fx1 = x as f32 / field.width as f32; let fy1 = y as f32 / field.height as f32; let fz1 = z as f32 / field.depth as f32; let dx = S as f32 / field.width as f32; let dy = S as f32 / field.height as f32; let dz = S as f32 / field.depth as f32; let fx2 = fx1 + dx; let fy2 = fy1 + dy; let fz2 = fz1 + dz; let v = &mut verts; let push = &MarchingCubes::push_edge; let ep = EPSILON; push(edges, 00, v, ep, (fx1, fy1, fz1), (fx2, fy1, fz1), v1m, v2m); push(edges, 01, v, ep, (fx2, fy1, fz1), (fx2, fy1, fz2), v2m, v3m); push(edges, 02, v, ep, (fx2, fy1, fz2), (fx1, fy1, fz2), v3m, v4m); push(edges, 03, v, ep, (fx1, fy1, fz2), (fx1, fy1, fz1), v4m, v1m); push(edges, 04, v, ep, (fx1, fy2, fz1), (fx2, fy2, fz1), v5m, v6m); push(edges, 05, v, ep, (fx2, fy2, fz1), (fx2, fy2, fz2), v6m, v7m); push(edges, 06, v, ep, (fx2, fy2, fz2), (fx1, fy2, fz2), v7m, v8m); push(edges, 07, v, ep, (fx1, fy2, fz2), (fx1, fy2, fz1), v8m, v5m); push(edges, 08, v, ep, (fx1, fy1, fz1), (fx1, fy2, fz1), v1m, v5m); push(edges, 09, v, ep, (fx2, fy1, fz1), (fx2, fy2, fz1), v2m, v6m); push(edges, 10, v, ep, (fx2, fy1, fz2), (fx2, fy2, fz2), v3m, v7m); push(edges, 11, v, ep, (fx1, fy1, fz2), (fx1, fy2, fz2), v4m, v8m); let mut id = 0; let triangle_table = &consts::MARCHING_CUBES_TRIANGLE_TABLE; while triangle_table[cidx][id] != -1 { let v1 = verts[triangle_table[cidx][id] as usize]; let v2 = verts[triangle_table[cidx][id + 1] as usize]; let v3 = verts[triangle_table[cidx][id + 2] as usize]; let ab = (v2.0 - v1.0, v2.1 - v1.1, v2.2 - v1.2); let cb = (v3.0 - v1.0, v3.1 - v1.1, v3.2 - v1.2); let cross = ( cb.1 * ab.2 - cb.2 * ab.1, cb.2 * ab.0 - cb.0 * ab.2, cb.0 * ab.1 - cb.1 * ab.0, ); let dist = (cross.0 * cross.0 + cross.1 * cross.1 + cross.2 * cross.2).sqrt(); let norm = (cross.0 / dist, cross.1 / dist, cross.2 / dist); MarchingCubes::push_vert(&mut vertices, v1, norm); MarchingCubes::push_vert(&mut vertices, v2, norm); MarchingCubes::push_vert(&mut vertices, v3, norm); id += 3; } } vertices.bind(); let len = vertices.len(); vertices.upload_data(0, len, true); let shader: OurShader = OurShader::new( str::from_utf8(OBJ_VERTEX_SHADER).expect("Failed to read vertex shader"), str::from_utf8(OBJ_FRAGMENT_SHADER).expect("Failed to read fragment shader"), &[ ShaderAttribute { name: "a_position".to_string(), size: 3, }, ShaderAttribute { name: "a_normal".to_string(), size: 3, }, ], ); MarchingCubes { vertices, shader: Rc::new(shader), } } #[allow(clippy::too_many_arguments)] fn push_edge( edges: u32, edge: usize, verts: &mut [Vector3], epsilon: f32, v1: Vector3, v2: Vector3, m1: f32, m2: f32, ) { if edges & (1 << edge) != 0 { verts[edge] = MarchingCubes::interp(epsilon, v1, v2, m1, m2); } } fn push_vert(vertices: &mut Buffer<f32>, (x, y, z): Vector3, (nx, ny, nz): Vector3) { vertices.push(&[ x - 0.5, y - 0.5, z - 0.5, // position nx, ny, nz, // normals ]) } fn interp(epsilon: f32, v1: Vector3, v2: Vector3, m1: f32, m2: f32) -> Vector3 { if (epsilon - m1).abs() < 0.00001 { return v1; } if (epsilon - m2).abs() < 0.00001 { return v2; } if (m1 - m2).abs() < 0.00001 { return v1; } let mu = (epsilon - m1) / (m2 - m1); let x = v1.0 + mu * (v2.0 - v1.0); let y = v1.1 + mu * (v2.1 - v1.1); let z = v1.2 + mu * (v2.2 - v1.2); (x, y, z) } }
use num::iter::range; use crate::riscv32_core::Riscv32Core; use crate::riscv32_core::Riscv32Env; use crate::riscv64_core::Riscv64Core; use crate::riscv64_core::Riscv64Env; use crate::riscv32_core::AddrT; use crate::riscv32_core::XlenT; use crate::riscv64_core::Xlen64T; use crate::riscv32_core::MemAccType; use crate::riscv32_core::MemResult; use crate::riscv_exception::ExceptCode; use crate::riscv32_core::PrivMode; use crate::riscv32_core::VMMode; use crate::riscv_csr::CsrAddr; use crate::riscv_exception::RiscvException; use crate::riscv_csr_bitdef::SYSREG_MSTATUS_MPP_LSB; use crate::riscv_csr_bitdef::SYSREG_MSTATUS_MPP_MSB; use crate::riscv_csr_bitdef::SYSREG_MSTATUS_MPRV_LSB; use crate::riscv_csr_bitdef::SYSREG_MSTATUS_MPRV_MSB; use crate::riscv_csr_bitdef::SYSREG_MSTATUS_MXR_LSB; use crate::riscv_csr_bitdef::SYSREG_MSTATUS_MXR_MSB; use crate::riscv_csr_bitdef::SYSREG_SATP_PPN_LSB; use crate::riscv_csr_bitdef::SYSREG_SATP_PPN_MSB; pub trait RiscvMmu { fn convert_virtual_address(&mut self, vaddr: AddrT, acc_type: MemAccType) -> (MemResult, AddrT); fn walk_page_table( &mut self, vaddr: AddrT, acc_type: MemAccType, init_level: u32, ppn_idx: Vec<u8>, pte_len: Vec<u8>, pte_idx: Vec<u8>, vpn_len: Vec<u8>, vpn_idx: Vec<u8>, PAGESIZE: u32, PTESIZE: u32, ) -> (MemResult, AddrT); fn is_allowed_access(&mut self, i_type: u8, acc_type: MemAccType, priv_mode: PrivMode) -> bool; } impl RiscvMmu for Riscv32Env { fn walk_page_table( &mut self, vaddr: AddrT, acc_type: MemAccType, init_level: u32, ppn_idx: Vec<u8>, pte_len: Vec<u8>, pte_idx: Vec<u8>, vpn_len: Vec<u8>, vpn_idx: Vec<u8>, PAGESIZE: u32, PTESIZE: u32, ) -> (MemResult, AddrT) { let is_write_access = match acc_type { MemAccType::Write => true, _ => false, }; //=================== // Simple TLB Search //=================== // let vaddr_vpn: AddrT = (vaddr >> 12); // let vaddr_tag: u8 = vaddr_vpn & (tlb_width-1); // if (m_tlb_en[vaddr_tag] && m_tlb_tag[vaddr_tag] == vaddr_vpn) { // let paddr:AddrT = (m_tlb_addr[vaddr_tag] & !0x0fff) + (vaddr & 0x0fff); // let pte_val:u64 = m_tlb_addr[vaddr_tag] & 0x0ff; // // if (!is_allowed_access ((pte_val >> 1) & 0x0f, acc_type, self.m_priv)) { // println! ("<Page Access Failed. Allowed Access Failed PTE_VAL=%016lx>", pte_val); // return (MemResult::TlbError, paddr); // } // if (((pte_val & 0x40) == 0) || // PTE.A // ((acc_type == MemAccType::Write) && (pte_val & 0x80) == 0)) { // PTE.D // println!("<Access Fault : Page Permission Fault {:01x}>", (pte_val >> 1) & 0x0f); // if (acc_type == MemAccType::Fetch) { // generate_exception (self, ExceptCode::InstPageFault, vaddr as XlenT); // } // return (MemResult::TlbError, paddr); // } // return (MemResult::NoExcept, paddr); // } let satp = self.m_csr.csrrs(CsrAddr::Satp, 0); let pte_base: AddrT = Self::extract_bit_field(satp, SYSREG_SATP_PPN_MSB, SYSREG_SATP_PPN_LSB) as AddrT; let mut pte_val: XlenT = 0; let mut pte_addr: AddrT = (pte_base * PAGESIZE) as AddrT; let level: usize = 0; for level in range(0, init_level).rev() { let va_vpn_i: AddrT = (vaddr >> vpn_idx[level as usize]) & ((1 << vpn_len[level as usize]) - 1); pte_addr += (va_vpn_i * PTESIZE) as AddrT; pte_val = self.read_memory_word(pte_addr); // println!( // "<Info: VAddr = 0x{:08x} PTEAddr = 0x{:08x} : PPTE = 0x{:08x}>", // vaddr, pte_addr, pte_val // ); // 3. If pte:v = 0, or if pte:r = 0 and pte:w = 1, stop and raise a page-fault exception. if (pte_val & 0x01) == 0 || (((pte_val & 0x02) == 0) && ((pte_val & 0x04) == 0x04)) { // let bit_length: u32 = m_bit_mode == RiscvBitMode_t::Bit32 ? 8 : 16; println!("<Page Table Error : 0x{:016x} = 0x{:08x} is not valid Page Table. Generate Exception>", pte_addr, pte_val); match acc_type { MemAccType::Fetch => { self.generate_exception(ExceptCode::InstPageFault, vaddr as XlenT); } MemAccType::Read => { self.generate_exception(ExceptCode::LoadPageFault, vaddr as XlenT); } MemAccType::Write => { self.generate_exception(ExceptCode::StorePageFault, vaddr as XlenT); } }; return (MemResult::TlbError, 0); } // If pte:r = 1 or pte:x = 1, go to step 5. Otherwise, this PTE is a // pointer to the next level of the page table. Let i = i − 1. If i < 0, stop and raise a page-fault // exception. Otherwise, let a = pte:ppn × PAGESIZE and go to step 2. if ((pte_val & 0x08) == 0x08) || ((pte_val & 0x02) == 0x02) { break; } else { if level == 0 { println!( "<Access Fault : Tried to Access to Page {:01x}>", ((pte_val >> 1) & 0x0f) ); match acc_type { MemAccType::Fetch => { self.generate_exception(ExceptCode::InstPageFault, vaddr as XlenT); } MemAccType::Read => { self.generate_exception(ExceptCode::LoadPageFault, vaddr as XlenT); } MemAccType::Write => { self.generate_exception(ExceptCode::StorePageFault, vaddr as XlenT); } }; return (MemResult::TlbError, 0); } } let pte_ppn: AddrT = Self::extract_bit_field( pte_val as XlenT, pte_len[(init_level - 1) as usize] + pte_idx[(init_level - 1) as usize] - 1, pte_idx[0], ) as AddrT; pte_addr = pte_ppn * PAGESIZE; } let current_priv: PrivMode = self.m_priv.clone(); if !self.is_allowed_access( ((pte_val >> 1) & 0x0f) as u8, acc_type.clone(), current_priv, ) { println!( "<Page Access Failed. Allowed Access Failed PTE_VAL={:016x}>", pte_val, ); return (MemResult::TlbError, 0); } if level != 0 && Self::extract_bit_field( pte_val as XlenT, pte_len[level - 1] + pte_idx[level - 1] - 1, pte_idx[0], ) != 0 { // 6. If i > 0 and pa:ppn[i−1:0] != 0, this is a misaligned superpage // stop and raise a page-fault exception. // println! ("<Page Access Failed. Last PTE != 0>"); return (MemResult::TlbError, 0); } if ((pte_val & 0x40) == 0) || // PTE.A (is_write_access && (pte_val & 0x80) == 0) { // PTE.D println!( "<Access Fault : Page Permission Fault {:01x}", ((pte_val >> 1) & 0x0f) ); match acc_type { MemAccType::Fetch => { self.generate_exception(ExceptCode::InstPageFault, vaddr as XlenT); } MemAccType::Read => { self.generate_exception(ExceptCode::LoadPageFault, vaddr as XlenT); } MemAccType::Write => { self.generate_exception(ExceptCode::StorePageFault, vaddr as XlenT); } }; return (MemResult::TlbError, 0); } let mut phy_addr: AddrT = (Self::extract_bit_field( pte_val as XlenT, pte_len[(init_level - 1) as usize] + pte_idx[(init_level - 1) as usize] - 1, pte_idx[level], ) << ppn_idx[level]) as AddrT; // println!("Level = {}", level); for l in 0..(level + 1) { let vaddr_vpn: AddrT = Self::extract_bit_field( vaddr as XlenT, vpn_len[level - l as usize] + vpn_idx[level - l as usize] - 1, vpn_idx[level - l as usize], ) as AddrT; phy_addr |= vaddr_vpn << ppn_idx[level as usize]; } // Finally Add Page Offset phy_addr |= Self::extract_bit_field(vaddr as XlenT, vpn_idx[0] - 1, 0) as AddrT; //========================== // Update Simple TLB Search //========================== // println!( // "<Info: TLB[{:d}] <= 0x{:016x}(0x{:016x})>", // vaddr as XlenT_tag, // vaddr as XlenT_vpn, // *paddr & !0x0fff // ); // m_tlb_en [vaddr_tag] = true; // m_tlb_tag [vaddr_tag] = vaddr_vpn; // m_tlb_addr[vaddr_tag] = (*paddr & !0x0fff) | (pte_val & 0x0ff); // println!("<Converted Virtual Address = {:08x}>", phy_addr); return (MemResult::NoExcept, phy_addr); } fn convert_virtual_address( &mut self, vaddr: AddrT, acc_type: MemAccType, ) -> (MemResult, AddrT) { let is_fetch_access = match acc_type { MemAccType::Fetch => true, _ => false, }; let mstatus: XlenT = self .m_csr .csrrs(CsrAddr::Mstatus, PrivMode::Machine as XlenT); let mprv: u8 = Self::extract_bit_field(mstatus, SYSREG_MSTATUS_MPRV_MSB, SYSREG_MSTATUS_MPRV_LSB) as u8; let mpp_u8: u8 = Self::extract_bit_field(mstatus, SYSREG_MSTATUS_MPP_MSB, SYSREG_MSTATUS_MPP_LSB) as u8; let mpp: PrivMode = PrivMode::from_u8(mpp_u8); let priv_mode: PrivMode = if !is_fetch_access && (mprv != 0) { mpp } else { self.m_priv }; // println!("<Convert Virtual Addres : vm_mode = {}, priv_mode = {}>", // self.get_vm_mode() as u32, priv_mode as u32); if self.get_vm_mode() == VMMode::Sv39 && (priv_mode == PrivMode::Supervisor || priv_mode == PrivMode::User) { let ppn_idx: Vec<u8> = vec![12, 21, 30]; let pte_len: Vec<u8> = vec![9, 9, 26]; let pte_idx: Vec<u8> = vec![10, 19, 28]; let vpn_len: Vec<u8> = vec![9, 9, 9]; let vpn_idx: Vec<u8> = vec![12, 21, 30]; const PAGESIZE: u32 = 4096; // num::pow(2, 12); const PTESIZE: u32 = 8; return self.walk_page_table( vaddr, acc_type, 3, ppn_idx, pte_len, pte_idx, vpn_len, vpn_idx, PAGESIZE, PTESIZE, ); } else if self.get_vm_mode() == VMMode::Sv32 && (priv_mode == PrivMode::Supervisor || priv_mode == PrivMode::User) { let ppn_idx: Vec<u8> = vec![12, 22]; let pte_len: Vec<u8> = vec![10, 12]; let pte_idx: Vec<u8> = vec![10, 20]; let vpn_len: Vec<u8> = vec![10, 10]; let vpn_idx: Vec<u8> = vec![12, 22]; const PAGESIZE: u32 = 4096; // num::pow(2, 12); const PTESIZE: u32 = 4; return self.walk_page_table( vaddr, acc_type, 2, ppn_idx, pte_len, pte_idx, vpn_len, vpn_idx, PAGESIZE, PTESIZE, ); } else { return (MemResult::NoExcept, vaddr); } } fn is_allowed_access(&mut self, i_type: u8, acc_type: MemAccType, priv_mode: PrivMode) -> bool { let is_user_mode = match priv_mode { PrivMode::User => true, _ => false, }; if is_user_mode && !((i_type & 0x08) != 0) { return false; } let allowed_access = match acc_type { MemAccType::Fetch => (i_type & 0x04) != 0, MemAccType::Write => ((i_type & 0x01) != 0) && ((i_type & 0x02) != 0), MemAccType::Read => { let mstatus: XlenT = self.m_csr.csrrs(CsrAddr::Mstatus, 0); let mxr: u8 = Self::extract_bit_field( mstatus, SYSREG_MSTATUS_MXR_MSB, SYSREG_MSTATUS_MXR_LSB, ) as u8; ((i_type & 0x01) != 0) | ((mxr & (i_type & 0x04)) != 0) } }; return allowed_access; } } impl RiscvMmu for Riscv64Env { fn walk_page_table( &mut self, vaddr: AddrT, acc_type: MemAccType, init_level: u32, ppn_idx: Vec<u8>, pte_len: Vec<u8>, pte_idx: Vec<u8>, vpn_len: Vec<u8>, vpn_idx: Vec<u8>, PAGESIZE: u32, PTESIZE: u32, ) -> (MemResult, AddrT) { let is_write_access = match acc_type { MemAccType::Write => true, _ => false, }; //=================== // Simple TLB Search //=================== // let vaddr_vpn: AddrT = (vaddr >> 12); // let vaddr_tag: u8 = vaddr_vpn & (tlb_width-1); // if (m_tlb_en[vaddr_tag] && m_tlb_tag[vaddr_tag] == vaddr_vpn) { // let paddr:AddrT = (m_tlb_addr[vaddr_tag] & !0x0fff) + (vaddr & 0x0fff); // let pte_val:u64 = m_tlb_addr[vaddr_tag] & 0x0ff; // // if (!is_allowed_access ((pte_val >> 1) & 0x0f, acc_type, self.m_priv)) { // println! ("<Page Access Failed. Allowed Access Failed PTE_VAL=%016lx>", pte_val); // return (MemResult::TlbError, paddr); // } // if (((pte_val & 0x40) == 0) || // PTE.A // ((acc_type == MemAccType::Write) && (pte_val & 0x80) == 0)) { // PTE.D // println!("<Access Fault : Page Permission Fault {:01x}>", (pte_val >> 1) & 0x0f); // if (acc_type == MemAccType::Fetch) { // generate_exception (self, ExceptCode::InstPageFault, vaddr as Xlen64T); // } // return (MemResult::TlbError, paddr); // } // return (MemResult::NoExcept, paddr); // } let satp = self.m_csr.csrrs(CsrAddr::Satp, 0) as Xlen64T; let pte_base: AddrT = Self::extract_bit_field(satp, SYSREG_SATP_PPN_MSB, SYSREG_SATP_PPN_LSB) as AddrT; let mut pte_val: Xlen64T = 0; let mut pte_addr: AddrT = (pte_base * PAGESIZE) as AddrT; let level: usize = 0; for level in range(0, init_level).rev() { let va_vpn_i: AddrT = (vaddr >> vpn_idx[level as usize]) & ((1 << vpn_len[level as usize]) - 1); pte_addr += (va_vpn_i * PTESIZE) as AddrT; pte_val = self.read_memory_word(pte_addr); // println!( // "<Info: VAddr = 0x{:08x} PTEAddr = 0x{:08x} : PPTE = 0x{:08x}>", // vaddr, pte_addr, pte_val // ); // 3. If pte:v = 0, or if pte:r = 0 and pte:w = 1, stop and raise a page-fault exception. if (pte_val & 0x01) == 0 || (((pte_val & 0x02) == 0) && ((pte_val & 0x04) == 0x04)) { // let bit_length: u32 = m_bit_mode == RiscvBitMode_t::Bit32 ? 8 : 16; println!("<Page Table Error : 0x{:016x} = 0x{:08x} is not valid Page Table. Generate Exception>", pte_addr, pte_val); match acc_type { MemAccType::Fetch => { self.generate_exception(ExceptCode::InstPageFault, vaddr as Xlen64T); } MemAccType::Read => { self.generate_exception(ExceptCode::LoadPageFault, vaddr as Xlen64T); } MemAccType::Write => { self.generate_exception(ExceptCode::StorePageFault, vaddr as Xlen64T); } }; return (MemResult::TlbError, 0); } // If pte:r = 1 or pte:x = 1, go to step 5. Otherwise, this PTE is a // pointer to the next level of the page table. Let i = i − 1. If i < 0, stop and raise a page-fault // exception. Otherwise, let a = pte:ppn × PAGESIZE and go to step 2. if ((pte_val & 0x08) == 0x08) || ((pte_val & 0x02) == 0x02) { break; } else { if level == 0 { println!( "<Access Fault : Tried to Access to Page {:01x}>", ((pte_val >> 1) & 0x0f) ); match acc_type { MemAccType::Fetch => { self.generate_exception(ExceptCode::InstPageFault, vaddr as Xlen64T); } MemAccType::Read => { self.generate_exception(ExceptCode::LoadPageFault, vaddr as Xlen64T); } MemAccType::Write => { self.generate_exception(ExceptCode::StorePageFault, vaddr as Xlen64T); } }; return (MemResult::TlbError, 0); } } let pte_ppn: AddrT = Self::extract_bit_field( pte_val as Xlen64T, pte_len[(init_level - 1) as usize] + pte_idx[(init_level - 1) as usize] - 1, pte_idx[0], ) as AddrT; pte_addr = pte_ppn * PAGESIZE; } let current_priv: PrivMode = self.m_priv.clone(); if !self.is_allowed_access( ((pte_val >> 1) & 0x0f) as u8, acc_type.clone(), current_priv, ) { println!( "<Page Access Failed. Allowed Access Failed PTE_VAL={:016x}>", pte_val, ); return (MemResult::TlbError, 0); } if level != 0 && Self::extract_bit_field( pte_val as Xlen64T, pte_len[level - 1] + pte_idx[level - 1] - 1, pte_idx[0], ) != 0 { // 6. If i > 0 and pa:ppn[i−1:0] != 0, this is a misaligned superpage // stop and raise a page-fault exception. // println! ("<Page Access Failed. Last PTE != 0>"); return (MemResult::TlbError, 0); } if ((pte_val & 0x40) == 0) || // PTE.A (is_write_access && (pte_val & 0x80) == 0) { // PTE.D println!( "<Access Fault : Page Permission Fault {:01x}", ((pte_val >> 1) & 0x0f) ); match acc_type { MemAccType::Fetch => { self.generate_exception(ExceptCode::InstPageFault, vaddr as Xlen64T); } MemAccType::Read => { self.generate_exception(ExceptCode::LoadPageFault, vaddr as Xlen64T); } MemAccType::Write => { self.generate_exception(ExceptCode::StorePageFault, vaddr as Xlen64T); } }; return (MemResult::TlbError, 0); } let mut phy_addr: AddrT = (Self::extract_bit_field( pte_val as Xlen64T, pte_len[(init_level - 1) as usize] + pte_idx[(init_level - 1) as usize] - 1, pte_idx[level], ) << ppn_idx[level]) as AddrT; // println!("Level = {}", level); for l in 0..(level + 1) { let vaddr_vpn: AddrT = Self::extract_bit_field( vaddr as Xlen64T, vpn_len[level - l as usize] + vpn_idx[level - l as usize] - 1, vpn_idx[level - l as usize], ) as AddrT; phy_addr |= vaddr_vpn << ppn_idx[level as usize]; } // Finally Add Page Offset phy_addr |= Self::extract_bit_field(vaddr as Xlen64T, vpn_idx[0] - 1, 0) as AddrT; //========================== // Update Simple TLB Search //========================== // println!( // "<Info: TLB[{:d}] <= 0x{:016x}(0x{:016x})>", // vaddr as Xlen64T_tag, // vaddr as Xlen64T_vpn, // *paddr & !0x0fff // ); // m_tlb_en [vaddr_tag] = true; // m_tlb_tag [vaddr_tag] = vaddr_vpn; // m_tlb_addr[vaddr_tag] = (*paddr & !0x0fff) | (pte_val & 0x0ff); // println!("<Converted Virtual Address = {:08x}>", phy_addr); return (MemResult::NoExcept, phy_addr); } fn convert_virtual_address( &mut self, vaddr: AddrT, acc_type: MemAccType, ) -> (MemResult, AddrT) { let is_fetch_access = match acc_type { MemAccType::Fetch => true, _ => false, }; let mstatus: Xlen64T = self .m_csr .csrrs(CsrAddr::Mstatus, PrivMode::Machine as Xlen64T); let mprv: u8 = Self::extract_bit_field(mstatus, SYSREG_MSTATUS_MPRV_MSB, SYSREG_MSTATUS_MPRV_LSB) as u8; let mpp_u8: u8 = Self::extract_bit_field(mstatus, SYSREG_MSTATUS_MPP_MSB, SYSREG_MSTATUS_MPP_LSB) as u8; let mpp: PrivMode = PrivMode::from_u8(mpp_u8); let priv_mode: PrivMode = if !is_fetch_access && (mprv != 0) { mpp } else { self.m_priv }; // println!("<Convert Virtual Addres : vm_mode = {}, priv_mode = {}>", // self.get_vm_mode() as u32, priv_mode as u32); if self.get_vm_mode() == VMMode::Sv39 && (priv_mode == PrivMode::Supervisor || priv_mode == PrivMode::User) { let ppn_idx: Vec<u8> = vec![12, 21, 30]; let pte_len: Vec<u8> = vec![9, 9, 26]; let pte_idx: Vec<u8> = vec![10, 19, 28]; let vpn_len: Vec<u8> = vec![9, 9, 9]; let vpn_idx: Vec<u8> = vec![12, 21, 30]; const PAGESIZE: u32 = 4096; // num::pow(2, 12); const PTESIZE: u32 = 8; return self.walk_page_table( vaddr, acc_type, 3, ppn_idx, pte_len, pte_idx, vpn_len, vpn_idx, PAGESIZE, PTESIZE, ); } else if self.get_vm_mode() == VMMode::Sv32 && (priv_mode == PrivMode::Supervisor || priv_mode == PrivMode::User) { let ppn_idx: Vec<u8> = vec![12, 22]; let pte_len: Vec<u8> = vec![10, 12]; let pte_idx: Vec<u8> = vec![10, 20]; let vpn_len: Vec<u8> = vec![10, 10]; let vpn_idx: Vec<u8> = vec![12, 22]; const PAGESIZE: u32 = 4096; // num::pow(2, 12); const PTESIZE: u32 = 4; return self.walk_page_table( vaddr, acc_type, 2, ppn_idx, pte_len, pte_idx, vpn_len, vpn_idx, PAGESIZE, PTESIZE, ); } else { return (MemResult::NoExcept, vaddr); } } fn is_allowed_access(&mut self, i_type: u8, acc_type: MemAccType, priv_mode: PrivMode) -> bool { let is_user_mode = match priv_mode { PrivMode::User => true, _ => false, }; if is_user_mode && !((i_type & 0x08) != 0) { return false; } let allowed_access = match acc_type { MemAccType::Fetch => (i_type & 0x04) != 0, MemAccType::Write => ((i_type & 0x01) != 0) && ((i_type & 0x02) != 0), MemAccType::Read => { let mstatus: Xlen64T = self.m_csr.csrrs(CsrAddr::Mstatus, 0); let mxr: u8 = Self::extract_bit_field( mstatus, SYSREG_MSTATUS_MXR_MSB, SYSREG_MSTATUS_MXR_LSB, ) as u8; ((i_type & 0x01) != 0) | ((mxr & (i_type & 0x04)) != 0) } }; return allowed_access; } }
#![deny(missing_docs)] //! `bincode` is a crate for encoding and decoding using a tiny binary //! serialization strategy. //! //! There are simple functions for encoding to `Vec<u8>` and decoding from //! `&[u8]`, but the meat of the library is the `serialize_into` and `deserialize_from` //! functions which respectively allow encoding into any `std::io::Write` //! or decode from any `std::io::Read`. //! //! ## Modules //! Until "default type parameters" lands, we have an extra module called `endian_choice` //! that duplicates all of the core bincode functionality but with the option to choose //! which endianness the integers are encoded using. //! //! The default endianness is little. //! //! ### Using Basic Functions //! //! ```rust //! extern crate bincode; //! use bincode::{serialize, deserialize, Bounded}; //! fn main() { //! // The object that we will serialize. //! let target = Some("hello world".to_string()); //! // The maximum size of the encoded message. //! let limit = Bounded(20); //! //! let encoded: Vec<u8> = serialize(&target, limit).unwrap(); //! let decoded: Option<String> = deserialize(&encoded[..]).unwrap(); //! assert_eq!(target, decoded); //! } //! ``` #![crate_name = "bincode"] #![crate_type = "rlib"] #![crate_type = "dylib"] extern crate byteorder; extern crate serde as serde_crate; mod ser; mod de; pub mod internal; pub mod read_types { //! The types that the deserializer uses for optimizations pub use de::read::{SliceReader, BincodeRead, IoReader}; } use std::io::{Read, Write}; pub use internal::{ErrorKind, Error, Result, serialized_size, serialized_size_bounded}; /// A Deserializer that uses LittleEndian byteorder pub type Deserializer<W, S> = internal::Deserializer<W, S, byteorder::LittleEndian>; /// A Serializer that uses LittleEndian byteorder pub type Serializer<W> = internal::Serializer<W, byteorder::LittleEndian>; /// Deserializes a slice of bytes into an object. /// /// This method does not have a size-limit because if you already have the bytes /// in memory, then you don't gain anything by having a limiter. pub fn deserialize<'a, T>(bytes: &'a [u8]) -> internal::Result<T> where T: serde_crate::de::Deserialize<'a>, { internal::deserialize::<_, byteorder::LittleEndian>(bytes) } /// Deserializes an object directly from a `Buffer`ed Reader. /// /// If the provided `SizeLimit` is reached, the deserialization will bail immediately. /// A SizeLimit can help prevent an attacker from flooding your server with /// a neverending stream of values that runs your server out of memory. /// /// If this returns an `Error`, assume that the buffer that you passed /// in is in an invalid state, as the error could be returned during any point /// in the reading. pub fn deserialize_from<R: ?Sized, T, S>(reader: &mut R, size_limit: S) -> internal::Result<T> where R: Read, T: serde_crate::de::DeserializeOwned, S: SizeLimit, { internal::deserialize_from::<_, _, _, byteorder::LittleEndian>(reader, size_limit) } /// Serializes an object directly into a `Writer`. /// /// If the serialization would take more bytes than allowed by `size_limit`, an error /// is returned and *no bytes* will be written into the `Writer`. /// /// If this returns an `Error` (other than SizeLimit), assume that the /// writer is in an invalid state, as writing could bail out in the middle of /// serializing. pub fn serialize_into<W: ?Sized, T: ?Sized, S>( writer: &mut W, value: &T, size_limit: S, ) -> internal::Result<()> where W: Write, T: serde_crate::Serialize, S: SizeLimit, { internal::serialize_into::<_, _, _, byteorder::LittleEndian>(writer, value, size_limit) } /// Serializes a serializable object into a `Vec` of bytes. /// /// If the serialization would take more bytes than allowed by `size_limit`, /// an error is returned. pub fn serialize<T: ?Sized, S>(value: &T, size_limit: S) -> internal::Result<Vec<u8>> where T: serde_crate::Serialize, S: SizeLimit, { internal::serialize::<_, _, byteorder::LittleEndian>(value, size_limit) } /// A limit on the amount of bytes that can be read or written. /// /// Size limits are an incredibly important part of both encoding and decoding. /// /// In order to prevent DOS attacks on a decoder, it is important to limit the /// amount of bytes that a single encoded message can be; otherwise, if you /// are decoding bytes right off of a TCP stream for example, it would be /// possible for an attacker to flood your server with a 3TB vec, causing the /// decoder to run out of memory and crash your application! /// Because of this, you can provide a maximum-number-of-bytes that can be read /// during decoding, and the decoder will explicitly fail if it has to read /// any more than that. /// /// On the other side, you want to make sure that you aren't encoding a message /// that is larger than your decoder expects. By supplying a size limit to an /// encoding function, the encoder will verify that the structure can be encoded /// within that limit. This verification occurs before any bytes are written to /// the Writer, so recovering from an error is easy. pub trait SizeLimit: private::Sealed { /// Tells the SizeLimit that a certain number of bytes has been /// read or written. Returns Err if the limit has been exceeded. fn add(&mut self, n: u64) -> Result<()>; /// Returns the hard limit (if one exists) fn limit(&self) -> Option<u64>; } /// A SizeLimit that restricts serialized or deserialized messages from /// exceeding a certain byte length. #[derive(Copy, Clone)] pub struct Bounded(pub u64); /// A SizeLimit without a limit! /// Use this if you don't care about the size of encoded or decoded messages. #[derive(Copy, Clone)] pub struct Infinite; struct CountSize { total: u64, limit: Option<u64>, } impl SizeLimit for Bounded { #[inline(always)] fn add(&mut self, n: u64) -> Result<()> { if self.0 >= n { self.0 -= n; Ok(()) } else { Err(Box::new(ErrorKind::SizeLimit)) } } #[inline(always)] fn limit(&self) -> Option<u64> { Some(self.0) } } impl SizeLimit for Infinite { #[inline(always)] fn add(&mut self, _: u64) -> Result<()> { Ok(()) } #[inline(always)] fn limit(&self) -> Option<u64> { None } } mod private { pub trait Sealed {} impl<'a> Sealed for super::de::read::SliceReader<'a> {} impl<R> Sealed for super::de::read::IoReader<R> {} impl Sealed for super::Infinite {} impl Sealed for super::Bounded {} impl Sealed for super::CountSize {} }
#[doc = "Reader of register TX_LPI_USEC_CNTR"] pub type R = crate::R<u32, super::TX_LPI_USEC_CNTR>; #[doc = "Reader of field `TXLPIUSC`"] pub type TXLPIUSC_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - Tx LPI Microseconds Counter"] #[inline(always)] pub fn txlpiusc(&self) -> TXLPIUSC_R { TXLPIUSC_R::new((self.bits & 0xffff_ffff) as u32) } }
use std::cell::RefCell; pub struct Seed(RefCell<u64>); impl Default for Seed { fn default() -> Self { Self(RefCell::new(1)) } } impl Seed { pub fn generate(&self) -> u64 { self.alloc(1) } pub fn alloc(&self, len: u64) -> u64 { let mut seed = self.0.borrow_mut(); let seed_origin = *seed; *seed += len; seed_origin } }
use std::error::Error; use std::process; mod mender; mod parse; fn main() { let matches = parse::build_cli().get_matches(); let command = parse::Command::new(matches).unwrap_or_else(|err| { println!("Parse error: {}", err); process::exit(1); }); let config = parse::Config::new(command).unwrap_or_else(|err| { println!("Config error: {}", err); process::exit(1); }); if let Err(e) = run(config) { println!("Run error: {}", e); process::exit(2); } } fn run(config: parse::Config) -> Result<(), Box<dyn Error>> { match config.command { parse::Command::Login { .. } => { println!("Type password:"); let mut password = String::new(); std::io::stdin().read_line(&mut password)?; println!("Token {}", mender::get_token(&config, &password.trim())?); } parse::Command::Deploy { .. } => { println!("Deployed to {} devices", mender::deploy(&config)?) } parse::Command::GetId { .. } => println!("Mender id is: {}", mender::get_id(&config)?), parse::Command::GetInfo { .. } => println!("{}", mender::get_info(&config)?), parse::Command::CountArtifacts => println!("{}", mender::count_artifacts(&config)?), }; Ok(()) }
use crate::{FunctionData, Instruction, Label, Value}; struct SkewedCFGInfo { skew: Label, exit: Label, true_pred: Label, false_pred: Label, } fn make_unconditional_branch(function: &mut FunctionData, from: Label, to: Label) { let body = function.blocks.get_mut(&from).unwrap(); let body_size = body.len(); body[body_size - 1] = Instruction::Branch { target: to, }; } fn move_instructions(function: &mut FunctionData, treshold: usize, from: &[Label], to: Label) -> bool { let mut total_instructions = 0; for &label in from { let body = &function.blocks[&label]; let size = body.len(); // Ignore last instruction (branch) as it will be removed anyway. for instruction in &body[..size - 1] { if !instruction.can_be_reordered() { return false; } if !instruction.is_nop() { total_instructions += 1; } } } if total_instructions > treshold { return false; } for &from in from { // Remove all body of this label as it's unlinked from CFG anyway. let mut body = function.blocks.remove(&from).unwrap(); // Remove the last branch. body.pop(); let to_body = function.blocks.get_mut(&to).unwrap(); // Move all instruction from this label to the beginning // of `exit`. for instruction in body.into_iter().rev() { to_body.insert(0, instruction); } } true } fn rewrite_phis_to_selects(function: &mut FunctionData, condition: Value, label: Label, true_label: Label, false_label: Label) { let body = function.blocks.get_mut(&label).unwrap(); for instruction in body { if let Instruction::Phi { dst, incoming } = instruction { assert_eq!(incoming.len(), 2, "Number of incoming values \ doesn't match block predecessor count."); let mut true_value = None; let mut false_value = None; // Get value which is returned when we enter from true label and // value which is returned when we enter from false label. for &mut (label, value) in incoming { if label == true_label { true_value = Some(value); } if label == false_label { false_value = Some(value); } } let true_value = true_value.unwrap(); let false_value = false_value.unwrap(); // Rewrite: // v5 = phi [on_true: v4; on_false: v5] // To: // v5 = select cond, v4, v5 *instruction = Instruction::Select { dst: *dst, cond: condition, on_true: true_value, on_false: false_value, }; } } } pub struct BranchToSelectPass; impl super::Pass for BranchToSelectPass { fn name(&self) -> &str { "branch to select" } fn time(&self) -> crate::timing::TimedBlock { crate::timing::branch_to_select() } fn run_on_function(&self, function: &mut FunctionData) -> bool { let mut did_something = false; // Find branches which only purpose is to select value and change them to `select` // instruction. This can be only done if there are no volatile operations in // branch arms and memory accesses. // // entry: // v2 = u32 4 // v4 = cmp eq u32 v0, v2 // bcond u1 v4, block_2, block_3 // // block_2: // v10 = u32 555 // branch block_1 // // block_3: // v11 = u32 823 // branch block_1 // // block_1: // v15 = phi u32 [block_3: v11, block_2: v10] // ret u32 v15 // // Will get optimized to: // entry: // v11 = u32 823 // v10 = u32 555 // v2 = u32 4 // v4 = cmp eq u32 v0, v2 // v15 = select u1 v4, u32 v10, v11 // ret u32 v15 const COPY_TRESHOLD: usize = 8; 'main_loop: loop { // Recalculate data as we have altered the CFG. let labels = function.reachable_labels(); let flow_incoming = function.flow_graph_incoming(); 'next_label: for label in labels { let bcond = function.last_instruction(label); if let Instruction::BranchCond { cond, on_true, on_false } = *bcond { // Skip conditional branches with both labels equal and skip loops. if on_true == on_false || on_true == label || on_false == label { continue 'next_label; } // Get unconditional branch target for `on_true`. let mut true_exit = None; if let Instruction::Branch { target } = function.last_instruction(on_true) { true_exit = Some(*target); } // Get unconditional branch target for `on_false`. let mut false_exit = None; if let Instruction::Branch { target } = function.last_instruction(on_false) { false_exit = Some(*target); } let mut skew_info = None; // A // / \ // B | // \ / // D // Try to detect both left-skew and right-skew in the CFG. if false_exit == Some(on_true) { // B - `on_false`. // D - `on_true`. skew_info = Some(SkewedCFGInfo { skew: on_false, exit: on_true, true_pred: label, false_pred: on_false, }); } else if true_exit == Some(on_false) { // B - `on_true`. // D - `on_false`. skew_info = Some(SkewedCFGInfo { skew: on_true, exit: on_false, true_pred: on_true, false_pred: label, }); } if let Some(skew_info) = skew_info { let SkewedCFGInfo { skew, exit, true_pred, false_pred, } = skew_info; // Skew should be only reachable from `label` and `exit` should be // reachable from `label` and `skew`. if flow_incoming[&skew].len() != 1 || flow_incoming[&exit].len() != 2 { continue 'next_label; } // Avoid loops. if skew == exit || skew == label || exit == label { continue 'next_label; } // Try to copy all instructions from `skew` to `exit`. if !move_instructions(function, COPY_TRESHOLD, &[skew], exit) { continue 'next_label; } // Make `label` jump directly to `exit`. This will unlink `skew` from // CFG. make_unconditional_branch(function, label, exit); rewrite_phis_to_selects(function, cond, exit, true_pred, false_pred); // As we have altered CFG we cannot continue this loop so // we go directly to the main loop. continue 'main_loop; } // To continue, both `on_true` and `on_false` must end with unconditional // branch. if true_exit.is_none() || false_exit.is_none() { continue 'next_label; } let true_exit = true_exit.unwrap(); let false_exit = false_exit.unwrap(); // We cannot optimize this branch if `on_true` or `on_false` label is // reachable from somewhere else then from `label`. if flow_incoming[&on_true].len() != 1 || flow_incoming[&on_false].len() != 1 { continue 'next_label; } // Get exit label if there is a common one. Otherwise we cannot optimize // branch out so we continue. let exit = if true_exit == false_exit { true_exit } else { continue 'next_label; }; // We cannot optimize this branch if `exit` can be reached from // somewhere else then `on_true` or `on_false`. if flow_incoming[&exit].len() != 2 { continue 'next_label; } // Skip loops. if exit == label || exit == on_true || exit == on_false { continue 'next_label; } // We have now detected following pattern in the CFG: // // A // / \ // B C // \ / // D // // Where A is `label`, B is `on_true`, C is `on_false` and D is `exit`. // If B and C don't contain non-reorderable instructions we can optimize // the branch out. // Try to copy everything from `on_true` and `on_false` to `exit`. if !move_instructions(function, COPY_TRESHOLD, &[on_true, on_false], exit) { continue 'next_label; } // Make `label` enter `exit` directly. This will unlink `on_true` and // `on_false` from the CFG. make_unconditional_branch(function, label, exit); // Rewrite all PHIs in `exit` to `select`s. rewrite_phis_to_selects(function, cond, exit, on_true, on_false); did_something = true; // As we have altered CFG we cannot continue this loop so // we go directly to the main loop. continue 'main_loop; } } // We haven't done anything this iteration so don't continue trying. break; } did_something } }