text stringlengths 8 4.13M |
|---|
#![cfg_attr(feature="clippy", feature(plugin))]
#![cfg_attr(feature="clippy", plugin(clippy))]
extern crate glium;
extern crate glium_text;
extern crate cgmath;
#[macro_use]
extern crate clap;
use std::io::Read;
use std::fs::File;
use std::time::Duration;
use std::thread;
use clap::{Arg, App};
use glium::{DisplayBuild, Surface};
use glium::glutin;
fn main() {
let matches = App::new("Helium")
.version(crate_version!())
.author(crate_authors!())
.about("The awesomest of editors.")
.arg(Arg::with_name("file")
.help("Input file")
.index(1))
.get_matches();
let mut string = String::new();
if let Some(file) = matches.value_of("file") {
println!("Reading file: {}", file);
File::open(file)
.expect("Failed to open file")
.read_to_string(&mut string)
.expect("Failed to read file.");
}
let display = glutin::WindowBuilder::new()
.with_vsync()
.with_dimensions(800, 600)
.with_title("Helium")
.build_glium()
.unwrap();
let system = glium_text::TextSystem::new(&display);
let font = glium_text::FontTexture::new(&display, &include_bytes!("../DejaVuSansMono.ttf")[..], 70).unwrap();
let mut buffer = String::new();
let sleep_duration = Duration::from_millis(17);
// let mut text: String = "A japanese poem:\r
// \r
// 色は匂へど散りぬるを我が世誰ぞ常ならむ有為の奥山今日越えて浅き夢見じ酔ひもせず\r
// \r
// Feel free to type out some text, and delete it with Backspace. You can also try resizing this window."
// .into();
'main: loop {
let text = glium_text::TextDisplay::new(&system, &font, &buffer);
let (w, h) = display.get_framebuffer_dimensions();
let matrix: [[f32; 4]; 4] = cgmath::Matrix4::new(0.1,
0.0,
0.0,
0.0,
0.0,
0.1 * (w as f32) / (h as f32),
0.0,
0.0,
0.0,
0.0,
1.0,
0.0,
-0.9,
0.0,
0.0,
1.0f32)
.into();
let mut target = display.draw();
target.clear_color(0.0, 0.0, 0.0, 1.0);
glium_text::draw(&text, &system, &mut target, matrix, (1.0, 1.0, 0.0, 1.0));
target.finish().unwrap();
thread::sleep(sleep_duration);
for event in display.poll_events() {
match event {
glutin::Event::KeyboardInput(_, _, Some(glutin::VirtualKeyCode::Escape)) |
glutin::Event::Closed => break 'main,
glutin::Event::ReceivedCharacter(c) => {
if c != '\u{7f}' && c != '\u{8}' {
buffer.push(c);
}
}
glutin::Event::KeyboardInput(glutin::ElementState::Pressed, _, Some(glutin::VirtualKeyCode::Back)) => {
buffer.pop();
}
_ => {}
}
}
}
}
|
use crate::budget::data::{Budget, BudgetEntry, NewBudgetEntry};
use crate::datastruct::SqlResult;
use chrono::Utc;
use rusqlite::{params, Result};
use std::ops::DerefMut;
pub fn get_budget(
conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
id: i32,
) -> Result<Budget> {
let mut stmt = conn.prepare("SELECT id, name, open, close FROM Budgets WHERE id = ?1")?;
stmt.query_row(params![id], |row| {
Ok(Budget::new(
row.get(0).unwrap(),
&row.get(1).unwrap(),
row.get(2).unwrap(),
row.get(3).unwrap(),
))
})
}
pub fn remove_budget(
mut conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
id: i32,
) -> Result<()> {
let con = conn.deref_mut();
let tx = con.transaction()?;
tx.execute("DELETE FROM Budgets WHERE id = ?1", params![id])?;
tx.commit()
}
pub fn create_budget(
mut conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
budget: &Budget,
) -> Result<i64> {
let con = conn.deref_mut();
let tx = con.transaction()?;
tx.execute(
"INSERT INTO Budgets (name, open, close) VALUES (?1, ?2, ?3)",
params![budget.name, budget.open, budget.close],
)?;
let budget_id = tx.last_insert_rowid();
let transaction_result = tx.commit();
match transaction_result {
Ok(_) => Ok(budget_id),
Err(_) => panic!("Budget creation has failed"),
}
}
pub fn get_budget_by_date(
conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
start: chrono::DateTime<Utc>,
end: chrono::DateTime<Utc>,
) -> Result<Budget> {
let mut stmt = conn.prepare("SELECT * from Budgets WHERE open >= ?1 AND close < ?2;")?;
stmt.query_row(params![start, end], |row| {
Ok(Budget::new(
row.get(0).unwrap(),
&row.get(1).unwrap(),
row.get(2).unwrap(),
row.get(3).unwrap(),
))
})
}
pub fn check_if_budget_exists(
conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
start: chrono::DateTime<Utc>,
end: chrono::DateTime<Utc>,
) -> Result<bool> {
let mut stmt =
conn.prepare("SELECT EXISTS(SELECT * from Budgets WHERE open >= ?1 AND close < ?2);")?;
let result = stmt
.query_row(params![start, end], |row| {
Ok(SqlResult {
value: row.get(0).unwrap(),
})
})
.unwrap();
if result.value == 0 {
return Ok(false);
} else {
Ok(true)
}
}
pub fn add_budget_entry(
mut conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
budget_id: i32,
entry: NewBudgetEntry,
) -> Result<()> {
let con = conn.deref_mut();
let tx = con.transaction()?;
tx.execute(
"INSERT INTO BudgetEntries (account, budget, balance) VALUES (?1, ?2, ?3)",
params![entry.account, budget_id, entry.balance],
)?;
tx.commit()
}
pub fn update_budget_entry(
mut conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
budget_id: i32,
entry: NewBudgetEntry,
) -> Result<()> {
let con = conn.deref_mut();
let tx = con.transaction()?;
tx.execute(
"UPDATE BudgetEntries SET balance = ?1 WHERE account = ?2 AND budget = ?3",
params![entry.balance, entry.account, budget_id],
)?;
tx.commit()
}
pub fn delete_budget_entry(
mut conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
budget_id: i32,
entry: NewBudgetEntry,
) -> Result<()> {
let con = conn.deref_mut();
let tx = con.transaction()?;
tx.execute(
"DELETE FROM BudgetEntries WHERE account = ?1 AND budget = ?2",
params![entry.account, budget_id],
)?;
tx.commit()
}
pub fn list_budget_entries(
conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
budget: i32,
) -> Result<Vec<BudgetEntry>> {
let mut stmt =
conn.prepare("SELECT id, account, budget, balance FROM BudgetEntries WHERE budget = ?1;")?;
let result = stmt
.query_map(params![budget], |row| {
Ok(BudgetEntry {
id: row.get(0).unwrap(),
account: row.get(1).unwrap(),
budget: row.get(2).unwrap(),
balance: row.get(3).unwrap(),
})
})
.and_then(|mapped_rows| {
Ok(mapped_rows
.map(|row| row.unwrap())
.collect::<Vec<BudgetEntry>>())
})?;
Ok(result)
}
pub fn generate_budget(
mut conn: r2d2::PooledConnection<r2d2_sqlite::SqliteConnectionManager>,
budget: &Budget,
) -> Result<i64> {
let con = conn.deref_mut();
let tx = con.transaction()?;
tx.execute(
"INSERT INTO Budgets (name, open, close) VALUES (?1, ?2, ?3)",
params![budget.name, budget.open, budget.close],
)?;
let budget_id = tx.last_insert_rowid();
tx.execute(
"INSERT INTO BudgetEntries (account, budget, balance)
SELECT id, ?1, 0 FROM Accounts WHERE Accounts.type = 4;",
params![budget_id],
)?;
let transaction_result = tx.commit();
match transaction_result {
Ok(_) => Ok(budget_id),
Err(_) => panic!("Budget creation has failed"),
}
}
|
use alloc::sync::Arc;
use rcore_fs::vfs::FileSystem;
use linux_object::fs::MemBuf;
use kernel_hal_bare::drivers::virtio::{BlockDriverWrapper, BLK_DRIVERS};
pub fn init_filesystem(ramfs_data: &'static mut [u8]) -> Arc<dyn FileSystem> {
#[cfg(target_arch = "x86_64")]
let device = Arc::new(MemBuf::new(ramfs_data));
#[cfg(feature = "link_user_img")]
let ramfs_data = unsafe {
extern {
fn _user_img_start();
fn _user_img_end();
}
core::slice::from_raw_parts_mut(
_user_img_start as *mut u8,
_user_img_end as usize - _user_img_start as usize,
)
};
#[cfg(feature = "link_user_img")]
let device = Arc::new(MemBuf::new(ramfs_data));
#[cfg(all(target_arch="riscv64", not(feature="link_user_img")))]
let device = {
let driver = BlockDriverWrapper(
BLK_DRIVERS
.read()
.iter()
.next()
.expect("Block device not found")
.clone(),
);
Arc::new(rcore_fs::dev::block_cache::BlockCache::new(driver, 0x100))
};
info!("Opening the rootfs ...");
// 输入类型: Arc<Device>
let rootfs =
rcore_fs_sfs::SimpleFileSystem::open(device).expect("failed to open device SimpleFS");
rootfs
}
// Hard link rootfs img
#[cfg(feature = "link_user_img")]
global_asm!(concat!(
r#"
.section .data.img
.global _user_img_start
.global _user_img_end
_user_img_start:
.incbin ""#,
env!("USER_IMG"),
r#""
_user_img_end:
"#
));
|
fn main() {
let stdin = std::io::stdin();
let mut rd = ProconReader::new(stdin.lock());
let h: usize = rd.get();
let w: usize = rd.get();
let a: Vec<Vec<char>> = (0..h)
.map(|_| {
let r: String = rd.get();
r.chars().collect::<Vec<char>>()
})
.collect();
let dy = vec![-1, 0, 0, 1];
let dx = vec![0, -1, 1, 0];
let mut ans = 0;
for y in 0..h {
for x in 0..w {
if a[y][x] == '#' {
continue;
}
for k in 0..4 {
let yy = y as i32 + dy[k];
let xx = x as i32 + dx[k];
if yy < 0 || yy >= h as i32 || xx < 0 || xx >= w as i32 {
continue;
}
let yy = yy as usize;
let xx = xx as usize;
if a[yy][xx] == '.' {
ans += 1;
}
}
}
}
println!("{}", ans / 2);
}
pub struct ProconReader<R: std::io::Read> {
reader: R,
}
impl<R: std::io::Read> ProconReader<R> {
pub fn new(reader: R) -> Self {
Self { reader }
}
pub fn get<T: std::str::FromStr>(&mut self) -> T {
use std::io::Read;
let buf = self
.reader
.by_ref()
.bytes()
.map(|b| b.unwrap())
.skip_while(|&byte| byte == b' ' || byte == b'\n' || byte == b'\r')
.take_while(|&byte| byte != b' ' && byte != b'\n' && byte != b'\r')
.collect::<Vec<_>>();
std::str::from_utf8(&buf)
.unwrap()
.parse()
.ok()
.expect("Parse Error.")
}
}
|
use std::{convert::TryFrom, ffi::OsString, os::windows::prelude::OsStringExt};
use win32_error::Win32Error;
use winapi::shared::minwindef::FALSE;
use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
use winapi::um::tlhelp32::{
CreateToolhelp32Snapshot, Process32FirstW, Process32NextW,
PROCESSENTRY32W, TH32CS_SNAPPROCESS,
};
use winapi::um::winbase::lstrlenW;
use winapi::um::winnt::HANDLE;
use crate::{Error, Result};
use super::Pid;
pub struct ProcessEnumerator {
toolhelp32: HANDLE,
is_first: bool,
}
pub struct ProcessRecord {
inner: PROCESSENTRY32W,
}
impl ProcessEnumerator {
pub fn new() -> Result<ProcessEnumerator> {
let toolhelp32 = unsafe { CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0) };
if toolhelp32 != INVALID_HANDLE_VALUE {
Ok(ProcessEnumerator {
toolhelp32,
is_first: true,
})
} else {
Err(Error::Toolhelp32Error(Win32Error::new()))
}
}
}
impl Iterator for ProcessEnumerator {
type Item = Result<ProcessRecord>;
fn next(&mut self) -> Option<Self::Item> {
let mut entry: PROCESSENTRY32W = unsafe { std::mem::MaybeUninit::uninit().assume_init() };
entry.dwSize = std::mem::size_of::<PROCESSENTRY32W>() as u32;
let result = if self.is_first {
unsafe { Process32FirstW(self.toolhelp32, &mut entry) }
} else {
unsafe { Process32NextW(self.toolhelp32, &mut entry) }
};
self.is_first = false;
if result != FALSE {
Some(Ok(ProcessRecord { inner: entry }))
} else {
None
}
}
}
impl Drop for ProcessEnumerator {
fn drop(&mut self) {
unsafe {
CloseHandle(self.toolhelp32);
// the return value is silently ignored
}
}
}
impl ProcessRecord {
pub fn pid(&self) -> Pid {
Pid(self.inner.th32ProcessID)
}
pub fn executable(&self) -> String {
let wstr_ptr = self.inner.szExeFile.as_ptr();
let num_chars = unsafe { lstrlenW(wstr_ptr) };
let num_chars = usize::try_from(num_chars).expect("invalid number returned by lstrlenW");
OsString::from_wide(unsafe { std::slice::from_raw_parts(wstr_ptr, num_chars) })
.into_string()
.expect("the executable name contains invalid Unicode characters")
}
}
|
extern crate permutohedron;
extern crate pcre;
use std::fs::File;
use std::io::BufReader;
use std::io::BufRead;
use std::collections::{HashMap, HashSet};
use std::cmp::{min, max};
use permutohedron::Heap;
use pcre::Pcre;
fn main() {
let f = File::open("day9.in").unwrap();
let file = BufReader::new(&f);
let mut distances : HashMap<(String,String), i32> = HashMap::new();
let mut cities: HashSet<String> = HashSet::new();
let mut re = Pcre::compile(r"(\w+) to (\w+) = (\d+)").unwrap();
for line in file.lines() {
let line = line.unwrap();
let m = re.exec(&line).unwrap();
let c1 = m.group(1).to_string();
let c2 = m.group(2).to_string();
let d = m.group(3).parse().unwrap();
distances.insert((c1.clone(), c2.clone()), d);
distances.insert((c2.clone(), c1.clone()), d);
cities.insert(c1);
cities.insert(c2);
}
let mut min_dist = 1000000;
let mut max_dist = 0;
let mut cities_vec: Vec<String> = cities.into_iter().collect();
for p in Heap::new(&mut cities_vec) {
let mut dist = 0;
for (a,b) in p.iter().zip(p[1..p.len()].iter()) {
dist += distances[&(a.to_string(),b.to_string())];
}
min_dist = min(min_dist, dist);
max_dist = max(max_dist, dist);
}
println!("{}", min_dist);
println!("{}", max_dist);
}
|
#[cfg(feature = "rustpython-ast")]
pub(crate) mod ast;
pub mod atexit;
pub mod builtins;
mod codecs;
mod collections;
pub mod errno;
mod functools;
mod imp;
pub mod io;
mod itertools;
mod marshal;
mod operator;
// TODO: maybe make this an extension module, if we ever get those
// mod re;
mod sre;
mod string;
#[cfg(feature = "rustpython-compiler")]
mod symtable;
mod sysconfigdata;
#[cfg(feature = "threading")]
pub mod thread;
pub mod time;
pub mod warnings;
mod weakref;
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
#[macro_use]
pub mod os;
#[cfg(windows)]
pub mod nt;
#[cfg(unix)]
pub mod posix;
#[cfg(any(not(target_arch = "wasm32"), target_os = "wasi"))]
#[cfg(not(any(unix, windows)))]
#[path = "posix_compat.rs"]
pub mod posix;
#[cfg(windows)]
pub(crate) mod msvcrt;
#[cfg(all(unix, not(any(target_os = "android", target_os = "redox"))))]
mod pwd;
#[cfg(not(target_arch = "wasm32"))]
pub(crate) mod signal;
pub mod sys;
#[cfg(windows)]
mod winapi;
#[cfg(windows)]
mod winreg;
use crate::{builtins::PyModule, PyRef, VirtualMachine};
use std::{borrow::Cow, collections::HashMap};
pub type StdlibInitFunc = Box<py_dyn_fn!(dyn Fn(&VirtualMachine) -> PyRef<PyModule>)>;
pub type StdlibMap = HashMap<Cow<'static, str>, StdlibInitFunc, ahash::RandomState>;
pub fn get_module_inits() -> StdlibMap {
macro_rules! modules {
{
$(
#[cfg($cfg:meta)]
{ $( $key:expr => $val:expr),* $(,)? }
)*
} => {{
let modules = [
$(
$(#[cfg($cfg)] (Cow::<'static, str>::from($key), Box::new($val) as StdlibInitFunc),)*
)*
];
modules.into_iter().collect()
}};
}
modules! {
#[cfg(all())]
{
"atexit" => atexit::make_module,
"_codecs" => codecs::make_module,
"_collections" => collections::make_module,
"errno" => errno::make_module,
"_functools" => functools::make_module,
"itertools" => itertools::make_module,
"_io" => io::make_module,
"marshal" => marshal::make_module,
"_operator" => operator::make_module,
"_sre" => sre::make_module,
"_string" => string::make_module,
"time" => time::make_module,
"_weakref" => weakref::make_module,
"_imp" => imp::make_module,
"_warnings" => warnings::make_module,
sys::sysconfigdata_name() => sysconfigdata::make_module,
}
// parser related modules:
#[cfg(feature = "rustpython-ast")]
{
"_ast" => ast::make_module,
}
// compiler related modules:
#[cfg(feature = "rustpython-compiler")]
{
"symtable" => symtable::make_module,
}
#[cfg(any(unix, target_os = "wasi"))]
{
"posix" => posix::make_module,
// "fcntl" => fcntl::make_module,
}
// disable some modules on WASM
#[cfg(not(target_arch = "wasm32"))]
{
"_signal" => signal::make_module,
}
#[cfg(feature = "threading")]
{
"_thread" => thread::make_module,
}
// Unix-only
#[cfg(all(unix, not(any(target_os = "android", target_os = "redox"))))]
{
"pwd" => pwd::make_module,
}
// Windows-only
#[cfg(windows)]
{
"nt" => nt::make_module,
"msvcrt" => msvcrt::make_module,
"_winapi" => winapi::make_module,
"winreg" => winreg::make_module,
}
}
}
|
use std::fmt;
use std::fs::{self, File};
use std::io::{BufReader, Read, Write};
use std::path::Path;
use std::str::FromStr;
use chrono::prelude::*;
use glob::glob;
use serde::{Deserialize, Serialize};
use slog::Logger;
use zip::write::FileOptions;
use zip::{ZipArchive, ZipWriter};
use crate::connection::Connection;
use crate::errors::PsqlpackErrorKind::*;
use crate::errors::{PsqlpackResult, PsqlpackResultExt};
use crate::model::{Capabilities, DefinableCatalog, Dependency, Project};
use crate::semver::Semver;
use crate::sql::ast::*;
macro_rules! ztry {
($expr:expr) => {{
match $expr {
Ok(_) => {}
Err(e) => bail!(GenerationError(format!("Failed to write package: {}", e))),
}
}};
}
macro_rules! zip_collection {
($zip:ident, $package:ident, $collection:ident) => {{
let collection_name = stringify!($collection);
ztry!($zip.add_directory(format!("{}/", collection_name), FileOptions::default()));
for item in &$package.$collection {
ztry!($zip.start_file(
format!("{}/{}.json", collection_name, item.name),
FileOptions::default()
));
let json = match serde_json::to_string_pretty(&item) {
Ok(j) => j,
Err(e) => bail!(GenerationError(format!("Failed to write package: {}", e))),
};
ztry!($zip.write_all(json.as_bytes()));
}
}};
}
// Search paths for extensions
const DEFAULT_SEARCH_PATHS: [&str; 2] = ["./lib", "~/.psqlpack/lib"];
#[derive(Debug)]
pub struct Package {
pub meta: MetaInfo,
pub extensions: Vec<Dependency>,
pub functions: Vec<FunctionDefinition>,
pub indexes: Vec<IndexDefinition>,
pub schemas: Vec<SchemaDefinition>,
pub scripts: Vec<ScriptDefinition>,
pub tables: Vec<TableDefinition>,
pub types: Vec<TypeDefinition>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct MetaInfo {
version: Semver,
generated_at: DateTime<Utc>,
source: SourceInfo,
publishable: bool,
}
impl MetaInfo {
pub fn new(source: SourceInfo) -> Self {
let publishable = !matches!(source, SourceInfo::Extension(..));
MetaInfo {
version: crate_version(),
generated_at: Utc::now(),
source,
publishable,
}
}
}
fn crate_version() -> Semver {
Semver::from_str(&format!(
"{}.{}.{}",
env!("CARGO_PKG_VERSION_MAJOR"),
env!("CARGO_PKG_VERSION_MINOR"),
env!("CARGO_PKG_VERSION_PATCH")
))
.unwrap()
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum SourceInfo {
Database,
Extension(String),
Project,
}
impl fmt::Display for SourceInfo {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
SourceInfo::Database => write!(f, "database"),
SourceInfo::Extension(ref name) => write!(f, "extension {}", name),
SourceInfo::Project => write!(f, "project"),
}
}
}
impl Package {
fn maybe_packaged_file(source_path: &Path) -> PsqlpackResult<bool> {
File::open(&source_path)
.chain_err(|| IOError(source_path.to_str().unwrap().into(), "Failed to open file".into()))
.and_then(|file| {
let mut reader = BufReader::with_capacity(4, file);
let mut buffer = [0; 2];
let b = reader.read(&mut buffer[..]).map_err(|e| {
IOError(
source_path.to_str().unwrap().into(),
format!("Failed to read file: {}", e),
)
})?;
if b != 2 {
bail!(IOError(
source_path.to_str().unwrap().into(),
"Invalid file provide (< 4 bytes)".into()
));
}
Ok(buffer[0] == 0x50 && buffer[1] == 0x4B)
})
}
pub fn from_path(log: &Logger, source_path: &Path) -> PsqlpackResult<Package> {
let log = log.new(o!("package" => "from_path"));
// source_path could be either a project file or a psqlpack file
// Try and guess which type it is first
if Self::maybe_packaged_file(source_path)? {
Self::from_packaged_file(&log, source_path)
} else {
// We'll optimistically load it as a project
let project = Project::from_project_file(&log, source_path)?;
project.build_package(&log)
}
}
pub fn from_packaged_file(log: &Logger, source_path: &Path) -> PsqlpackResult<Package> {
let _log = log.new(o!("package" => "from_packaged_file"));
let mut archive = File::open(&source_path)
.chain_err(|| PackageReadError(source_path.to_path_buf()))
.and_then(|file| ZipArchive::new(file).chain_err(|| PackageUnarchiveError(source_path.to_path_buf())))?;
let mut meta: Option<MetaInfo> = None;
let mut extensions = Vec::new();
let mut functions = Vec::new();
let mut indexes = Vec::new();
let mut schemas = Vec::new();
let mut scripts = Vec::new();
let mut tables = Vec::new();
let mut types = Vec::new();
for i in 0..archive.len() {
let file = archive.by_index(i).unwrap();
if file.size() == 0 {
continue;
}
let name = file.name().to_owned();
if name.starts_with("meta") {
if meta.is_some() {
bail!(PackageReadError(source_path.to_path_buf()));
}
let m = serde_json::from_reader(file).chain_err(|| PackageInternalReadError(name))?;
meta = Some(m);
} else if name.starts_with("extensions/") {
extensions.push(serde_json::from_reader(file).chain_err(|| PackageInternalReadError(name))?);
} else if name.starts_with("functions/") {
functions.push(serde_json::from_reader(file).chain_err(|| PackageInternalReadError(name))?);
} else if name.starts_with("indexes") {
indexes.push(serde_json::from_reader(file).chain_err(|| PackageInternalReadError(name))?);
} else if name.starts_with("schemas/") {
schemas.push(serde_json::from_reader(file).chain_err(|| PackageInternalReadError(name))?);
} else if name.starts_with("scripts/") {
scripts.push(serde_json::from_reader(file).chain_err(|| PackageInternalReadError(name))?);
} else if name.starts_with("tables/") {
tables.push(serde_json::from_reader(file).chain_err(|| PackageInternalReadError(name))?);
} else if name.starts_with("types/") {
types.push(serde_json::from_reader(file).chain_err(|| PackageInternalReadError(name))?);
}
}
let mut package = Package {
meta: match meta {
Some(m) => m,
// Temporary - this will be an error in the future
// For now, it assumes a standard project
None => MetaInfo::new(SourceInfo::Project),
},
extensions,
functions,
indexes,
schemas,
scripts,
tables,
types,
};
package.promote_primary_keys_to_table_constraints();
Ok(package)
}
pub fn from_connection(
log: &Logger,
connection: &Connection,
capabilities: &Capabilities,
) -> PsqlpackResult<Option<Package>> {
let log = log.new(o!("package" => "from_connection"));
trace!(log, "Checking for database `{}`", connection.database());
if !capabilities.database_exists {
return Ok(None);
}
// We do a few SQL queries to get the package details
trace!(log, "Connecting to database");
let mut client = connection.connect_database()?;
let extensions = capabilities
.extensions
.iter()
.filter(|e| e.installed)
.map(|e| Dependency {
name: e.name.clone(),
version: Some(e.version),
})
.collect::<Vec<_>>();
// TODO: Refactor connection so we only need to pass through that
let schemas = capabilities.schemata(&mut client, connection.database())?;
let types = capabilities.types(&mut client)?;
let functions = capabilities.functions(&mut client)?;
let tables = capabilities.tables(&mut client)?;
let indexes = capabilities.indexes(&mut client)?;
let mut package = Package {
meta: MetaInfo::new(SourceInfo::Database),
extensions,
functions,
indexes,
schemas,
scripts: Vec::new(), // Scripts can't be known from a connection
tables,
types,
};
package.promote_primary_keys_to_table_constraints();
Ok(Some(package))
}
pub fn write_to(&self, destination: &Path) -> PsqlpackResult<()> {
if let Some(parent) = destination.parent() {
match fs::create_dir_all(parent) {
Ok(_) => {}
Err(e) => bail!(GenerationError(format!("Failed to create package directory: {}", e))),
}
}
File::create(&destination)
.chain_err(|| GenerationError("Failed to write package".to_owned()))
.and_then(|output_file| {
let mut zip = ZipWriter::new(output_file);
ztry!(zip.start_file("meta.json", FileOptions::default()));
let json = match serde_json::to_string_pretty(&self.meta) {
Ok(j) => j,
Err(e) => bail!(GenerationError(format!("Failed to write package: {}", e))),
};
ztry!(zip.write_all(json.as_bytes()));
zip_collection!(zip, self, extensions);
zip_collection!(zip, self, functions);
zip_collection!(zip, self, indexes);
zip_collection!(zip, self, schemas);
zip_collection!(zip, self, scripts);
zip_collection!(zip, self, tables);
zip_collection!(zip, self, types);
ztry!(zip.finish());
Ok(())
})
}
pub fn new() -> Self {
Package {
// By default, our source is a project file
meta: MetaInfo::new(SourceInfo::Project),
extensions: Vec::new(),
functions: Vec::new(),
indexes: Vec::new(),
schemas: Vec::new(),
scripts: Vec::new(),
tables: Vec::new(),
types: Vec::new(),
}
}
pub fn push_extension(&mut self, extension: Dependency) {
self.extensions.push(extension);
}
pub fn push_function(&mut self, function: FunctionDefinition) {
self.functions.push(function);
}
pub fn push_index(&mut self, index: IndexDefinition) {
self.indexes.push(index);
}
pub fn push_script(&mut self, script: ScriptDefinition) {
self.scripts.push(script);
}
pub fn push_schema(&mut self, schema: SchemaDefinition) {
self.schemas.push(schema);
}
pub fn push_table(&mut self, table: TableDefinition) {
self.tables.push(table);
}
pub fn push_type(&mut self, def: TypeDefinition) {
self.types.push(def);
}
pub fn set_defaults(&mut self, project: &Project) {
// Make sure the public schema exists
let mut has_public = false;
for schema in &mut self.schemas {
if project.default_schema.eq_ignore_ascii_case(&schema.name[..]) {
has_public = true;
break;
}
}
if !has_public {
self.schemas.push(SchemaDefinition {
name: project.default_schema.to_owned(),
});
}
for typ in &mut self.types {
if typ.name.schema.is_none() {
typ.name.schema = Some(project.default_schema.clone());
}
}
fn ensure_not_null_column(column: &mut ColumnDefinition) {
// Remove null for primary keys
let pos = column.constraints.iter().position(|c| c.eq(&ColumnConstraint::Null));
if let Some(pos) = pos {
column.constraints.remove(pos);
}
// Add not null for primary keys
let pos = column.constraints.iter().position(|c| c.eq(&ColumnConstraint::NotNull));
if pos.is_none() {
column.constraints.push(ColumnConstraint::NotNull);
}
}
// Set default schema's as well as marking primary key columns as not null
for table in &mut self.tables {
if table.name.schema.is_none() {
table.name.schema = Some(project.default_schema.clone());
}
for constraint in table.constraints.iter_mut() {
match *constraint {
TableConstraint::Primary { ref columns, .. } => {
for column in columns {
let item = table.columns.iter_mut().find(|item| item.name.eq(column));
if let Some(item) = item {
ensure_not_null_column(item);
}
}
}
TableConstraint::Foreign { ref mut ref_table, .. } => {
if ref_table.schema.is_none() {
ref_table.schema = Some(project.default_schema.clone());
}
}
}
}
// Primary keys may also be specified against the column directly. We promote these to table constraints.`
for column in table.columns.iter_mut() {
let pk = column
.constraints
.iter()
.position(|c| c.eq(&ColumnConstraint::PrimaryKey));
if pk.is_some() {
// Make sure it is not null
ensure_not_null_column(column);
}
// Also, if the type is custom, then assume the default search path
if let SqlType::Custom(ref mut custom_type, ref _opts, _dim) = column.sql_type {
if custom_type.schema.is_none() {
custom_type.schema = Some(project.default_schema.clone());
}
}
}
}
// Set missing schema's and default values in indexes
for index in &mut self.indexes {
// Set default schema
if index.table.schema.is_none() {
index.table.schema = Some(project.default_schema.clone());
}
// Set default storage type
if index.index_type.is_none() {
index.index_type = Some(IndexType::BTree);
}
// Set default column sorts
for col in &mut index.columns {
if col.order.is_none() {
col.order = Some(IndexOrder::Ascending);
}
if col.null_position.is_none() {
if let Some(ref order) = col.order {
col.null_position = Some(match order {
IndexOrder::Ascending => IndexPosition::Last,
IndexOrder::Descending => IndexPosition::First,
});
}
}
}
}
// We also do the promotion here
self.promote_primary_keys_to_table_constraints();
}
pub fn promote_primary_keys_to_table_constraints(&mut self) {
// Set default schema's as well as marking primary key columns as not null
for table in &mut self.tables {
// Primary keys may also be specified against the column directly. We promote these to table constraints.`
for column in table.columns.iter_mut() {
let pk_pos = column
.constraints
.iter()
.position(|c| c.eq(&ColumnConstraint::PrimaryKey));
if let Some(pk_pos) = pk_pos {
// Remove the PK constraint
column.constraints.remove(pk_pos);
// Add a table constraint if it doesn't exist
let found = table
.constraints
.iter()
.position(|c| matches!(c, TableConstraint::Primary { .. }));
if found.is_none() {
let name = format!("{}_pkey", table.name.name);
table.constraints.push(TableConstraint::Primary {
name,
columns: vec![column.name.to_owned()],
parameters: None,
});
}
}
}
}
}
pub fn generate_dependency_graph(&self, log: &Logger) -> PsqlpackResult<Vec<Node>> {
let log = log.new(o!("graph" => "generate"));
let mut graph = Graph::new();
// Go through and add each object and add it to the graph
// Schemas and types are always implied
trace!(log, "Scanning table dependencies");
for table in &self.tables {
let log = log.new(o!("table" => table.name.to_string()));
table.graph(&log, &mut graph, None);
}
trace!(log, "Scanning table constraints");
for table in &self.tables {
let log = log.new(o!("table" => table.name.to_string()));
let table_node = Node::Table(table);
trace!(log, "Scanning constraints");
for constraint in &table.constraints {
constraint.graph(&log, &mut graph, Some(&table_node));
}
}
trace!(log, "Scanning function dependencies");
for function in &self.functions {
let log = log.new(o!("function" => function.name.to_string()));
function.graph(&log, &mut graph, None);
}
// Then generate the order
trace!(log, "Sorting graph");
match petgraph::algo::toposort(&graph, None) {
Err(_) => bail!(GenerationError("Circular reference detected".to_owned())),
Ok(index_order) => {
let log = log.new(o!("order" => "sorted"));
for node in &index_order {
trace!(log, ""; "node" => node.to_string());
}
Ok(index_order)
}
}
}
// TODO: Stop moving string, consider making this a utility
fn expand_tilde(input: &str) -> String {
if let Some(after_tilde) = input.strip_prefix('~') {
if after_tilde.is_empty() || after_tilde.starts_with('/') {
if let Some(hd) = dirs::home_dir() {
format!("{}{}", hd.display(), after_tilde)
} else {
input.into()
}
} else {
input.into()
}
} else {
input.into()
}
}
pub fn load_references(&self, project: &Project, log: &Logger) -> Vec<Package> {
let log = log.new(o!("package" => "load_references"));
let mut references = Vec::new();
// Get the search paths to look for. We favor project level paths first if they exist.
trace!(log, "Setting up search paths");
let mut search_paths = Vec::new();
if let Some(ref user_search_paths) = project.reference_search_paths {
for path in user_search_paths {
if let Ok(p) = Path::new(&Self::expand_tilde(path)).canonicalize() {
search_paths.push(p);
} else {
warn!(log, "Path not found: {}", path);
}
}
}
for path in &DEFAULT_SEARCH_PATHS {
if let Ok(p) = Path::new(&Self::expand_tilde(path)).canonicalize() {
search_paths.push(p);
} else {
warn!(log, "Path not found: {}", path);
}
}
// Firstly, load extensions
trace!(log, "Loading extensions");
for extension in &self.extensions {
let mut found = false;
for path in &search_paths {
if let Some(version) = extension.version {
// If the extension specifies a version we search for name-version.psqlpack.
let mut path = path.to_path_buf();
path.push(format!("{}-{}.psqlpack", extension.name, version));
if path.exists() && path.is_file() {
match Package::from_packaged_file(&log, &path) {
Ok(package) => {
references.push(package);
found = true;
break;
}
Err(e) => {
error!(log, "Failed to load extension: {}", e);
break;
}
}
}
} else {
// If no version is specified then we search for either the non-versioned extension
// or the highest versioned extension.
// Try to find the globs matching ext_name*.psqlpack
let mut search_path = path.to_path_buf();
search_path.push(format!("{}*.psqlpack", extension.name));
let search_path = search_path.to_str().unwrap();
let mut found_packages = Vec::new();
for glob_path in glob(search_path).unwrap() {
if let Ok(path) = glob_path {
if path.is_file() {
match Package::from_packaged_file(&log, &path) {
Ok(package) => {
trace!(log, "Found {} {}", package.meta.source, package.meta.version);
found_packages.push(package);
}
Err(e) => {
error!(log, "Failed to load extension: {}", e);
}
}
}
} else {
error!(log, "Glob result had an error: {}", glob_path.err().unwrap().error());
}
}
if found_packages.is_empty() {
trace!(log, "No packages matched: {}", search_path);
break;
} else if found_packages.len() > 1 {
trace!(log, "Search for highest version");
found_packages.sort_by(|a, b| a.meta.version.cmp(&b.meta.version));
references.extend(found_packages.drain(..1));
break;
} else {
// Only one item in there so just drain and extend
references.extend(found_packages.drain(..));
found = true;
break;
}
}
}
if !found {
warn!(log, "Extension not found: {}", extension);
}
}
// TODO: load passed references
references
}
pub fn validate(&self, references: &[Package]) -> PsqlpackResult<()> {
// 1. Validate schema existence
let schemata = self.schemas.iter().map(|schema| &schema.name[..]).collect::<Vec<_>>();
let names = self
.tables
.iter()
.map(|t| &t.name)
.chain(self.functions.iter().map(|f| &f.name))
.collect::<Vec<_>>();
let mut errors = names
.iter()
.filter(|o| {
if let Some(ref s) = o.schema {
!schemata.contains(&&s[..])
} else {
false
}
})
.map(|o| ValidationKind::SchemaMissing {
schema: o.schema.clone().unwrap(),
object: o.name.to_owned(),
})
.collect::<Vec<_>>();
// 2. Validate custom type are known
let mut custom_types = self.types.iter().map(|ty| &ty.name).collect::<Vec<_>>();
for reference in references {
for ty in &reference.types {
custom_types.push(&ty.name);
}
}
errors.extend(self.tables.iter().flat_map(|t| {
t.columns
.iter()
.filter_map(|c| match c.sql_type {
SqlType::Custom(ref name, ref _opts, _dim) => {
if !custom_types.contains(&&name) {
Some(ValidationKind::UnknownType {
ty: name.to_owned(),
table: t.name.to_string(),
})
} else {
None
}
}
_ => None,
})
.collect::<Vec<_>>()
}));
// 3. Validate constraints map to known tables
let foreign_keys = self
.tables
.iter()
.flat_map(|t| t.constraints.clone())
.filter_map(|c| match c {
TableConstraint::Foreign {
name,
columns,
ref_table,
ref_columns,
..
} => Some((name, columns, ref_table, ref_columns)),
_ => None,
})
.collect::<Vec<_>>();
// Four types here:
// i. Reference table doesn't exist
errors.extend(
foreign_keys
.iter()
.filter(|&&(_, _, ref table, _)| !self.tables.iter().any(|t| t.name.eq(table)))
.map(
|&(ref name, _, ref table, _)| ValidationKind::TableConstraintInvalidReferenceTable {
constraint: name.to_owned(),
table: table.to_string(),
},
),
);
// ii. Reference table exists, but the reference column doesn't.
errors.extend(
foreign_keys
.iter()
.filter(|&&(_, _, ref table, ref columns)| {
let table = self.tables.iter().find(|t| t.name.eq(table));
match table {
Some(t) => !columns.iter().all(|rc| t.columns.iter().any(|c| c.name.eq(rc))),
None => false,
}
})
.map(
|&(ref name, _, ref table, ref columns)| ValidationKind::TableConstraintInvalidReferenceColumns {
constraint: name.to_owned(),
table: table.to_string(),
columns: columns.clone(),
},
),
);
// iii. Source column doesn't exist
errors.extend(
foreign_keys
.iter()
.filter(|&&(ref constraint, ref columns, _, _)| {
let table = self
.tables
.iter()
.find(|t| t.constraints.iter().any(|c| c.name() == constraint));
match table {
Some(t) => !columns.iter().all(|rc| t.columns.iter().any(|c| c.name.eq(rc))),
None => false,
}
})
.map(
|&(ref name, ref columns, _, _)| ValidationKind::TableConstraintInvalidSourceColumns {
constraint: name.to_owned(),
columns: columns.clone(),
},
),
);
// iv. (Future) Source column match type is not compatible with reference column type
// 4. Validate indexes map to known tables
// i. reference table missing
errors.extend(
self.indexes
.iter()
.filter(|&index| !self.tables.iter().any(|t| t.name.eq(&index.table)))
.map(|ref index| ValidationKind::IndexInvalidReferenceTable {
index: index.name.to_string(),
table: index.table.to_string(),
}),
);
// ii. reference table exists but columns missing
errors.extend(
self.indexes
.iter()
.filter(|&index| {
let table = self.tables.iter().find(|t| t.name.eq(&index.table));
match table {
Some(t) => !index
.columns
.iter()
.all(|rc| t.columns.iter().any(|c| c.name.eq(&rc.name))),
None => false,
}
})
.map(|ref index| ValidationKind::IndexInvalidReferenceColumns {
index: index.name.to_string(),
table: index.table.to_string(),
columns: index.columns.iter().map(|c| c.name.to_string()).collect(),
}),
);
// 5. Validate function languages. For now, custom languages aren't supported
// until we can validate them.
errors.extend(
self.functions
.iter()
.filter(|&function| matches!(function.language, FunctionLanguage::Custom(_)))
.map(|ref function| ValidationKind::UnsupportedFunctionLanguage {
language: function.language.clone(),
name: function.name.clone(),
}),
);
// If there are no errors then we're "ok"
if errors.is_empty() {
Ok(())
} else {
bail!(ValidationError(errors))
}
}
}
impl Default for Package {
fn default() -> Self {
Self::new()
}
}
#[derive(Debug)]
pub enum ValidationKind {
IndexInvalidReferenceTable {
index: String,
table: String,
},
IndexInvalidReferenceColumns {
index: String,
table: String,
columns: Vec<String>,
},
TableConstraintInvalidReferenceTable {
constraint: String,
table: String,
},
TableConstraintInvalidReferenceColumns {
constraint: String,
table: String,
columns: Vec<String>,
},
TableConstraintInvalidSourceColumns {
constraint: String,
columns: Vec<String>,
},
SchemaMissing {
schema: String,
object: String,
},
UnknownType {
ty: ObjectName,
table: String,
},
UnsupportedFunctionLanguage {
language: FunctionLanguage,
name: ObjectName,
},
}
impl fmt::Display for ValidationKind {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ValidationKind::IndexInvalidReferenceTable { ref index, ref table } => {
write!(f, "Index `{}` uses unknown reference table `{}`", index, table)
}
ValidationKind::IndexInvalidReferenceColumns {
ref index,
ref table,
ref columns,
} => write!(
f,
"Index `{}` uses unknown reference column(s) on table `{}` (`{}`)",
index,
table,
columns.join("`, `")
),
ValidationKind::TableConstraintInvalidReferenceTable {
ref constraint,
ref table,
} => write!(
f,
"Foreign Key constraint `{}` uses unknown reference table `{}`",
constraint, table
),
ValidationKind::TableConstraintInvalidReferenceColumns {
ref constraint,
ref table,
ref columns,
} => write!(
f,
"Foreign Key constraint `{}` uses unknown reference column(s) on table `{}` (`{}`)",
constraint,
table,
columns.join("`, `")
),
ValidationKind::TableConstraintInvalidSourceColumns {
ref constraint,
ref columns,
} => write!(
f,
"Foreign Key constraint `{}` uses unknown source column(s) (`{}`)",
constraint,
columns.join("`, `")
),
ValidationKind::SchemaMissing { ref schema, ref object } => {
write!(f, "Schema `{}` missing for object `{}`", schema, object)
}
ValidationKind::UnknownType { ref ty, ref table } => {
write!(f, "Unknown type `{}` used on table `{}`", ty, table)
}
ValidationKind::UnsupportedFunctionLanguage { ref language, ref name } => write!(
f,
"Unsupported function language `{}` used on function `{}`",
language, name,
),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Node<'def> {
Table(&'def TableDefinition),
Column(&'def TableDefinition, &'def ColumnDefinition),
Constraint(&'def TableDefinition, &'def TableConstraint),
Function(&'def FunctionDefinition),
}
impl<'def> fmt::Display for Node<'def> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Node::Table(table) => write!(f, "Table: {}", table.name.to_string()),
Node::Column(table, column) => write!(f, "Column: {}.{}", table.name.to_string(), column.name),
Node::Constraint(table, constraint) => {
write!(f, "Constraint: {}.{}", table.name.to_string(), constraint.name())
}
Node::Function(function) => write!(f, "Function: {}", function.name.to_string()),
}
}
}
type Graph<'graph> = petgraph::graphmap::GraphMap<Node<'graph>, (), petgraph::Directed>;
trait Graphable {
fn graph<'graph, 'def: 'graph>(
&'def self,
log: &Logger,
graph: &mut Graph<'graph>,
parent: Option<&Node<'graph>>,
) -> Node<'graph>;
}
impl Graphable for TableDefinition {
fn graph<'graph, 'def: 'graph>(
&'def self,
log: &Logger,
graph: &mut Graph<'graph>,
_: Option<&Node<'graph>>,
) -> Node<'graph> {
// Table is dependent on a schema, so add the edge
// It will not have a parent - the schema is embedded in the name
trace!(log, "Adding");
let table_node = graph.add_node(Node::Table(self));
trace!(log, "Scanning columns");
for column in &self.columns {
let log = log.new(o!("column" => column.name.to_string()));
let column_node = column.graph(&log, graph, Some(&table_node));
graph.add_edge(table_node, column_node, ());
}
table_node
}
}
impl Graphable for ColumnDefinition {
fn graph<'graph, 'def: 'graph>(
&'def self,
log: &Logger,
graph: &mut Graph<'graph>,
parent: Option<&Node<'graph>>,
) -> Node<'graph> {
// Column does have a parent - namely the table
let table = match *parent.unwrap() {
Node::Table(table) => table,
_ => panic!("Non table parent for column."),
};
trace!(log, "Adding");
graph.add_node(Node::Column(table, self))
}
}
impl Graphable for FunctionDefinition {
fn graph<'graph, 'def: 'graph>(
&'def self,
log: &Logger,
graph: &mut Graph<'graph>,
_: Option<&Node<'graph>>,
) -> Node<'graph> {
// It will not have a parent - the schema is embedded in the name
trace!(log, "Adding");
graph.add_node(Node::Function(self))
}
}
impl Graphable for TableConstraint {
fn graph<'graph, 'def: 'graph>(
&'def self,
log: &Logger,
graph: &mut Graph<'graph>,
parent: Option<&Node<'graph>>,
) -> Node<'graph> {
// We currently have two types of table constraints: Primary and Foreign
// Primary is easy with a direct dependency to the column
// Foreign requires a weighted dependency
// This does have a parent - namely the table
let table_node = *parent.unwrap();
let table = match table_node {
Node::Table(table) => table,
_ => panic!("Non table parent for column."),
};
match *self {
TableConstraint::Primary {
ref name, ref columns, ..
} => {
let log = log.new(o!("primary constraint" => name.to_owned()));
// Primary relies on the columns existing (of course)
trace!(log, "Adding");
let constraint = graph.add_node(Node::Constraint(table, self));
for column_name in columns {
trace!(log, "Adding edge to column"; "column" => &column_name);
let column = table.columns.iter().find(|x| &x.name == column_name).unwrap();
graph.add_edge(Node::Column(table, column), constraint, ());
}
graph.add_edge(table_node, constraint, ());
constraint
}
TableConstraint::Foreign {
ref name,
ref columns,
ref ref_table,
ref ref_columns,
..
} => {
let log = log.new(o!("foreign constraint" => name.to_owned()));
// Foreign has two types of edges
trace!(log, "Adding");
let constraint = graph.add_node(Node::Constraint(table, self));
// Add edges to the columns in this table.
for column_name in columns {
trace!(log, "Adding edge to column"; "column" => &column_name);
let column = table.columns.iter().find(|x| &x.name == column_name).unwrap();
graph.add_edge(Node::Column(table, column), constraint, ());
}
// Find the details of the referenced table.
let table_named = |node: &Node| match *node {
Node::Table(table) => &table.name == ref_table,
_ => false,
};
let table_def = match graph.nodes().find(table_named) {
Some(Node::Table(table_def)) => table_def,
_ => panic!("Non table node found"),
};
// Add edges to the referenced columns.
for ref_column_name in ref_columns {
trace!(log, "Adding edge to refrenced column";
"table" => ref_table.to_string(),
"column" => &ref_column_name);
let ref_column = table_def.columns.iter().find(|x| &x.name == ref_column_name).unwrap();
graph.add_edge(Node::Column(table_def, ref_column), constraint, ());
// If required, add an edge to any primary keys.
for primary in &table_def.constraints {
if let TableConstraint::Primary { ref columns, .. } = *primary {
if columns.contains(ref_column_name) {
graph.add_edge(Node::Constraint(table_def, primary), constraint, ());
}
}
}
}
graph.add_edge(table_node, constraint, ());
constraint
}
}
}
}
#[cfg(test)]
mod tests {
use crate::errors::PsqlpackError;
use crate::errors::PsqlpackErrorKind::*;
use crate::model::*;
use crate::sql::parser::StatementListParser;
use crate::sql::{ast, lexer};
use slog::{Discard, Drain, Logger};
fn package_sql(sql: &str) -> Package {
let tokens = match lexer::tokenize_stmt(sql) {
Ok(t) => t,
Err(e) => panic!("Syntax error: {}", e.line),
};
let mut package = Package::new();
match StatementListParser::new().parse(tokens) {
Ok(statement_list) => {
for statement in statement_list {
match statement {
ast::Statement::Error(kind) => panic!("Unhandled error detected: {}", kind),
ast::Statement::Function(function_definition) => package.push_function(function_definition),
ast::Statement::Index(index_definition) => package.push_index(index_definition),
ast::Statement::Schema(schema_definition) => package.push_schema(schema_definition),
ast::Statement::Table(table_definition) => package.push_table(table_definition),
ast::Statement::Type(type_definition) => package.push_type(type_definition),
}
}
}
Err(err) => panic!("Failed to parse sql: {:?}", err),
}
package
}
fn empty_logger() -> Logger {
Logger::root(Discard.fuse(), o!())
}
macro_rules! assert_table {
($graph:ident,$index:expr,$name:expr) => {
match $graph[$index] {
Node::Table(table) => {
assert_eq!(table.name.to_string(), $name);
}
_ => panic!("Expected a table at index {}", $index),
}
};
}
macro_rules! assert_column {
($graph:ident,$index:expr,$table_name:expr,$column_name:expr) => {
match $graph[$index] {
Node::Column(table, column) => {
assert_eq!(table.name.to_string(), $table_name);
assert_eq!(column.name.to_string(), $column_name);
}
_ => panic!("Expected a column at index {}", $index),
}
};
}
macro_rules! assert_pk_constraint {
($graph:ident,$index:expr,$table_name:expr,$constraint_name:expr) => {
match $graph[$index] {
Node::Constraint(table, constraint) => {
assert_eq!(table.name.to_string(), $table_name);
match *constraint {
ast::TableConstraint::Primary { ref name, .. } => {
assert_eq!(name.to_string(), $constraint_name);
}
_ => panic!("Expected a primary key constraint at index {}", $index),
}
}
_ => panic!("Expected a constraint at index {}", $index),
}
};
}
macro_rules! assert_fk_constraint {
($graph:ident,$index:expr,$table_name:expr,$constraint_name:expr) => {
match $graph[$index] {
Node::Constraint(table, constraint) => {
assert_eq!(table.name.to_string(), $table_name);
match *constraint {
ast::TableConstraint::Foreign { ref name, .. } => {
assert_eq!(name.to_string(), $constraint_name);
}
_ => panic!("Expected a foreign key constraint at index {}", $index),
}
}
_ => panic!("Expected a constraint at index {}", $index),
}
};
}
#[test]
fn it_sets_table_defaults() {
let mut package = package_sql("CREATE TABLE hello_world(id int);");
let project = Project::default();
// Pre-condition checks
{
assert!(package.schemas.is_empty());
assert_eq!(package.tables.len(), 1);
let table = &package.tables[0];
assert!(table.name.schema.is_none());
assert_eq!(table.name.name, "hello_world");
}
// Set the defaults and assert again
package.set_defaults(&project);
assert_eq!(package.schemas.len(), 1);
assert_eq!(package.tables.len(), 1);
let schema = &package.schemas[0];
assert_eq!(schema.name, "public");
let table = &package.tables[0];
assert!(table.name.schema.is_some());
assert_eq!(table.name.schema.as_ref().unwrap(), "public");
assert_eq!(table.name.name, "hello_world");
}
#[test]
fn it_sets_index_defaults() {
let mut package = package_sql("CREATE INDEX idx_person_name ON person(name);");
let project = Project::default();
// Pre-condition checks
{
assert!(package.schemas.is_empty());
assert_eq!(package.indexes.len(), 1);
let index = &package.indexes[0];
assert!(index.table.schema.is_none());
assert_eq!(index.table.name, "person");
assert_eq!(index.columns.len(), 1);
let col = &index.columns[0];
assert_eq!(col.name, "name");
assert!(col.order.is_none());
assert!(col.null_position.is_none());
}
// Set the defaults and assert again
package.set_defaults(&project);
assert_eq!(package.schemas.len(), 1);
assert_eq!(package.indexes.len(), 1);
let schema = &package.schemas[0];
assert_eq!(schema.name, "public");
let index = &package.indexes[0];
assert!(index.table.schema.is_some());
assert_eq!(index.table.schema.as_ref().unwrap(), "public");
assert_eq!(index.table.name, "person");
assert_eq!(index.columns.len(), 1);
let col = &index.columns[0];
assert_eq!(col.name, "name");
assert!(col.order.is_some());
assert_eq!(col.order.as_ref().unwrap(), &ast::IndexOrder::Ascending);
assert!(col.null_position.is_some());
assert_eq!(col.null_position.as_ref().unwrap(), &ast::IndexPosition::Last);
}
#[test]
fn it_generates_a_simple_ordering() {
let package = package_sql(
"CREATE TABLE my.parents(id int);
CREATE SCHEMA my;",
);
let logger = empty_logger();
let graph = package.generate_dependency_graph(&logger);
// Make sure we generated two nodes.
// We don't generate schema's so it's just going to be table/column
assert!(graph.is_ok());
let graph = graph.unwrap();
assert_eq!(graph.len(), 2);
assert_table!(graph, 0, "my.parents");
assert_column!(graph, 1, "my.parents", "id");
}
#[test]
fn it_generates_a_complex_ordering_1() {
let package = package_sql(
"CREATE TABLE my.child(id int, parent_id int,
CONSTRAINT fk_parent_child FOREIGN KEY (parent_id)
REFERENCES my.parent(id)
MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION);
CREATE TABLE my.parent(id int);",
);
let logger = empty_logger();
let graph = package.generate_dependency_graph(&logger);
// Make sure we generated enough nodes (two tables + three columns + one constraint).
assert!(graph.is_ok());
let graph = graph.unwrap();
assert_eq!(graph.len(), 6);
assert_table!(graph, 0, "my.parent");
assert_column!(graph, 1, "my.parent", "id");
assert_table!(graph, 2, "my.child");
assert_column!(graph, 3, "my.child", "id");
assert_column!(graph, 4, "my.child", "parent_id");
assert_fk_constraint!(graph, 5, "my.child", "fk_parent_child");
}
#[test]
fn it_generates_a_complex_ordering_2() {
let package = package_sql(
"CREATE TABLE public.allocation (
id serial NOT NULL,
CONSTRAINT pk_public_allocation PRIMARY KEY (id)
);
CREATE TABLE public.transaction (
id serial NOT NULL,
allocation_id int NOT NULL,
CONSTRAINT pk_public_transaction PRIMARY KEY (id),
CONSTRAINT fk_public_transaction__allocation_id FOREIGN KEY (allocation_id)
REFERENCES public.allocation (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
);",
);
let logger = empty_logger();
let graph = package.generate_dependency_graph(&logger);
// Make sure we generated enough nodes (two tables + three columns + three constraints).
assert!(graph.is_ok());
let graph = graph.unwrap();
assert_eq!(graph.len(), 8);
assert_table!(graph, 0, "public.transaction");
assert_column!(graph, 1, "public.transaction", "id");
assert_column!(graph, 2, "public.transaction", "allocation_id");
assert_pk_constraint!(graph, 3, "public.transaction", "pk_public_transaction");
assert_table!(graph, 4, "public.allocation");
assert_column!(graph, 5, "public.allocation", "id");
assert_pk_constraint!(graph, 6, "public.allocation", "pk_public_allocation");
// FK is last
assert_fk_constraint!(graph, 7, "public.transaction", "fk_public_transaction__allocation_id");
}
#[test]
fn it_validates_missing_schema_references() {
let mut package = package_sql("CREATE TABLE my.items(id int);");
let result = package.validate(&Vec::new());
// `my` schema is missing
assert!(result.is_err());
let validation_errors = match result.err().unwrap() {
PsqlpackError(ValidationError(errors), _) => errors,
unexpected => panic!("Expected validation error however saw {:?}", unexpected),
};
assert_eq!(validation_errors.len(), 1);
match validation_errors[0] {
ValidationKind::SchemaMissing { ref schema, ref object } => {
assert_eq!(schema, "my");
assert_eq!(object, "items");
}
ref unexpected => panic!("Unexpected validation type: {:?}", unexpected),
}
// Add the schema and try again
package.schemas.push(ast::SchemaDefinition { name: "my".to_owned() });
assert!(package.validate(&Vec::new()).is_ok());
}
#[test]
fn it_validates_unknown_types() {
let mut package = package_sql(
"CREATE SCHEMA my;
CREATE TABLE my.items(id mytype);",
);
let project = Project::default();
package.set_defaults(&project);
let result = package.validate(&Vec::new());
// `mytype` is missing
assert!(result.is_err());
let validation_errors = match result.err().unwrap() {
PsqlpackError(ValidationError(errors), _) => errors,
unexpected => panic!("Expected validation error however saw {:?}", unexpected),
};
assert_eq!(validation_errors.len(), 1);
match validation_errors[0] {
ValidationKind::UnknownType { ref ty, ref table } => {
assert_eq!(
*ty,
ast::ObjectName {
schema: Some("public".to_string()),
name: "mytype".to_string(),
}
);
assert_eq!(table, "my.items");
}
ref unexpected => panic!("Unexpected validation type: {:?}", unexpected),
}
// Add the type and try again
package.types.push(ast::TypeDefinition {
name: ast::ObjectName {
schema: Some("public".to_string()),
name: "mytype".to_string(),
},
kind: ast::TypeDefinitionKind::Enum(Vec::new()),
});
assert!(package.validate(&Vec::new()).is_ok());
}
#[test]
fn it_validates_missing_reference_table_in_constraint() {
let mut package = package_sql(
"CREATE SCHEMA my;
CREATE TABLE my.child(id int, parent_id int,
CONSTRAINT fk_parent_child FOREIGN KEY (parent_id)
REFERENCES my.parent(id)
MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION);",
);
let result = package.validate(&Vec::new());
// `my.parent` does not exist
assert!(result.is_err());
let validation_errors = match result.err().unwrap() {
PsqlpackError(ValidationError(errors), _) => errors,
unexpected => panic!("Expected validation error however saw {:?}", unexpected),
};
assert_eq!(validation_errors.len(), 1);
match validation_errors[0] {
ValidationKind::TableConstraintInvalidReferenceTable {
ref constraint,
ref table,
} => {
assert_eq!(constraint, "fk_parent_child");
assert_eq!(table, "my.parent");
}
ref unexpected => panic!("Unexpected validation type: {:?}", unexpected),
}
// Add the table and try again
package.tables.push(ast::TableDefinition {
name: ast::ObjectName {
schema: Some("my".to_owned()),
name: "parent".to_owned(),
},
columns: vec![ast::ColumnDefinition {
name: "id".to_owned(),
sql_type: ast::SqlType::Simple(ast::SimpleSqlType::Serial, None),
constraints: Vec::new(),
}],
constraints: Vec::new(),
});
assert!(package.validate(&Vec::new()).is_ok());
}
#[test]
fn it_validates_missing_reference_column_in_constraint() {
let mut package = package_sql(
"CREATE SCHEMA my;
CREATE TABLE my.child(id int, parent_id int,
CONSTRAINT fk_parent_child FOREIGN KEY (parent_id)
REFERENCES my.parent(parent_id)
MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION);
CREATE TABLE my.parent(id int);",
);
let result = package.validate(&Vec::new());
// Column `parent_id` is invalid
assert!(result.is_err());
let validation_errors = match result.err().unwrap() {
PsqlpackError(ValidationError(errors), _) => errors,
unexpected => panic!("Expected validation error however saw {:?}", unexpected),
};
assert_eq!(validation_errors.len(), 1);
match validation_errors[0] {
ValidationKind::TableConstraintInvalidReferenceColumns {
ref constraint,
ref table,
ref columns,
} => {
assert_eq!(constraint, "fk_parent_child");
assert_eq!(table, "my.parent");
assert_eq!(columns.len(), 1);
assert_eq!(columns[0], "parent_id");
}
ref unexpected => panic!("Unexpected validation type: {:?}", unexpected),
}
// Add the column and try again
{
let parent = package.tables.iter_mut().find(|t| t.name.name.eq("parent")).unwrap();
parent.columns.push(ast::ColumnDefinition {
name: "parent_id".to_owned(),
sql_type: ast::SqlType::Simple(ast::SimpleSqlType::Integer, None),
constraints: Vec::new(),
});
}
assert!(package.validate(&Vec::new()).is_ok());
}
#[test]
fn it_validates_missing_source_column_in_constraint() {
let mut package = package_sql(
"CREATE SCHEMA my;
CREATE TABLE my.child(id int, parent_id int,
CONSTRAINT fk_parent_child FOREIGN KEY (par_id)
REFERENCES my.parent(id)
MATCH SIMPLE ON UPDATE NO ACTION ON DELETE NO ACTION);
CREATE TABLE my.parent(id int);",
);
let result = package.validate(&Vec::new());
// Column `par_id` is invalid
assert!(result.is_err());
let validation_errors = match result.err().unwrap() {
PsqlpackError(ValidationError(errors), _) => errors,
unexpected => panic!("Expected validation error however saw {:?}", unexpected),
};
assert_eq!(validation_errors.len(), 1);
match validation_errors[0] {
ValidationKind::TableConstraintInvalidSourceColumns {
ref constraint,
ref columns,
} => {
assert_eq!(constraint, "fk_parent_child");
assert_eq!(columns.len(), 1);
assert_eq!(columns[0], "par_id");
}
ref unexpected => panic!("Unexpected validation type: {:?}", unexpected),
}
// Add the column and try again
{
let child = package.tables.iter_mut().find(|t| t.name.name.eq("child")).unwrap();
child.columns.push(ast::ColumnDefinition {
name: "par_id".to_owned(),
sql_type: ast::SqlType::Simple(ast::SimpleSqlType::Integer, None),
constraints: Vec::new(),
});
}
assert!(package.validate(&Vec::new()).is_ok());
}
#[test]
fn it_validates_missing_reference_table_in_index() {
let mut package = package_sql(
"CREATE SCHEMA my;
CREATE TABLE my.person(id int, name varchar(50));
CREATE UNIQUE INDEX idx_company_name ON my.company (name);",
);
let result = package.validate(&Vec::new());
// `my.company` does not exist
assert!(result.is_err());
let validation_errors = match result.err().unwrap() {
PsqlpackError(ValidationError(errors), _) => errors,
unexpected => panic!("Expected validation error however saw {:?}", unexpected),
};
assert_eq!(validation_errors.len(), 1);
match validation_errors[0] {
ValidationKind::IndexInvalidReferenceTable { ref index, ref table } => {
assert_eq!(index, "idx_company_name");
assert_eq!(table, "my.company");
}
ref unexpected => panic!("Unexpected validation type: {:?}", unexpected),
}
// Add the table and try again
package.tables.push(ast::TableDefinition {
name: ast::ObjectName {
schema: Some("my".to_owned()),
name: "company".to_owned(),
},
columns: vec![
ast::ColumnDefinition {
name: "id".to_owned(),
sql_type: ast::SqlType::Simple(ast::SimpleSqlType::Serial, None),
constraints: Vec::new(),
},
ast::ColumnDefinition {
name: "name".to_owned(),
sql_type: ast::SqlType::Simple(ast::SimpleSqlType::VariableLengthString(50), None),
constraints: Vec::new(),
},
],
constraints: Vec::new(),
});
assert!(package.validate(&Vec::new()).is_ok());
}
#[test]
fn it_validates_missing_reference_column_in_index() {
let mut package = package_sql(
"CREATE SCHEMA my;
CREATE TABLE my.person(id int, name varchar(50));
CREATE UNIQUE INDEX idx_person_number ON my.person (number);",
);
let result = package.validate(&Vec::new());
// Column `person.number` is invalid
assert!(result.is_err());
let validation_errors = match result.err().unwrap() {
PsqlpackError(ValidationError(errors), _) => errors,
unexpected => panic!("Expected validation error however saw {:?}", unexpected),
};
assert_eq!(validation_errors.len(), 1);
match validation_errors[0] {
ValidationKind::IndexInvalidReferenceColumns {
ref index,
ref table,
ref columns,
} => {
assert_eq!(index, "idx_person_number");
assert_eq!(table, "my.person");
assert_eq!(columns.len(), 1);
assert_eq!(columns[0], "number");
}
ref unexpected => panic!("Unexpected validation type: {:?}", unexpected),
}
// Add the column and try again
{
let person = package.tables.iter_mut().find(|t| t.name.name.eq("person")).unwrap();
person.columns.push(ast::ColumnDefinition {
name: "number".to_owned(),
sql_type: ast::SqlType::Simple(ast::SimpleSqlType::Integer, None),
constraints: Vec::new(),
});
}
assert!(package.validate(&Vec::new()).is_ok());
}
}
|
use serde::{Deserialize, Serialize};
use std::fmt::Write;
use time::{OffsetDateTime, UtcOffset};
use crate::{
default_datetime, direction::Direction, distance::Distance, humidity::Humidity,
latitude::Latitude, longitude::Longitude, precipitation::Precipitation, pressure::Pressure,
speed::Speed, temperature::Temperature, timestamp, timezone::TimeZone, StringType,
};
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Coord {
pub lon: Longitude,
pub lat: Latitude,
}
#[derive(Serialize, Deserialize, Debug, Clone, Default, PartialEq, Eq)]
pub struct WeatherCond {
pub id: usize,
pub main: StringType,
pub description: StringType,
pub icon: StringType,
}
#[derive(Serialize, Deserialize, Debug, Clone, Copy, Default, PartialEq)]
pub struct WeatherMain {
pub temp: Temperature,
pub feels_like: Temperature,
pub temp_min: Temperature,
pub temp_max: Temperature,
pub pressure: Pressure,
pub humidity: Humidity,
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy, Default, PartialEq)]
pub struct Wind {
pub speed: Speed,
#[serde(skip_serializing_if = "Option::is_none")]
pub deg: Option<Direction>,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq, Eq)]
pub struct Sys {
#[serde(skip_serializing_if = "Option::is_none")]
pub country: Option<StringType>,
#[serde(with = "timestamp")]
pub sunrise: OffsetDateTime,
#[serde(with = "timestamp")]
pub sunset: OffsetDateTime,
}
impl Default for Sys {
fn default() -> Self {
Self {
country: None,
sunrise: default_datetime(),
sunset: default_datetime(),
}
}
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq)]
pub struct Rain {
#[serde(alias = "3h", skip_serializing_if = "Option::is_none")]
pub three_hour: Option<Precipitation>,
#[serde(alias = "1h", skip_serializing_if = "Option::is_none")]
pub one_hour: Option<Precipitation>,
}
#[derive(Deserialize, Serialize, Debug, Clone, Copy, PartialEq)]
pub struct Snow {
#[serde(alias = "3h", skip_serializing_if = "Option::is_none")]
pub three_hour: Option<Precipitation>,
#[serde(alias = "1h", skip_serializing_if = "Option::is_none")]
pub one_hour: Option<Precipitation>,
}
#[derive(Deserialize, Serialize, Debug, Clone, PartialEq)]
pub struct WeatherData {
pub coord: Coord,
pub weather: Vec<WeatherCond>,
pub base: StringType,
pub main: WeatherMain,
#[serde(skip_serializing_if = "Option::is_none")]
pub visibility: Option<Distance>,
pub wind: Wind,
#[serde(skip_serializing_if = "Option::is_none")]
pub rain: Option<Rain>,
#[serde(skip_serializing_if = "Option::is_none")]
pub snow: Option<Snow>,
#[serde(with = "timestamp")]
pub dt: OffsetDateTime,
pub sys: Sys,
pub timezone: TimeZone,
pub name: StringType,
}
impl Default for WeatherData {
fn default() -> Self {
Self {
coord: Coord::default(),
weather: Vec::new(),
base: "".into(),
main: WeatherMain::default(),
visibility: None,
wind: Wind::default(),
rain: None,
snow: None,
dt: default_datetime(),
sys: Sys::default(),
timezone: TimeZone::default(),
name: "".into(),
}
}
}
impl WeatherData {
#[must_use]
pub fn get_offset(&self) -> UtcOffset {
self.timezone.into()
}
#[must_use]
pub fn get_dt(&self) -> OffsetDateTime {
self.dt.to_offset(self.get_offset())
}
#[must_use]
pub fn get_sunrise(&self) -> OffsetDateTime {
self.sys.sunrise.to_offset(self.get_offset())
}
#[must_use]
pub fn get_sunset(&self) -> OffsetDateTime {
self.sys.sunset.to_offset(self.get_offset())
}
/// Write out formatted information about current conditions for a mutable
/// buffer.
/// ```
/// use weather_util_rust::weather_data::WeatherData;
/// # use anyhow::Error;
/// # use std::io::{stdout, Write, Read};
/// # use std::fs::File;
/// # fn main() -> Result<(), Error> {
/// # let mut buf = String::new();
/// # let mut f = File::open("tests/weather.json")?;
/// # f.read_to_string(&mut buf)?;
/// let data: WeatherData = serde_json::from_str(&buf)?;
///
/// let buf = data.get_current_conditions();
///
/// assert!(buf.starts_with("Current conditions Astoria US 40.76"));
/// assert!(buf.contains("Temperature: 38.50 F (3.61 C)"));
/// # Ok(())
/// # }
/// ```
#[must_use]
pub fn get_current_conditions(&self) -> StringType {
let mut output: StringType = "Current conditions ".into();
let fo: UtcOffset = self.timezone.into();
let dt = self.dt.to_offset(fo);
let sunrise = self.sys.sunrise.to_offset(fo);
let sunset = self.sys.sunset.to_offset(fo);
if let Some(country) = &self.sys.country {
let name = &self.name;
write!(output, "{name} {country} ").unwrap_or(());
};
writeln!(output, "{:0.5}N {:0.5}E", self.coord.lat, self.coord.lon).unwrap_or(());
writeln!(output, "Last Updated {dt}").unwrap_or(());
writeln!(
output,
"\tTemperature: {f:0.2} F ({c:0.2} C)",
f = self.main.temp.fahrenheit(),
c = self.main.temp.celcius(),
)
.unwrap_or(());
writeln!(output, "\tRelative Humidity: {}%", self.main.humidity).unwrap_or(());
writeln!(
output,
"\tWind: {d} degrees at {s:0.2} mph",
d = self.wind.deg.unwrap_or_else(|| 0.0.into()),
s = self.wind.speed.mph(),
)
.unwrap_or(());
writeln!(
output,
"\tConditions: {}",
self.weather.get(0).map_or_else(|| "", |w| &w.description)
)
.unwrap_or(());
writeln!(output, "\tSunrise: {sunrise}").unwrap_or(());
write!(output, "\tSunset: {sunset}").unwrap_or(());
if let Some(rain) = &self.rain {
write!(
output,
"\n\tRain: {:0.3} in",
rain.one_hour.map_or(0.0, Precipitation::inches)
)
.unwrap_or(());
};
if let Some(snow) = &self.snow {
write!(
output,
"\n\tSnow: {:0.3} in",
snow.one_hour.map_or(0.0, Precipitation::inches)
)
.unwrap_or(());
};
output.push('\n');
output
}
}
#[cfg(test)]
mod test {
use crate::{
default_datetime,
timezone::TimeZone,
weather_data::{Coord, Sys, WeatherData, WeatherMain, Wind},
Error,
};
use log::info;
#[test]
fn test_weather_data() -> Result<(), Error> {
let buf = include_str!("../tests/weather.json");
let data: WeatherData = serde_json::from_str(buf)?;
let buf = data.get_current_conditions();
assert!(buf.starts_with("Current conditions Astoria US 40.76"));
assert!(buf.contains("Temperature: 38.50 F (3.61 C)"));
info!("{} {} {}", buf.len(), data.name, data.name.len());
Ok(())
}
#[test]
fn test_default_sys() -> Result<(), Error> {
let default_sys = Sys::default();
assert_eq!(default_sys.country, None);
assert_eq!(default_sys.sunrise, default_datetime());
assert_eq!(default_sys.sunset, default_datetime());
Ok(())
}
#[test]
fn test_default_weather_data() -> Result<(), Error> {
let default_data = WeatherData::default();
assert_eq!(default_data.coord, Coord::default());
assert_eq!(default_data.weather, Vec::new());
assert_eq!(&default_data.base, "");
assert_eq!(default_data.main, WeatherMain::default());
assert_eq!(default_data.visibility, None);
assert_eq!(default_data.wind, Wind::default());
assert_eq!(default_data.rain, None);
assert_eq!(default_data.snow, None);
assert_eq!(default_data.dt, default_datetime());
assert_eq!(default_data.sys, Sys::default());
assert_eq!(default_data.timezone, TimeZone::default());
assert_eq!(&default_data.name, "");
let default_offset = default_data.get_offset();
assert_eq!(default_data.get_offset(), TimeZone::default().into());
assert_eq!(
default_data.get_dt(),
default_datetime().to_offset(default_offset)
);
assert_eq!(
default_data.get_sunrise(),
Sys::default().sunrise.to_offset(default_offset)
);
assert_eq!(
default_data.get_sunset(),
Sys::default().sunset.to_offset(default_offset)
);
let conditions = default_data.get_current_conditions();
assert!(conditions.contains("Relative Humidity: 0%"));
Ok(())
}
}
|
use std::{
convert::TryInto,
io::{self, Read, Write},
};
use tokio::{
io::{AsyncRead, AsyncWrite},
prelude::Async,
sync::lock::Lock,
};
use zmq::{Context, Message, Result, Socket, REQ};
use enclave_protocol::FLAGS;
macro_rules! lock {
($e:expr) => {
match $e.poll_lock() {
Async::Ready(inner) => inner,
Async::NotReady => return Ok(Async::NotReady),
}
};
}
macro_rules! try_lock {
($e:expr) => {
match $e.poll_lock() {
Async::Ready(inner) => inner,
Async::NotReady => return Err(io::ErrorKind::WouldBlock.into()),
}
};
}
macro_rules! try_poll {
($e:expr) => {
match $e {
Async::Ready(inner) => inner,
Async::NotReady => return Err(io::ErrorKind::WouldBlock.into()),
}
};
}
/// Temporary bridging between the old code and EDP. In the long term, it may go away completely.
///
/// 1. Decryption requests may include the sealed payload in them (so no need to request them via zmq)
/// 2. Encryption requests may be done via a direct attested secure channel (instead of this passing of sealed requests)
pub struct ZmqHelper {
inner: Lock<Inner>,
}
/// Inner struct to hold values in a `Lock`
///
/// `Lock` is there to enforce the synchronous order as zmq isn't thread safe
struct Inner {
/// State of ZeroMQ socket
state: SocketState,
/// ZeroMQ socket
socket: Socket,
}
/// State of ZeroMQ socket
#[derive(Debug)]
enum SocketState {
/// Denotes that a new request can be sent on ZeroMQ socket
Ready,
/// Denotes that a request is sent to ZeroMQ socket but response is not received yet
RequestSent,
/// Denotes that response to a previously sent request is received
ResponseReceived(Message),
}
impl ZmqHelper {
/// Creates a new instance of ZeroMQ helper
pub fn new(connection_str: &str) -> Self {
let ctx = Context::new();
let socket = ctx.socket(REQ).expect("failed to init zmq context");
socket
.connect(connection_str)
.expect("failed to connect to the tx validation enclave zmq");
let inner = Inner {
state: SocketState::Ready,
socket,
};
log::debug!("Successfully created ZeroMQ helper");
Self {
inner: Lock::new(inner),
}
}
/// Sends a message to ZeroMQ socket
pub fn send<S: Into<Message>>(&mut self, message: S) -> Result<Async<()>> {
log::debug!("Sending message to ZeroMQ");
let mut inner = lock!(self.inner);
match inner.state {
SocketState::Ready => {
inner.socket.send(message, FLAGS)?;
inner.state = SocketState::RequestSent;
Ok(Async::Ready(()))
}
_ => {
log::debug!("Unable to send message. Previous response isn't processed");
Ok(Async::NotReady)
}
}
}
/// Returns `true` if previous request was sent. `false` otherwise.
pub fn is_request_sent(&mut self) -> Result<Async<bool>> {
let inner = lock!(self.inner);
Ok(Async::Ready(matches!(
inner.state,
SocketState::RequestSent
)))
}
/// Returns `true` if response was received. `false` otherwise.
pub fn is_response_received(&mut self) -> Result<Async<bool>> {
let inner = lock!(self.inner);
Ok(Async::Ready(matches!(
inner.state,
SocketState::ResponseReceived(_)
)))
}
/// Returns the length of message received from ZeroMQ
pub fn get_message_len(&mut self) -> Result<Async<usize>> {
let mut inner = lock!(self.inner);
let message = match inner.state {
SocketState::RequestSent => inner.socket.recv_msg(FLAGS)?,
_ => {
log::debug!("Unable to receive message. Previous request wasn't sent");
return Ok(Async::NotReady);
}
};
let message_len = message.len();
inner.state = SocketState::ResponseReceived(message);
Ok(Async::Ready(message_len))
}
/// Returns the message received from ZeroMQ
pub fn get_message(&mut self) -> Result<Async<Message>> {
log::debug!("Receiving response to ZeroMQ");
let mut inner = lock!(self.inner);
if matches!(inner.state, SocketState::ResponseReceived(_)) {
let mut socket_state = SocketState::Ready;
std::mem::swap(&mut socket_state, &mut inner.state);
if let SocketState::ResponseReceived(message) = socket_state {
Ok(Async::Ready(message))
} else {
unreachable!("Socket state cannot be anything other than `ResponseReceived`")
}
} else {
log::debug!("Unable to receive message. Previous request wasn't sent");
Ok(Async::NotReady)
}
}
}
impl Read for ZmqHelper {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
if try_poll!(self.is_request_sent()?) {
let message_len: u32 = try_poll!(self.get_message_len()?)
.try_into()
.expect("Message length exceeds `u32` bounds");
buf.copy_from_slice(&message_len.to_le_bytes());
Ok(core::mem::size_of::<u32>())
} else if try_poll!(self.is_response_received()?) {
let message = try_poll!(self.get_message()?);
buf.copy_from_slice(&message);
Ok(message.len())
} else {
Err(io::ErrorKind::WouldBlock.into())
}
}
}
impl Write for ZmqHelper {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
try_poll!(self.send(buf)?);
Ok(buf.len())
}
fn flush(&mut self) -> io::Result<()> {
try_lock!(self.inner);
Ok(())
}
}
impl AsyncRead for ZmqHelper {}
impl AsyncWrite for ZmqHelper {
fn shutdown(&mut self) -> io::Result<Async<()>> {
Ok(().into())
}
}
|
//! Passes between intermediate languages.
//!
//! The most significant step in this process is the [`surface_to_core`] pass,
//! which handles elaboration of the surface language into the core language,
//! and is the source of most user-facing typing diagnostics.
pub mod core_to_pretty;
pub mod core_to_surface;
pub mod surface_to_core;
pub mod surface_to_pretty;
|
use super::is_transient_error;
use crate::listener::Listener;
use crate::{log, Server};
use std::fmt::{self, Display, Formatter};
use async_std::net::{self, SocketAddr, TcpStream};
use async_std::prelude::*;
use async_std::{io, task};
/// This represents a tide [Listener](crate::listener::Listener) that
/// wraps an [async_std::net::TcpListener]. It is implemented as an
/// enum in order to allow creation of a tide::listener::TcpListener
/// from a SocketAddr spec that has not yet been bound OR from a bound
/// TcpListener.
///
/// This is currently crate-visible only, and tide users are expected
/// to create these through [ToListener](crate::ToListener) conversions.
#[derive(Debug)]
pub enum TcpListener {
FromListener(net::TcpListener),
FromAddrs(Vec<SocketAddr>, Option<net::TcpListener>),
}
impl TcpListener {
pub fn from_addrs(addrs: Vec<SocketAddr>) -> Self {
Self::FromAddrs(addrs, None)
}
pub fn from_listener(tcp_listener: impl Into<net::TcpListener>) -> Self {
Self::FromListener(tcp_listener.into())
}
fn listener(&self) -> io::Result<&net::TcpListener> {
match self {
Self::FromAddrs(_, Some(listener)) => Ok(listener),
Self::FromListener(listener) => Ok(listener),
Self::FromAddrs(addrs, None) => Err(io::Error::new(
io::ErrorKind::AddrNotAvailable,
format!("unable to connect to {:?}", addrs),
)),
}
}
async fn connect(&mut self) -> io::Result<()> {
if let Self::FromAddrs(addrs, listener @ None) = self {
*listener = Some(net::TcpListener::bind(addrs.as_slice()).await?);
}
Ok(())
}
}
fn handle_tcp<State: Clone + Send + Sync + 'static>(app: Server<State>, stream: TcpStream) {
task::spawn(async move {
let local_addr = stream.local_addr().ok();
let peer_addr = stream.peer_addr().ok();
let fut = async_h1::accept(stream, |mut req| async {
req.set_local_addr(local_addr);
req.set_peer_addr(peer_addr);
app.respond(req).await
});
if let Err(error) = fut.await {
log::error!("async-h1 error", { error: error.to_string() });
}
});
}
#[async_trait::async_trait]
impl<State: Clone + Send + Sync + 'static> Listener<State> for TcpListener {
async fn listen(&mut self, app: Server<State>) -> io::Result<()> {
self.connect().await?;
let listener = self.listener()?;
crate::log::info!("Server listening on {}", self);
let mut incoming = listener.incoming();
while let Some(stream) = incoming.next().await {
match stream {
Err(ref e) if is_transient_error(e) => continue,
Err(error) => {
let delay = std::time::Duration::from_millis(500);
crate::log::error!("Error: {}. Pausing for {:?}.", error, delay);
task::sleep(delay).await;
continue;
}
Ok(stream) => {
handle_tcp(app.clone(), stream);
}
};
}
Ok(())
}
}
impl Display for TcpListener {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
match self {
Self::FromListener(l) | Self::FromAddrs(_, Some(l)) => write!(
f,
"http://{}",
l.local_addr()
.ok()
.map(|a| a.to_string())
.as_deref()
.unwrap_or("[unknown]")
),
Self::FromAddrs(addrs, None) => write!(
f,
"{}",
addrs
.iter()
.map(|a| format!("http://{}", a))
.collect::<Vec<_>>()
.join(", ")
),
}
}
}
|
use crate::v0::support::{
try_only_named_multipart, with_ipfs, MaybeTimeoutExt, NotImplemented, StringError,
StringSerialized,
};
use cid::{Cid, Codec};
use futures::stream::Stream;
use ipfs::{Ipfs, IpfsTypes};
use mime::Mime;
use serde::Deserialize;
use serde_json::json;
use warp::{query, reply, Buf, Filter, Rejection, Reply};
#[derive(Debug, Deserialize)]
pub struct PutQuery {
format: Option<String>,
hash: Option<String>,
#[serde(rename = "input-enc", default)]
encoding: InputEncoding,
}
#[derive(PartialEq, Eq, Debug, Deserialize)]
pub enum InputEncoding {
#[serde(rename = "raw")]
Raw,
#[serde(rename = "json")]
Json,
}
impl Default for InputEncoding {
fn default() -> Self {
InputEncoding::Json
}
}
pub fn put<T: IpfsTypes>(
ipfs: &Ipfs<T>,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone {
with_ipfs(ipfs)
.and(query::<PutQuery>())
.and(warp::header::<Mime>("content-type")) // TODO: rejects if missing
.and(warp::body::stream())
.and_then(put_query)
}
async fn put_query<T: IpfsTypes>(
ipfs: Ipfs<T>,
query: PutQuery,
mime: Mime,
body: impl Stream<Item = Result<impl Buf, warp::Error>> + Unpin,
) -> Result<impl Reply, Rejection> {
use multihash::{Multihash, Sha2_256, Sha2_512, Sha3_512};
if query.encoding != InputEncoding::Raw {
return Err(NotImplemented.into());
}
let (format, v0_fmt) = match query.format.as_deref().unwrap_or("dag-cbor") {
"dag-cbor" => (Codec::DagCBOR, false),
"dag-pb" => (Codec::DagProtobuf, true),
"dag-json" => (Codec::DagJSON, false),
"raw" => (Codec::Raw, false),
_ => return Err(StringError::from("unknown codec").into()),
};
let (hasher, v0_hash) = match query.hash.as_deref().unwrap_or("sha2-256") {
"sha2-256" => (Sha2_256::digest as fn(&[u8]) -> Multihash, true),
"sha2-512" => (Sha2_512::digest as fn(&[u8]) -> Multihash, false),
"sha3-512" => (Sha3_512::digest as fn(&[u8]) -> Multihash, false),
_ => return Err(StringError::from("unknown hash").into()),
};
let boundary = mime
.get_param("boundary")
.map(|v| v.to_string())
.ok_or_else(|| StringError::from("missing 'boundary' on content-type"))?;
let data = try_only_named_multipart(&["data", "file"], 1024 * 1024, boundary, body)
.await
.map_err(StringError::from)?;
let digest = hasher(&data);
let cid = if v0_fmt && v0_hash {
// this is quite ugly way but apparently js-ipfs generates a v0 cid for this combination
// which is also created by go-ipfs
Cid::new_v0(digest).expect("cidv0 creation cannot fail for dag-pb and sha2-256")
} else {
Cid::new_v1(format, digest)
};
let reply = json!({
"Cid": { "/": cid.to_string() }
});
// delay reallocation until cid has been generated
let data = data.into_boxed_slice();
let block = ipfs::Block { cid, data };
ipfs.put_block(block).await.map_err(StringError::from)?;
Ok(reply::json(&reply))
}
/// Per https://docs-beta.ipfs.io/reference/http/api/#api-v0-block-resolve this endpoint takes in a
/// path and resolves it to the last block (the cid), and to the path inside the final block
/// (rempath).
pub fn resolve<T: IpfsTypes>(
ipfs: &Ipfs<T>,
) -> impl Filter<Extract = (impl Reply,), Error = Rejection> + Clone {
with_ipfs(ipfs)
.and(query::<ResolveOptions>())
.and_then(inner_resolve)
}
#[derive(Debug, Deserialize)]
struct ResolveOptions {
arg: String,
timeout: Option<StringSerialized<humantime::Duration>>,
#[serde(rename = "local-resolve", default)]
local_resolve: bool,
}
async fn inner_resolve<T: IpfsTypes>(
ipfs: Ipfs<T>,
opts: ResolveOptions,
) -> Result<impl Reply, Rejection> {
use ipfs::IpfsPath;
use std::convert::TryFrom;
let path = IpfsPath::try_from(opts.arg.as_str()).map_err(StringError::from)?;
// I think the naming of local_resolve is quite confusing. when following links we "resolve
// globally" and when not following links we are "resolving locally", or in single document.
let follow_links = !opts.local_resolve;
let (resolved, remaining) = ipfs
.dag()
.resolve(path, follow_links)
.maybe_timeout(opts.timeout.map(StringSerialized::into_inner))
.await
.map_err(StringError::from)?
.map_err(StringError::from)?;
let current = resolved.source();
Ok(reply::json(&json!({
"Cid": { "/": current.to_string() },
"RemPath": StringSerialized(remaining),
})))
}
|
//! Representations of various client errors
use std::io::Error as IoError;
use hyper::Error as HttpError;
use hyper::status::StatusCode;
use rustc_serialize::json::{DecoderError, EncoderError, ParserError};
#[derive(Debug)]
pub enum Error {
Decoding(DecoderError),
Encoding(EncoderError),
Parse(ParserError),
Http(HttpError),
IO(IoError),
Fault {
code: StatusCode,
message: String,
},
}
impl From<ParserError> for Error {
fn from(error: ParserError) -> Error {
Error::Parse(error)
}
}
impl From<DecoderError> for Error {
fn from(error: DecoderError) -> Error {
Error::Decoding(error)
}
}
impl From<EncoderError> for Error {
fn from(error: EncoderError) -> Error {
Error::Encoding(error)
}
}
impl From<HttpError> for Error {
fn from(error: HttpError) -> Error {
Error::Http(error)
}
}
impl From<IoError> for Error {
fn from(error: IoError) -> Error {
Error::IO(error)
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type AppServiceClosedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppServiceClosedStatus(pub i32);
impl AppServiceClosedStatus {
pub const Completed: Self = Self(0i32);
pub const Canceled: Self = Self(1i32);
pub const ResourceLimitsExceeded: Self = Self(2i32);
pub const Unknown: Self = Self(3i32);
}
impl ::core::marker::Copy for AppServiceClosedStatus {}
impl ::core::clone::Clone for AppServiceClosedStatus {
fn clone(&self) -> Self {
*self
}
}
pub type AppServiceConnection = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppServiceConnectionStatus(pub i32);
impl AppServiceConnectionStatus {
pub const Success: Self = Self(0i32);
pub const AppNotInstalled: Self = Self(1i32);
pub const AppUnavailable: Self = Self(2i32);
pub const AppServiceUnavailable: Self = Self(3i32);
pub const Unknown: Self = Self(4i32);
pub const RemoteSystemUnavailable: Self = Self(5i32);
pub const RemoteSystemNotSupportedByApp: Self = Self(6i32);
pub const NotAuthorized: Self = Self(7i32);
pub const AuthenticationError: Self = Self(8i32);
pub const NetworkNotAvailable: Self = Self(9i32);
pub const DisabledByPolicy: Self = Self(10i32);
pub const WebServiceUnavailable: Self = Self(11i32);
}
impl ::core::marker::Copy for AppServiceConnectionStatus {}
impl ::core::clone::Clone for AppServiceConnectionStatus {
fn clone(&self) -> Self {
*self
}
}
pub type AppServiceDeferral = *mut ::core::ffi::c_void;
pub type AppServiceRequest = *mut ::core::ffi::c_void;
pub type AppServiceRequestReceivedEventArgs = *mut ::core::ffi::c_void;
pub type AppServiceResponse = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct AppServiceResponseStatus(pub i32);
impl AppServiceResponseStatus {
pub const Success: Self = Self(0i32);
pub const Failure: Self = Self(1i32);
pub const ResourceLimitsExceeded: Self = Self(2i32);
pub const Unknown: Self = Self(3i32);
pub const RemoteSystemUnavailable: Self = Self(4i32);
pub const MessageSizeTooLarge: Self = Self(5i32);
pub const AppUnavailable: Self = Self(6i32);
pub const AuthenticationError: Self = Self(7i32);
pub const NetworkNotAvailable: Self = Self(8i32);
pub const DisabledByPolicy: Self = Self(9i32);
pub const WebServiceUnavailable: Self = Self(10i32);
}
impl ::core::marker::Copy for AppServiceResponseStatus {}
impl ::core::clone::Clone for AppServiceResponseStatus {
fn clone(&self) -> Self {
*self
}
}
pub type AppServiceTriggerDetails = *mut ::core::ffi::c_void;
pub type StatelessAppServiceResponse = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct StatelessAppServiceResponseStatus(pub i32);
impl StatelessAppServiceResponseStatus {
pub const Success: Self = Self(0i32);
pub const AppNotInstalled: Self = Self(1i32);
pub const AppUnavailable: Self = Self(2i32);
pub const AppServiceUnavailable: Self = Self(3i32);
pub const RemoteSystemUnavailable: Self = Self(4i32);
pub const RemoteSystemNotSupportedByApp: Self = Self(5i32);
pub const NotAuthorized: Self = Self(6i32);
pub const ResourceLimitsExceeded: Self = Self(7i32);
pub const MessageSizeTooLarge: Self = Self(8i32);
pub const Failure: Self = Self(9i32);
pub const Unknown: Self = Self(10i32);
pub const AuthenticationError: Self = Self(11i32);
pub const NetworkNotAvailable: Self = Self(12i32);
pub const DisabledByPolicy: Self = Self(13i32);
pub const WebServiceUnavailable: Self = Self(14i32);
}
impl ::core::marker::Copy for StatelessAppServiceResponseStatus {}
impl ::core::clone::Clone for StatelessAppServiceResponseStatus {
fn clone(&self) -> Self {
*self
}
}
|
//! UDP relay local server
use std::{io, net::SocketAddr, sync::Arc, time::Duration};
use async_trait::async_trait;
use log::{debug, error, info, trace, warn};
use tokio::{self, net::UdpSocket, time};
use crate::{
context::SharedContext,
relay::{
loadbalancing::server::{PlainPingBalancer, ServerType},
socks5::Address,
sys::create_udp_socket,
},
};
use super::{
association::{ProxyAssociation, ProxyAssociationManager, ProxySend},
MAXIMUM_UDP_PAYLOAD_SIZE,
};
#[derive(Clone)]
struct ProxyHandler {
src_addr: SocketAddr,
cache_key: String,
assoc_manager: ProxyAssociationManager<String>,
tx: Arc<UdpSocket>,
}
impl ProxyHandler {
fn new(src_addr: SocketAddr, assoc_manager: ProxyAssociationManager<String>, tx: Arc<UdpSocket>) -> ProxyHandler {
ProxyHandler {
src_addr,
cache_key: src_addr.to_string(),
assoc_manager,
tx,
}
}
}
#[async_trait]
impl ProxySend for ProxyHandler {
async fn send_packet(&mut self, _addr: Address, data: Vec<u8>) -> io::Result<()> {
if !self.assoc_manager.keep_alive(&self.cache_key).await {
debug!(
"UDP association {} <-> ... is already expired, throwing away packet {} bytes",
self.src_addr,
data.len()
);
return Ok(());
}
match self.tx.send_to(&data, &self.src_addr).await {
Ok(n) => {
if n < data.len() {
warn!(
"UDP association {} <- ... payload truncated, expecting {} bytes, but sent {} bytes",
self.src_addr,
data.len(),
n
);
}
Ok(())
}
Err(err) => return Err(err),
}
}
}
/// Starts a UDP local server
pub async fn run(context: SharedContext) -> io::Result<()> {
let local_addr = context.config().local_addr.as_ref().expect("local config");
let bind_addr = local_addr.bind_addr(&context).await?;
let l = create_udp_socket(&bind_addr).await?;
let local_addr = l.local_addr().expect("could not determine port bound to");
let balancer = PlainPingBalancer::new(context.clone(), ServerType::Udp).await;
let r = Arc::new(l);
let w = r.clone();
let forward_target = context.config().forward.clone().expect("`forward` address in config");
info!(
"shadowsocks UDP tunnel listening on {}, forward to {}",
local_addr, forward_target
);
let assoc_manager = ProxyAssociationManager::new(context.config());
let mut pkt_buf = vec![0u8; MAXIMUM_UDP_PAYLOAD_SIZE];
loop {
let (recv_len, src) = match r.recv_from(&mut pkt_buf).await {
Ok(o) => o,
Err(err) => {
error!("recv_from failed with err: {}", err);
time::sleep(Duration::from_secs(1)).await;
continue;
}
};
// Packet length is limited by MAXIMUM_UDP_PAYLOAD_SIZE, excess bytes will be discarded.
// Copy bytes, because udp_associate runs in another tokio Task
let pkt = &pkt_buf[..recv_len];
trace!("received UDP packet from {}, length {} bytes", src, recv_len);
if recv_len == 0 {
// For windows, it will generate a ICMP Port Unreachable Message
// https://docs.microsoft.com/en-us/windows/win32/api/winsock2/nf-winsock2-recvfrom
// Which will result in recv_from return 0.
//
// It cannot be solved here, because `WSAGetLastError` is already set.
//
// See `relay::udprelay::utils::create_udp_socket` for more detail.
continue;
}
// Check or (re)create an association
let res = assoc_manager
.send_packet(src.to_string(), forward_target.clone(), pkt.to_vec(), async {
// Pick a server
let server = balancer.pick_server();
let sender = ProxyHandler::new(src, assoc_manager.clone(), w.clone());
ProxyAssociation::associate_with_acl(src, server, sender).await
})
.await;
if let Err(err) = res {
debug!("failed to create UDP association, {}", err);
}
}
}
|
use crate::{
mock::{Origin, ProviderMembers, TestProvider, USD_ASSET},
Balance, Call, Module, Trait,
};
use alloc::{boxed::Box, vec, vec::Vec};
use frame_benchmarking::{benchmarks, whitelisted_caller};
use frame_system::{offchain::SigningTypes, RawOrigin};
use vln_commons::{
runtime::{AccountId, Signature},
Asset, Collateral, Destination, PairPrice,
};
benchmarks! {
where_clause {
where
<T as frame_system::Trait>::AccountId: AsRef<[u8; 32]>,
<T as SigningTypes>::Signature: From<Signature>,
<T as SigningTypes>::Signature: Default
}
_ {}
attest {
let origin = gen_member_and_attest::<T>(USD_ASSET);
let balance = Balance::<T>::from(100u32);
}: attest(RawOrigin::Signed(origin), Asset::Collateral(Collateral::Usd), balance, Vec::new())
verify {
}
members {
let (origin, _) = gen_member::<T>();
}: members(RawOrigin::Signed(origin))
verify {
}
submit_pair_prices {
let pair_prices = vec![
PairPrice::new([Asset::Btc, Asset::Collateral(Collateral::Usd)], 7u32.into(), 8u32.into()),
PairPrice::new([Asset::Btc, Asset::Ves], 9u32.into(), 10u32.into()),
PairPrice::new([Asset::Collateral(Collateral::Usd), Asset::Cop], 11u32.into(), 12u32.into()),
];
}: submit_pair_prices(RawOrigin::None, pair_prices, Default::default())
verify {
}
transfer {
let from = gen_member_and_attest::<T>(USD_ASSET);
let to: T::AccountId = whitelisted_caller();
let to_amount = Balance::<T>::from(100u32);
}: transfer(RawOrigin::Signed(from), Destination::Vln(to), to_amount)
verify {
}
update_offer_rates {
let from = gen_member_and_attest::<T>(USD_ASSET);
}: update_offer_rates(RawOrigin::Signed(from), Asset::Btc, Vec::new())
verify {
}
}
fn gen_member<T>() -> (T::AccountId, AccountId)
where
<T as frame_system::Trait>::AccountId: AsRef<[u8; 32]>,
T: Trait,
{
let from: T::AccountId = whitelisted_caller();
let from_public = AccountId::from_raw(*from.as_ref());
ProviderMembers::add_member(Origin::root(), from_public).unwrap();
(from, from_public)
}
fn gen_member_and_attest<T>(asset: Asset) -> T::AccountId
where
<T as frame_system::Trait>::AccountId: AsRef<[u8; 32]>,
T: Trait,
{
let (from, from_public) = gen_member::<T>();
TestProvider::attest(Origin::signed(from_public), asset, 100, Default::default()).unwrap();
from
}
#[cfg(test)]
mod tests {
use crate::{
benchmarks::{
test_benchmark_attest, test_benchmark_transfer, test_benchmark_update_offer_rates,
},
mock::Test,
tests::new_test_ext,
};
use frame_support::assert_ok;
#[test]
fn benchmarks_generate_unit_tests() {
new_test_ext().execute_with(|| {
assert_ok!(test_benchmark_attest::<Test>());
assert_ok!(test_benchmark_transfer::<Test>());
assert_ok!(test_benchmark_update_offer_rates::<Test>());
});
}
}
|
use super::error_types::XpsError;
use super::loader::open;
use super::types;
use std::alloc::{dealloc, Layout};
use std::ffi::CStr;
use std::os::raw::c_char;
use std::ptr;
#[repr(C)]
pub struct Vector3 {
x: f32,
y: f32,
z: f32,
}
#[repr(C)]
pub struct Vector2 {
x: f32,
y: f32,
}
#[repr(C)]
pub struct Color {
x: u8,
y: u8,
z: u8,
w: u8,
}
#[no_mangle]
pub extern "C" fn xps_load_model(
filename: *const c_char,
bone_naming_format: super::bone_naming::BoneNaming,
flip_uv: i32,
reverse_winding: i32,
) -> Box<types::Data> {
let c_str = unsafe { CStr::from_ptr(filename) };
let boxed = match c_str.to_str() {
Ok(s) => match open(
s,
bone_naming_format,
if flip_uv == 0 { false } else { true },
if reverse_winding == 0 { false } else { true },
) {
Ok(x) => Box::new(x),
Err(x) => {
let mut data = types::Data::default();
data.error = x;
Box::new(data)
}
},
Err(_) => Box::new(types::Data::default()),
};
return boxed;
}
#[no_mangle]
pub extern "C" fn xps_get_error(model: *mut types::Data) -> XpsError {
let mut _model = unsafe { &mut *model };
_model.error
}
#[no_mangle]
pub extern "C" fn xps_delete_model(model: Box<types::Data>) {
let p = Box::into_raw(model);
unsafe {
ptr::drop_in_place(p);
dealloc(p as *mut u8, Layout::new::<types::Data>());
}
}
#[no_mangle]
pub extern "C" fn xps_get_mesh_count(model: *mut types::Data) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes.len() as i32
}
#[no_mangle]
pub extern "C" fn xps_get_bone_count(model: *mut types::Data) -> i32 {
let mut _model = unsafe { &mut *model };
_model.bones.len() as i32
}
#[no_mangle]
pub extern "C" fn xps_get_bone_name(model: *mut types::Data, index: i32) -> *const c_char {
let mut _model = unsafe { &mut *model };
_model.bones[index as usize].name.as_ptr()
}
#[no_mangle]
pub extern "C" fn xps_get_bone_parent_id(model: *mut types::Data, index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
_model.bones[index as usize].parent_id as i32
}
#[no_mangle]
pub extern "C" fn xps_get_bone_position(model: *mut types::Data, index: i32) -> Vector3 {
let mut _model = unsafe { &mut *model };
Vector3 {
x: _model.bones[index as usize].co[0],
y: _model.bones[index as usize].co[1],
z: _model.bones[index as usize].co[2],
}
}
#[no_mangle]
pub extern "C" fn xps_get_mesh_name(model: *mut types::Data, mesh_index: i32) -> *const c_char {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].name.as_ptr()
}
#[no_mangle]
pub extern "C" fn xps_get_uv_layers(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].uv_count as i32
}
#[no_mangle]
pub extern "C" fn xps_get_vertex_count(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].vertices.len() as i32
}
#[no_mangle]
pub extern "C" fn xps_get_texture_count(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].textures.len() as i32
}
#[no_mangle]
pub extern "C" fn xps_get_texture_id(
model: *mut types::Data,
mesh_index: i32,
texture_index: i32,
) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].textures[texture_index as usize].id as i32
}
#[no_mangle]
pub extern "C" fn xps_get_texture_filename(
model: *mut types::Data,
mesh_index: i32,
texture_index: i32,
) -> *const c_char {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].textures[texture_index as usize]
.file
.as_ptr()
}
#[no_mangle]
pub extern "C" fn xps_get_texture_uv_layer(
model: *mut types::Data,
mesh_index: i32,
texture_index: i32,
) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].textures[texture_index as usize].uv_layer as i32
}
#[no_mangle]
pub extern "C" fn xps_get_mesh_index_count(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].faces.len() as i32
}
#[no_mangle]
pub extern "C" fn xps_get_mesh_index(
model: *mut types::Data,
mesh_index: i32,
index_num: i32,
) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].faces[index_num as usize] as i32
}
#[no_mangle]
pub extern "C" fn xps_get_vertex_position(
model: *mut types::Data,
mesh_index: i32,
vertex_index: i32,
) -> Vector3 {
let mut _model = unsafe { &mut *model };
Vector3 {
x: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].position[0],
y: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].position[1],
z: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].position[2],
}
}
#[no_mangle]
pub extern "C" fn xps_get_vertex_normal(
model: *mut types::Data,
mesh_index: i32,
vertex_index: i32,
) -> Vector3 {
let mut _model = unsafe { &mut *model };
Vector3 {
x: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].normal[0],
y: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].normal[1],
z: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].normal[2],
}
}
#[no_mangle]
pub extern "C" fn xps_get_vertex_color(
model: *mut types::Data,
mesh_index: i32,
vertex_index: i32,
) -> Color {
let mut _model = unsafe { &mut *model };
Color {
x: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].color[0],
y: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].color[1],
z: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].color[2],
w: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].color[3],
}
}
#[no_mangle]
pub extern "C" fn xps_get_vertex_uv(
model: *mut types::Data,
mesh_index: i32,
vertex_index: i32,
layer_id: i32,
) -> Vector2 {
let mut _model = unsafe { &mut *model };
Vector2 {
x: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].uv[layer_id as usize]
[0],
y: _model.meshes[mesh_index as usize].vertices[vertex_index as usize].uv[layer_id as usize]
[1],
}
}
#[no_mangle]
pub extern "C" fn xps_get_vertex_bone_index(
model: *mut types::Data,
mesh_index: i32,
vertex_index: i32,
weight_id: i32,
) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].vertices[vertex_index as usize].bone_weights
[weight_id as usize]
.id as i32
}
#[no_mangle]
pub extern "C" fn xps_get_vertex_bone_weight(
model: *mut types::Data,
mesh_index: i32,
vertex_index: i32,
weight_id: i32,
) -> f32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].vertices[vertex_index as usize].bone_weights
[weight_id as usize]
.weight
}
#[no_mangle]
fn xps_get_render_group_alpha(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
if _model.meshes[mesh_index as usize].render_group.alpha {
1
} else {
0
}
}
#[no_mangle]
fn xps_get_render_group_posable(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
if _model.meshes[mesh_index as usize].render_group.posable {
1
} else {
0
}
}
#[no_mangle]
fn xps_get_render_group_bump1_rep(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
if _model.meshes[mesh_index as usize].render_group.bump1_rep {
1
} else {
0
}
}
#[no_mangle]
fn xps_get_render_group_bump2_rep(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
if _model.meshes[mesh_index as usize].render_group.bump2_rep {
1
} else {
0
}
}
#[no_mangle]
fn xps_get_render_group_spec1_rep(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
if _model.meshes[mesh_index as usize].render_group.spec1_rep {
1
} else {
0
}
}
#[no_mangle]
fn xps_get_render_group_texture_count(model: *mut types::Data, mesh_index: i32) -> i32 {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize].render_group.tex_count
}
#[no_mangle]
fn xps_get_render_group_texture_type(
model: *mut types::Data,
mesh_index: i32,
texture_type_index: i32,
) -> *const c_char {
let mut _model = unsafe { &mut *model };
_model.meshes[mesh_index as usize]
.render_group
.texture_types[texture_type_index as usize]
.as_ptr()
}
|
use core::cmp::{Eq, Ord};
use std::list;
use std::list::{List, Cons, Nil};
/**
* A purely functional Pairing Heap [FSST86]
*
* Our implementation uses Linked List (cons cells) so may not be the
* fastest way to implement this in Rust.
*
* This implementation is a port of the Standard ML found in Okasaki's
* Purely Functional Data Structures.
*/
#[deriving_eq]
pub enum PairingHeap<E: Copy Eq Ord> {
Empty_,
PairingHeapCell(
E,
@List<PairingHeap<E>>
)
}
pub trait Heap<E: Copy Eq Ord> {
// returns true if the Heap is empty.
pure fn is_empty(&self) -> bool;
// returns a new Heap with the element inserted.
pure fn insert(elem: E) -> self;
// returns the minimum element without a modified heap
pure fn find_min() -> Option<E>;
// returns the minimum element and a new Heap without that element.
pure fn delete_min() -> (Option<E>, self);
}
pure fn Empty<E: Copy Eq Ord>() -> PairingHeap<E> {
Empty_
}
pure fn PairingHeap<E: Copy Eq Ord>(initial_value: E) -> PairingHeap<E> {
PairingHeapCell(
initial_value,
@Nil
)
}
/*
impl<E: Copy Eq Ord> PairingHeap<E> : Eq {
pure fn eq(other: &PairingHeap<E>) -> bool {
match (self, *other) {
(Empty_, Empty_) => {true}
(PairingHeapCell(headA, restA), PairingHeapCell(headB, restB)) => {
(headA == headB) && (restA == restB)
}
//(Empty_, PairingHeapCell(_)) => {false} // why are these unreachable?
//(PairingHeapCell(_), Empty) => {false}
(_, _) => {false}
}
}
pure fn ne(other: &PairingHeap<E>) -> bool { !(self).eq(other) }
}*/
impl<E: Copy Eq Ord> PairingHeap<E> {
pure fn merge(other: PairingHeap<E>) -> PairingHeap<E> {
match (self, other) {
(Empty_, b) => { b }
(a, Empty_) => { a }
(x@PairingHeapCell(headA, restA), y@PairingHeapCell(headB, restB)) => {
if (headA.le(&headB)) {
PairingHeapCell(
headA,
@Cons(y, restA)
)
} else {
PairingHeapCell(
headB,
@Cons(x, restB)
)
}
}
}
}
pure fn merge_pairs(heaps: @List<PairingHeap<E>>) -> PairingHeap<E> {
match heaps {
@Cons(a, @Cons(b, xs)) => {a.merge(b).merge(self.merge_pairs(xs))}
@Cons(elem, @Nil) => {elem}
@Nil => {Empty()}
}
}
}
impl<E: Copy Eq Ord> PairingHeap<E> : Heap<E> {
pure fn is_empty(&self) -> bool {
*self == Empty_
}
pure fn insert(e: E) -> PairingHeap<E> {
self.merge(PairingHeap(e))
}
pure fn find_min() -> Option<E> {
match self {
Empty_ => { None }
PairingHeapCell(head, _) => { Some(head) }
}
}
pure fn delete_min() -> (Option<E>, PairingHeap<E>) {
match self {
Empty_ => {(None, self)}
PairingHeapCell(head, rest) => {(Some(head), self.merge_pairs(rest))}
}
}
}
#[test]
fn test_heap_create() {
let heap = PairingHeap(1);
assert(!heap.is_empty());
// inference fails on this without a type declaration.
let heap : PairingHeap<()> = Empty();
assert(heap.is_empty());
}
#[test]
fn test_delete_last_item() {
let v1 = PairingHeap(1);
assert(!v1.is_empty());
let (_, v2) = v1.delete_min();
assert(v2.is_empty());
}
#[test]
fn test_heap_insert() {
let v1 = PairingHeap(10);
let v2 = v1.insert(1);
let (one, v3) = v2.delete_min();
let (ten, v4) = v3.delete_min();
let (e, v5) = v4.delete_min();
assert(one == Some(1));
assert(ten == Some(10));
assert(v4 == Empty_);
assert(e == None);
assert(v5 == Empty_);
}
#[test]
fn test_heap_insert_delete_interleaved() {
let v1 = PairingHeap(10);
let (a, v2) = v1.delete_min();
assert(a == Some(10));
assert(v2 == Empty_);
let v3 = v2.insert(9);
let v4 = v3.insert(8);
let v5 = v4.insert(11);
let (b, v6) = v5.delete_min();
assert(b == Some(8));
let v7 = v6.insert(7);
let v8 = v7.insert(12);
let x = v8.find_min();
assert(x == Some(7));
let (c, v9) = v8.delete_min();
assert(c == Some(7));
let (d, v10) = v9.delete_min();
assert(d == Some(9));
let (e, v11) = v10.delete_min();
assert(e == Some(11));
let (f, v12) = v11.delete_min();
assert(f == Some(12));
let (g, v13) = v12.delete_min();
assert(g == None);
assert(v13 == Empty_);
}
#[test]
fn test_immutable_heap() {
let heap = PairingHeap(10);
let x1 = heap.insert(1);
assert(x1.find_min() == Some(1));
assert(heap.find_min() == Some(10));
let (a, v1) = heap.delete_min();
assert(a == Some(10));
assert(v1 == Empty_);
let (b, x2) = x1.delete_min();
assert(b == Some(1));
assert(x2 != Empty_);
}
|
use std::default::Default;
use std::ops::Sub;
use std::time::Duration;
pub trait Pacer {
/// fn pace(&self, elapsed: Duration, hits: u64) -> (wait: Duration, stop: bool)
fn pace(&self, elapsed: Duration, hits: u64) -> (Duration, bool);
fn rate(&self, elapsed: Duration) -> f64;
}
#[derive(Clone, Debug, PartialEq)]
pub struct Rate {
pub freq: u64,
pub per: Duration,
}
impl Default for Rate {
fn default() -> Self {
Self {
freq: 1,
per: Duration::from_secs(1),
}
}
}
impl Pacer for Rate {
fn pace(&self, elapsed: Duration, hits: u64) -> (Duration, bool) {
let immediately = Duration::from_secs(0);
if self.freq == 0 || self.per == immediately {
return (immediately, false);
} else if self.per < immediately {
return (immediately, true);
}
let n = elapsed.as_nanos() / self.per.as_nanos();
let expected = self.freq as u64 * n as u64;
if hits < expected {
return (immediately, false);
}
let interval = self.per.as_nanos() / self.freq as u128;
let delta = Duration::from_nanos((hits + 1) * interval as u64);
if delta < elapsed {
return (immediately, false);
}
(delta.sub(elapsed), false)
}
fn rate(&self, _elapsed: Duration) -> f64 {
self.freq as f64 / self.per.as_nanos() as f64 * 1e9
}
}
#[cfg(test)]
mod tests {
fn float_eq(x: f64, y: f64) -> bool {
println!("{} {}", x, y);
let marg = 1e-6 * x.abs().min(y.abs());
(x - y).abs() <= marg.max(1e-6)
}
use crate::pace::Pacer;
use std::time::Duration;
#[test]
fn pacer_pace_test() {
let sec = Duration::from_secs(1);
let immediately = Duration::from_secs(0);
let table = vec![
((1, sec), (1 * sec, 0), (immediately, false)),
((1, sec), (2 * sec, 0), (immediately, false)),
((1, sec), (1 * sec, 1), (sec, false)),
((1, sec), (1 * sec, 2), (2 * sec, false)),
((1, sec), (1 * sec, 10), (10 * sec, false)),
((1, sec), (11 * sec, 10), (immediately, false)),
(
(2, sec),
(49 * sec / 10, 9),
(Duration::from_millis(100), false),
),
((0, sec), (sec, 0), (immediately, false)),
((1, Duration::from_secs(0)), (sec, 0), (immediately, false)),
((0, Duration::from_secs(0)), (sec, 0), (immediately, false)),
];
for ((freq, per), (elapsed, hits), (wait, stop)) in table {
let r = super::Rate { freq, per };
let (gwait, gstop) = r.pace(elapsed, hits);
assert_eq!(gstop, stop);
assert_eq!(gwait, wait);
}
}
#[test]
fn pacer_rate_test() {
let sec = Duration::from_secs(1);
let min = sec * 60;
let table = vec![
((60, 1 * min), 1.0),
((120, 1 * min), 2.0),
((30, 1 * min), 0.5),
((500, 1 * sec), 500.0),
];
for ((freq, per), expected) in table {
let r = super::Rate { freq, per };
let have = r.rate(Duration::from_secs(0));
assert!(float_eq(have, expected));
}
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_base::base::tokio;
use common_base::base::tokio::sync::mpsc::channel;
use common_base::base::tokio::sync::mpsc::Receiver;
use common_base::base::tokio::sync::mpsc::Sender;
use common_exception::Result;
use common_expression::DataBlock;
use common_pipeline_core::pipe::Pipe;
use common_pipeline_core::pipe::PipeItem;
use common_pipeline_core::processors::processor::ProcessorPtr;
use common_pipeline_sinks::SyncSenderSink;
use common_pipeline_sources::SyncReceiverSource;
use common_pipeline_transforms::processors::transforms::TransformDummy;
use databend_query::pipelines::executor::RunningGraph;
use databend_query::pipelines::processors::port::InputPort;
use databend_query::pipelines::processors::port::OutputPort;
use databend_query::pipelines::Pipeline;
use databend_query::sessions::QueryContext;
use crate::tests::create_query_context;
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_create_simple_pipeline() -> Result<()> {
let (_guard, ctx) = create_query_context().await?;
assert_eq!(
format!("{:?}", create_simple_pipeline(ctx)?),
"digraph {\
\n 0 [ label = \"SyncReceiverSource\" ]\
\n 1 [ label = \"DummyTransform\" ]\
\n 2 [ label = \"SyncSenderSink\" ]\
\n 0 -> 1 [ ]\
\n 1 -> 2 [ ]\
\n}\n"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_create_parallel_simple_pipeline() -> Result<()> {
let (_guard, ctx) = create_query_context().await?;
assert_eq!(
format!("{:?}", create_parallel_simple_pipeline(ctx)?),
"digraph {\
\n 0 [ label = \"SyncReceiverSource\" ]\
\n 1 [ label = \"SyncReceiverSource\" ]\
\n 2 [ label = \"DummyTransform\" ]\
\n 3 [ label = \"DummyTransform\" ]\
\n 4 [ label = \"SyncSenderSink\" ]\
\n 5 [ label = \"SyncSenderSink\" ]\
\n 0 -> 2 [ ]\
\n 1 -> 3 [ ]\
\n 2 -> 4 [ ]\
\n 3 -> 5 [ ]\
\n}\n"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_create_resize_pipeline() -> Result<()> {
let (_guard, ctx) = create_query_context().await?;
assert_eq!(
format!("{:?}", create_resize_pipeline(ctx)?),
"digraph {\
\n 0 [ label = \"SyncReceiverSource\" ]\
\n 1 [ label = \"Resize\" ]\
\n 2 [ label = \"DummyTransform\" ]\
\n 3 [ label = \"DummyTransform\" ]\
\n 4 [ label = \"Resize\" ]\
\n 5 [ label = \"DummyTransform\" ]\
\n 6 [ label = \"Resize\" ]\
\n 7 [ label = \"SyncSenderSink\" ]\
\n 8 [ label = \"SyncSenderSink\" ]\
\n 0 -> 1 [ ]\
\n 1 -> 2 [ ]\
\n 1 -> 3 [ ]\
\n 2 -> 4 [ ]\
\n 3 -> 4 [ ]\
\n 4 -> 5 [ ]\
\n 5 -> 6 [ ]\
\n 6 -> 7 [ ]\
\n 6 -> 8 [ ]\
\n}\n"
);
Ok(())
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_simple_pipeline_init_queue() -> Result<()> {
let (_guard, ctx) = create_query_context().await?;
unsafe {
assert_eq!(
format!("{:?}", create_simple_pipeline(ctx)?.init_schedule_queue(0)?),
"ScheduleQueue { \
sync_queue: [\
QueueItem { id: 2, name: \"SyncSenderSink\" }\
], \
async_queue: [] \
}"
);
Ok(())
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_parallel_simple_pipeline_init_queue() -> Result<()> {
let (_guard, ctx) = create_query_context().await?;
unsafe {
assert_eq!(
format!(
"{:?}",
create_parallel_simple_pipeline(ctx)?.init_schedule_queue(0)?
),
"ScheduleQueue { \
sync_queue: [\
QueueItem { id: 4, name: \"SyncSenderSink\" }, \
QueueItem { id: 5, name: \"SyncSenderSink\" }\
], \
async_queue: [] \
}"
);
Ok(())
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 1)]
async fn test_resize_pipeline_init_queue() -> Result<()> {
let (_guard, ctx) = create_query_context().await?;
unsafe {
assert_eq!(
format!("{:?}", create_resize_pipeline(ctx)?.init_schedule_queue(0)?),
"ScheduleQueue { \
sync_queue: [\
QueueItem { id: 7, name: \"SyncSenderSink\" }, \
QueueItem { id: 8, name: \"SyncSenderSink\" }\
], \
async_queue: [] \
}"
);
Ok(())
}
}
fn create_simple_pipeline(ctx: Arc<QueryContext>) -> Result<RunningGraph> {
let (_rx, sink_pipe) = create_sink_pipe(1)?;
let (_tx, source_pipe) = create_source_pipe(ctx, 1)?;
let mut pipeline = Pipeline::create();
pipeline.add_pipe(source_pipe);
pipeline.add_pipe(create_transform_pipe(1)?);
pipeline.add_pipe(sink_pipe);
RunningGraph::create(pipeline)
}
fn create_parallel_simple_pipeline(ctx: Arc<QueryContext>) -> Result<RunningGraph> {
let (_rx, sink_pipe) = create_sink_pipe(2)?;
let (_tx, source_pipe) = create_source_pipe(ctx, 2)?;
let mut pipeline = Pipeline::create();
pipeline.add_pipe(source_pipe);
pipeline.add_pipe(create_transform_pipe(2)?);
pipeline.add_pipe(sink_pipe);
RunningGraph::create(pipeline)
}
fn create_resize_pipeline(ctx: Arc<QueryContext>) -> Result<RunningGraph> {
let (_rx, sink_pipe) = create_sink_pipe(2)?;
let (_tx, source_pipe) = create_source_pipe(ctx, 1)?;
let mut pipeline = Pipeline::create();
pipeline.add_pipe(source_pipe);
pipeline.resize(2)?;
pipeline.add_pipe(create_transform_pipe(2)?);
pipeline.resize(1)?;
pipeline.add_pipe(create_transform_pipe(1)?);
pipeline.resize(2)?;
pipeline.add_pipe(sink_pipe);
RunningGraph::create(pipeline)
}
fn create_source_pipe(
ctx: Arc<QueryContext>,
size: usize,
) -> Result<(Vec<Sender<Result<DataBlock>>>, Pipe)> {
let mut txs = Vec::with_capacity(size);
let mut items = Vec::with_capacity(size);
for _index in 0..size {
let output = OutputPort::create();
let (tx, rx) = channel(1);
txs.push(tx);
items.push(PipeItem::create(
SyncReceiverSource::create(ctx.clone(), rx, output.clone())?,
vec![],
vec![output],
));
}
Ok((txs, Pipe::create(0, size, items)))
}
fn create_transform_pipe(size: usize) -> Result<Pipe> {
let mut items = Vec::with_capacity(size);
for _index in 0..size {
let input = InputPort::create();
let output = OutputPort::create();
items.push(PipeItem::create(
TransformDummy::create(input.clone(), output.clone()),
vec![input],
vec![output],
));
}
Ok(Pipe::create(size, size, items))
}
fn create_sink_pipe(size: usize) -> Result<(Vec<Receiver<Result<DataBlock>>>, Pipe)> {
let mut rxs = Vec::with_capacity(size);
let mut items = Vec::with_capacity(size);
for _index in 0..size {
let input = InputPort::create();
let (tx, rx) = channel(1);
rxs.push(rx);
items.push(PipeItem::create(
ProcessorPtr::create(SyncSenderSink::create(tx, input.clone())),
vec![input],
vec![],
));
}
Ok((rxs, Pipe::create(size, 0, items)))
}
|
#![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 CurrencyFormatter(pub ::windows::core::IInspectable);
impl CurrencyFormatter {
pub fn Currency(&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__)
}
}
#[cfg(feature = "deprecated")]
pub fn SetCurrency<'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() }
}
pub fn Mode(&self) -> ::windows::core::Result<CurrencyFormatterMode> {
let this = &::windows::core::Interface::cast::<ICurrencyFormatter2>(self)?;
unsafe {
let mut result__: CurrencyFormatterMode = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<CurrencyFormatterMode>(result__)
}
}
pub fn SetMode(&self, value: CurrencyFormatterMode) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ICurrencyFormatter2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn ApplyRoundingForCurrency(&self, roundingalgorithm: RoundingAlgorithm) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ICurrencyFormatter2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), roundingalgorithm).ok() }
}
pub fn FormatInt(&self, value: i64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt(&self, value: u64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble(&self, value: f64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatInt2(&self, value: i64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt2(&self, value: u64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble2(&self, value: f64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Languages(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(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<::windows::core::HSTRING>>(result__)
}
}
pub fn GeographicRegion(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IntegerDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetIntegerDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn FractionDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetFractionDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsGrouped(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsGrouped(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsDecimalPointAlwaysDisplayed(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsDecimalPointAlwaysDisplayed(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn NumeralSystem(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetNumeralSystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn ResolvedLanguage(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ResolvedGeographicRegion(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<i64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<i64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseUInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<u64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseDouble<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<f64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<f64>>(result__)
}
}
pub fn NumberRounder(&self) -> ::windows::core::Result<INumberRounder> {
let this = &::windows::core::Interface::cast::<INumberRounderOption>(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::<INumberRounder>(result__)
}
}
pub fn SetNumberRounder<'a, Param0: ::windows::core::IntoParam<'a, INumberRounder>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberRounderOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn IsZeroSigned(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ISignedZeroOption>(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 SetIsZeroSigned(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignedZeroOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn SignificantDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsOption>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetSignificantDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn CreateCurrencyFormatterCode<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(currencycode: Param0) -> ::windows::core::Result<CurrencyFormatter> {
Self::ICurrencyFormatterFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), currencycode.into_param().abi(), &mut result__).from_abi::<CurrencyFormatter>(result__)
})
}
#[cfg(feature = "Foundation_Collections")]
pub fn CreateCurrencyFormatterCodeContext<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>, Param1: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(currencycode: Param0, languages: Param1, geographicregion: Param2) -> ::windows::core::Result<CurrencyFormatter> {
Self::ICurrencyFormatterFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), currencycode.into_param().abi(), languages.into_param().abi(), geographicregion.into_param().abi(), &mut result__).from_abi::<CurrencyFormatter>(result__)
})
}
pub fn ICurrencyFormatterFactory<R, F: FnOnce(&ICurrencyFormatterFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<CurrencyFormatter, ICurrencyFormatterFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for CurrencyFormatter {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.NumberFormatting.CurrencyFormatter;{11730ca5-4b00-41b2-b332-73b12a497d54})");
}
unsafe impl ::windows::core::Interface for CurrencyFormatter {
type Vtable = ICurrencyFormatter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x11730ca5_4b00_41b2_b332_73b12a497d54);
}
impl ::windows::core::RuntimeName for CurrencyFormatter {
const NAME: &'static str = "Windows.Globalization.NumberFormatting.CurrencyFormatter";
}
impl ::core::convert::From<CurrencyFormatter> for ::windows::core::IUnknown {
fn from(value: CurrencyFormatter) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&CurrencyFormatter> for ::windows::core::IUnknown {
fn from(value: &CurrencyFormatter) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for CurrencyFormatter {
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 CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<CurrencyFormatter> for ::windows::core::IInspectable {
fn from(value: CurrencyFormatter) -> Self {
value.0
}
}
impl ::core::convert::From<&CurrencyFormatter> for ::windows::core::IInspectable {
fn from(value: &CurrencyFormatter) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for CurrencyFormatter {
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 CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<CurrencyFormatter> for INumberFormatter {
type Error = ::windows::core::Error;
fn try_from(value: CurrencyFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&CurrencyFormatter> for INumberFormatter {
type Error = ::windows::core::Error;
fn try_from(value: &CurrencyFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter> for CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter> for &CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter> {
::core::convert::TryInto::<INumberFormatter>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<CurrencyFormatter> for INumberFormatter2 {
type Error = ::windows::core::Error;
fn try_from(value: CurrencyFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&CurrencyFormatter> for INumberFormatter2 {
type Error = ::windows::core::Error;
fn try_from(value: &CurrencyFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter2> for CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter2> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter2> for &CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter2> {
::core::convert::TryInto::<INumberFormatter2>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<CurrencyFormatter> for INumberFormatterOptions {
type Error = ::windows::core::Error;
fn try_from(value: CurrencyFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&CurrencyFormatter> for INumberFormatterOptions {
type Error = ::windows::core::Error;
fn try_from(value: &CurrencyFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatterOptions> for CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatterOptions> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatterOptions> for &CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatterOptions> {
::core::convert::TryInto::<INumberFormatterOptions>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<CurrencyFormatter> for INumberParser {
type Error = ::windows::core::Error;
fn try_from(value: CurrencyFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&CurrencyFormatter> for INumberParser {
type Error = ::windows::core::Error;
fn try_from(value: &CurrencyFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberParser> for CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberParser> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberParser> for &CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberParser> {
::core::convert::TryInto::<INumberParser>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<CurrencyFormatter> for INumberRounderOption {
type Error = ::windows::core::Error;
fn try_from(value: CurrencyFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&CurrencyFormatter> for INumberRounderOption {
type Error = ::windows::core::Error;
fn try_from(value: &CurrencyFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounderOption> for CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounderOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounderOption> for &CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounderOption> {
::core::convert::TryInto::<INumberRounderOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<CurrencyFormatter> for ISignedZeroOption {
type Error = ::windows::core::Error;
fn try_from(value: CurrencyFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&CurrencyFormatter> for ISignedZeroOption {
type Error = ::windows::core::Error;
fn try_from(value: &CurrencyFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignedZeroOption> for CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignedZeroOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignedZeroOption> for &CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignedZeroOption> {
::core::convert::TryInto::<ISignedZeroOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<CurrencyFormatter> for ISignificantDigitsOption {
type Error = ::windows::core::Error;
fn try_from(value: CurrencyFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&CurrencyFormatter> for ISignificantDigitsOption {
type Error = ::windows::core::Error;
fn try_from(value: &CurrencyFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignificantDigitsOption> for CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignificantDigitsOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignificantDigitsOption> for &CurrencyFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignificantDigitsOption> {
::core::convert::TryInto::<ISignificantDigitsOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for CurrencyFormatter {}
unsafe impl ::core::marker::Sync for CurrencyFormatter {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct CurrencyFormatterMode(pub i32);
impl CurrencyFormatterMode {
pub const UseSymbol: CurrencyFormatterMode = CurrencyFormatterMode(0i32);
pub const UseCurrencyCode: CurrencyFormatterMode = CurrencyFormatterMode(1i32);
}
impl ::core::convert::From<i32> for CurrencyFormatterMode {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for CurrencyFormatterMode {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for CurrencyFormatterMode {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Globalization.NumberFormatting.CurrencyFormatterMode;i4)");
}
impl ::windows::core::DefaultType for CurrencyFormatterMode {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct DecimalFormatter(pub ::windows::core::IInspectable);
impl DecimalFormatter {
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<DecimalFormatter, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn FormatInt(&self, value: i64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt(&self, value: u64) -> ::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).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble(&self, value: f64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatInt2(&self, value: i64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt2(&self, value: u64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble2(&self, value: f64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Languages(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(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<::windows::core::HSTRING>>(result__)
}
}
pub fn GeographicRegion(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IntegerDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetIntegerDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn FractionDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetFractionDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsGrouped(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsGrouped(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsDecimalPointAlwaysDisplayed(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsDecimalPointAlwaysDisplayed(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn NumeralSystem(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetNumeralSystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn ResolvedLanguage(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ResolvedGeographicRegion(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<i64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<i64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseUInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<u64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseDouble<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<f64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<f64>>(result__)
}
}
pub fn NumberRounder(&self) -> ::windows::core::Result<INumberRounder> {
let this = &::windows::core::Interface::cast::<INumberRounderOption>(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::<INumberRounder>(result__)
}
}
pub fn SetNumberRounder<'a, Param0: ::windows::core::IntoParam<'a, INumberRounder>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberRounderOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn IsZeroSigned(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ISignedZeroOption>(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 SetIsZeroSigned(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignedZeroOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn SignificantDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsOption>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetSignificantDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn CreateDecimalFormatter<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(languages: Param0, geographicregion: Param1) -> ::windows::core::Result<DecimalFormatter> {
Self::IDecimalFormatterFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languages.into_param().abi(), geographicregion.into_param().abi(), &mut result__).from_abi::<DecimalFormatter>(result__)
})
}
pub fn IDecimalFormatterFactory<R, F: FnOnce(&IDecimalFormatterFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<DecimalFormatter, IDecimalFormatterFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for DecimalFormatter {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.NumberFormatting.DecimalFormatter;{a5007c49-7676-4db7-8631-1b6ff265caa9})");
}
unsafe impl ::windows::core::Interface for DecimalFormatter {
type Vtable = INumberFormatter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa5007c49_7676_4db7_8631_1b6ff265caa9);
}
impl ::windows::core::RuntimeName for DecimalFormatter {
const NAME: &'static str = "Windows.Globalization.NumberFormatting.DecimalFormatter";
}
impl ::core::convert::From<DecimalFormatter> for ::windows::core::IUnknown {
fn from(value: DecimalFormatter) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&DecimalFormatter> for ::windows::core::IUnknown {
fn from(value: &DecimalFormatter) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for DecimalFormatter {
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 DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<DecimalFormatter> for ::windows::core::IInspectable {
fn from(value: DecimalFormatter) -> Self {
value.0
}
}
impl ::core::convert::From<&DecimalFormatter> for ::windows::core::IInspectable {
fn from(value: &DecimalFormatter) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for DecimalFormatter {
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 DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<DecimalFormatter> for INumberFormatter {
fn from(value: DecimalFormatter) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&DecimalFormatter> for INumberFormatter {
fn from(value: &DecimalFormatter) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter> for DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter> for &DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
impl ::core::convert::TryFrom<DecimalFormatter> for INumberFormatter2 {
type Error = ::windows::core::Error;
fn try_from(value: DecimalFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&DecimalFormatter> for INumberFormatter2 {
type Error = ::windows::core::Error;
fn try_from(value: &DecimalFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter2> for DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter2> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter2> for &DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter2> {
::core::convert::TryInto::<INumberFormatter2>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<DecimalFormatter> for INumberFormatterOptions {
type Error = ::windows::core::Error;
fn try_from(value: DecimalFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&DecimalFormatter> for INumberFormatterOptions {
type Error = ::windows::core::Error;
fn try_from(value: &DecimalFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatterOptions> for DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatterOptions> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatterOptions> for &DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatterOptions> {
::core::convert::TryInto::<INumberFormatterOptions>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<DecimalFormatter> for INumberParser {
type Error = ::windows::core::Error;
fn try_from(value: DecimalFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&DecimalFormatter> for INumberParser {
type Error = ::windows::core::Error;
fn try_from(value: &DecimalFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberParser> for DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberParser> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberParser> for &DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberParser> {
::core::convert::TryInto::<INumberParser>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<DecimalFormatter> for INumberRounderOption {
type Error = ::windows::core::Error;
fn try_from(value: DecimalFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&DecimalFormatter> for INumberRounderOption {
type Error = ::windows::core::Error;
fn try_from(value: &DecimalFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounderOption> for DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounderOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounderOption> for &DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounderOption> {
::core::convert::TryInto::<INumberRounderOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<DecimalFormatter> for ISignedZeroOption {
type Error = ::windows::core::Error;
fn try_from(value: DecimalFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&DecimalFormatter> for ISignedZeroOption {
type Error = ::windows::core::Error;
fn try_from(value: &DecimalFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignedZeroOption> for DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignedZeroOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignedZeroOption> for &DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignedZeroOption> {
::core::convert::TryInto::<ISignedZeroOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<DecimalFormatter> for ISignificantDigitsOption {
type Error = ::windows::core::Error;
fn try_from(value: DecimalFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&DecimalFormatter> for ISignificantDigitsOption {
type Error = ::windows::core::Error;
fn try_from(value: &DecimalFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignificantDigitsOption> for DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignificantDigitsOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignificantDigitsOption> for &DecimalFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignificantDigitsOption> {
::core::convert::TryInto::<ISignificantDigitsOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for DecimalFormatter {}
unsafe impl ::core::marker::Sync for DecimalFormatter {}
#[repr(transparent)]
#[doc(hidden)]
pub struct ICurrencyFormatter(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICurrencyFormatter {
type Vtable = ICurrencyFormatter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x11730ca5_4b00_41b2_b332_73b12a497d54);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICurrencyFormatter_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, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICurrencyFormatter2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICurrencyFormatter2 {
type Vtable = ICurrencyFormatter2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x072c2f1d_e7ba_4197_920e_247c92f7dea6);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICurrencyFormatter2_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 CurrencyFormatterMode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: CurrencyFormatterMode) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, roundingalgorithm: RoundingAlgorithm) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ICurrencyFormatterFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ICurrencyFormatterFactory {
type Vtable = ICurrencyFormatterFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x86c7537e_b938_4aa2_84b0_2c33dc5b1450);
}
#[repr(C)]
#[doc(hidden)]
pub struct ICurrencyFormatterFactory_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, currencycode: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, currencycode: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, languages: ::windows::core::RawPtr, geographicregion: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IDecimalFormatterFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IDecimalFormatterFactory {
type Vtable = IDecimalFormatterFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0d018c9a_e393_46b8_b830_7a69c8f89fbb);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDecimalFormatterFactory_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, languages: ::windows::core::RawPtr, geographicregion: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IIncrementNumberRounder(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IIncrementNumberRounder {
type Vtable = IIncrementNumberRounder_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x70a64ff8_66ab_4155_9da1_739e46764543);
}
#[repr(C)]
#[doc(hidden)]
pub struct IIncrementNumberRounder_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 RoundingAlgorithm) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: RoundingAlgorithm) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut f64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: f64) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct INumberFormatter(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumberFormatter {
type Vtable = INumberFormatter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa5007c49_7676_4db7_8631_1b6ff265caa9);
}
impl INumberFormatter {
pub fn FormatInt(&self, value: i64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt(&self, value: u64) -> ::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).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble(&self, value: f64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for INumberFormatter {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{a5007c49-7676-4db7-8631-1b6ff265caa9}");
}
impl ::core::convert::From<INumberFormatter> for ::windows::core::IUnknown {
fn from(value: INumberFormatter) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&INumberFormatter> for ::windows::core::IUnknown {
fn from(value: &INumberFormatter) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INumberFormatter {
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 INumberFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<INumberFormatter> for ::windows::core::IInspectable {
fn from(value: INumberFormatter) -> Self {
value.0
}
}
impl ::core::convert::From<&INumberFormatter> for ::windows::core::IInspectable {
fn from(value: &INumberFormatter) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INumberFormatter {
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 INumberFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct INumberFormatter_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, value: i64, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u64, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: f64, result__: *mut ::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 INumberFormatter2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumberFormatter2 {
type Vtable = INumberFormatter2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd4a8c1f0_80d0_4b0d_a89e_882c1e8f8310);
}
impl INumberFormatter2 {
pub fn FormatInt(&self, value: i64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt(&self, value: u64) -> ::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).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble(&self, value: f64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for INumberFormatter2 {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{d4a8c1f0-80d0-4b0d-a89e-882c1e8f8310}");
}
impl ::core::convert::From<INumberFormatter2> for ::windows::core::IUnknown {
fn from(value: INumberFormatter2) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&INumberFormatter2> for ::windows::core::IUnknown {
fn from(value: &INumberFormatter2) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INumberFormatter2 {
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 INumberFormatter2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<INumberFormatter2> for ::windows::core::IInspectable {
fn from(value: INumberFormatter2) -> Self {
value.0
}
}
impl ::core::convert::From<&INumberFormatter2> for ::windows::core::IInspectable {
fn from(value: &INumberFormatter2) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INumberFormatter2 {
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 INumberFormatter2 {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct INumberFormatter2_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, value: i64, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u64, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: f64, result__: *mut ::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 INumberFormatterOptions(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumberFormatterOptions {
type Vtable = INumberFormatterOptions_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x80332d21_aee1_4a39_baa2_07ed8c96daf6);
}
impl INumberFormatterOptions {
#[cfg(feature = "Foundation_Collections")]
pub fn Languages(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
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<::windows::core::HSTRING>>(result__)
}
}
pub fn GeographicRegion(&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).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IntegerDigits(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetIntegerDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn FractionDigits(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetFractionDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsGrouped(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsGrouped(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsDecimalPointAlwaysDisplayed(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsDecimalPointAlwaysDisplayed(&self, value: bool) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn NumeralSystem(&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).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetNumeralSystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn ResolvedLanguage(&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).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ResolvedGeographicRegion(&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).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for INumberFormatterOptions {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{80332d21-aee1-4a39-baa2-07ed8c96daf6}");
}
impl ::core::convert::From<INumberFormatterOptions> for ::windows::core::IUnknown {
fn from(value: INumberFormatterOptions) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&INumberFormatterOptions> for ::windows::core::IUnknown {
fn from(value: &INumberFormatterOptions) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INumberFormatterOptions {
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 INumberFormatterOptions {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<INumberFormatterOptions> for ::windows::core::IInspectable {
fn from(value: INumberFormatterOptions) -> Self {
value.0
}
}
impl ::core::convert::From<&INumberFormatterOptions> for ::windows::core::IInspectable {
fn from(value: &INumberFormatterOptions) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INumberFormatterOptions {
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 INumberFormatterOptions {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct INumberFormatterOptions_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,
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 i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: 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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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, result__: *mut ::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 INumberParser(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumberParser {
type Vtable = INumberParser_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe6659412_4a13_4a53_83a1_392fbe4cff9f);
}
impl INumberParser {
#[cfg(feature = "Foundation")]
pub fn ParseInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<i64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<i64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseUInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<u64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseDouble<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<f64>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<f64>>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for INumberParser {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{e6659412-4a13-4a53-83a1-392fbe4cff9f}");
}
impl ::core::convert::From<INumberParser> for ::windows::core::IUnknown {
fn from(value: INumberParser) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&INumberParser> for ::windows::core::IUnknown {
fn from(value: &INumberParser) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INumberParser {
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 INumberParser {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<INumberParser> for ::windows::core::IInspectable {
fn from(value: INumberParser) -> Self {
value.0
}
}
impl ::core::convert::From<&INumberParser> for ::windows::core::IInspectable {
fn from(value: &INumberParser) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INumberParser {
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 INumberParser {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct INumberParser_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, text: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, 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, text: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, 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, text: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct INumberRounder(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumberRounder {
type Vtable = INumberRounder_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5473c375_38ed_4631_b80c_ef34fc48b7f5);
}
impl INumberRounder {
pub fn RoundInt32(&self, value: i32) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<i32>(result__)
}
}
pub fn RoundUInt32(&self, value: u32) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<u32>(result__)
}
}
pub fn RoundInt64(&self, value: i64) -> ::windows::core::Result<i64> {
let this = self;
unsafe {
let mut result__: i64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<i64>(result__)
}
}
pub fn RoundUInt64(&self, value: u64) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<u64>(result__)
}
}
pub fn RoundSingle(&self, value: f32) -> ::windows::core::Result<f32> {
let this = self;
unsafe {
let mut result__: f32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<f32>(result__)
}
}
pub fn RoundDouble(&self, value: f64) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<f64>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for INumberRounder {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{5473c375-38ed-4631-b80c-ef34fc48b7f5}");
}
impl ::core::convert::From<INumberRounder> for ::windows::core::IUnknown {
fn from(value: INumberRounder) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&INumberRounder> for ::windows::core::IUnknown {
fn from(value: &INumberRounder) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INumberRounder {
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 INumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<INumberRounder> for ::windows::core::IInspectable {
fn from(value: INumberRounder) -> Self {
value.0
}
}
impl ::core::convert::From<&INumberRounder> for ::windows::core::IInspectable {
fn from(value: &INumberRounder) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INumberRounder {
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 INumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct INumberRounder_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, value: i32, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i64, result__: *mut i64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u64, result__: *mut u64) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: f32, result__: *mut f32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: f64, result__: *mut f64) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct INumberRounderOption(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumberRounderOption {
type Vtable = INumberRounderOption_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3b088433_646f_4efe_8d48_66eb2e49e736);
}
impl INumberRounderOption {
pub fn NumberRounder(&self) -> ::windows::core::Result<INumberRounder> {
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::<INumberRounder>(result__)
}
}
pub fn SetNumberRounder<'a, Param0: ::windows::core::IntoParam<'a, INumberRounder>>(&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() }
}
}
unsafe impl ::windows::core::RuntimeType for INumberRounderOption {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{3b088433-646f-4efe-8d48-66eb2e49e736}");
}
impl ::core::convert::From<INumberRounderOption> for ::windows::core::IUnknown {
fn from(value: INumberRounderOption) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&INumberRounderOption> for ::windows::core::IUnknown {
fn from(value: &INumberRounderOption) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for INumberRounderOption {
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 INumberRounderOption {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<INumberRounderOption> for ::windows::core::IInspectable {
fn from(value: INumberRounderOption) -> Self {
value.0
}
}
impl ::core::convert::From<&INumberRounderOption> for ::windows::core::IInspectable {
fn from(value: &INumberRounderOption) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for INumberRounderOption {
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 INumberRounderOption {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct INumberRounderOption_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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct INumeralSystemTranslator(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumeralSystemTranslator {
type Vtable = INumeralSystemTranslator_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x28f5bc2c_8c23_4234_ad2e_fa5a3a426e9b);
}
#[repr(C)]
#[doc(hidden)]
pub struct INumeralSystemTranslator_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,
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, value: ::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>, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct INumeralSystemTranslatorFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for INumeralSystemTranslatorFactory {
type Vtable = INumeralSystemTranslatorFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x9630c8da_36ef_4d88_a85c_6f0d98d620a6);
}
#[repr(C)]
#[doc(hidden)]
pub struct INumeralSystemTranslatorFactory_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, languages: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPercentFormatterFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPercentFormatterFactory {
type Vtable = IPercentFormatterFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb7828aef_fed4_4018_a6e2_e09961e03765);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPercentFormatterFactory_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, languages: ::windows::core::RawPtr, geographicregion: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IPermilleFormatterFactory(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IPermilleFormatterFactory {
type Vtable = IPermilleFormatterFactory_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2b37b4ac_e638_4ed5_a998_62f6b06a49ae);
}
#[repr(C)]
#[doc(hidden)]
pub struct IPermilleFormatterFactory_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, languages: ::windows::core::RawPtr, geographicregion: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISignedZeroOption(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISignedZeroOption {
type Vtable = ISignedZeroOption_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xfd1cdd31_0a3c_49c4_a642_96a1564f4f30);
}
impl ISignedZeroOption {
pub fn IsZeroSigned(&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 SetIsZeroSigned(&self, value: bool) -> ::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 ISignedZeroOption {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{fd1cdd31-0a3c-49c4-a642-96a1564f4f30}");
}
impl ::core::convert::From<ISignedZeroOption> for ::windows::core::IUnknown {
fn from(value: ISignedZeroOption) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISignedZeroOption> for ::windows::core::IUnknown {
fn from(value: &ISignedZeroOption) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISignedZeroOption {
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 ISignedZeroOption {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISignedZeroOption> for ::windows::core::IInspectable {
fn from(value: ISignedZeroOption) -> Self {
value.0
}
}
impl ::core::convert::From<&ISignedZeroOption> for ::windows::core::IInspectable {
fn from(value: &ISignedZeroOption) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISignedZeroOption {
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 ISignedZeroOption {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISignedZeroOption_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ISignificantDigitsNumberRounder(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISignificantDigitsNumberRounder {
type Vtable = ISignificantDigitsNumberRounder_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf5941bca_6646_4913_8c76_1b191ff94dfd);
}
#[repr(C)]
#[doc(hidden)]
pub struct ISignificantDigitsNumberRounder_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 RoundingAlgorithm) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: RoundingAlgorithm) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ISignificantDigitsOption(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ISignificantDigitsOption {
type Vtable = ISignificantDigitsOption_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1d4dfcdd_2d43_4ee8_bbf1_c1b26a711a58);
}
impl ISignificantDigitsOption {
pub fn SignificantDigits(&self) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetSignificantDigits(&self, value: i32) -> ::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 ISignificantDigitsOption {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{1d4dfcdd-2d43-4ee8-bbf1-c1b26a711a58}");
}
impl ::core::convert::From<ISignificantDigitsOption> for ::windows::core::IUnknown {
fn from(value: ISignificantDigitsOption) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ISignificantDigitsOption> for ::windows::core::IUnknown {
fn from(value: &ISignificantDigitsOption) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ISignificantDigitsOption {
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 ISignificantDigitsOption {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ISignificantDigitsOption> for ::windows::core::IInspectable {
fn from(value: ISignificantDigitsOption) -> Self {
value.0
}
}
impl ::core::convert::From<&ISignificantDigitsOption> for ::windows::core::IInspectable {
fn from(value: &ISignificantDigitsOption) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ISignificantDigitsOption {
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 ISignificantDigitsOption {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct ISignificantDigitsOption_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 i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IncrementNumberRounder(pub ::windows::core::IInspectable);
impl IncrementNumberRounder {
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<IncrementNumberRounder, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn RoundInt32(&self, value: i32) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<i32>(result__)
}
}
pub fn RoundUInt32(&self, value: u32) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<u32>(result__)
}
}
pub fn RoundInt64(&self, value: i64) -> ::windows::core::Result<i64> {
let this = self;
unsafe {
let mut result__: i64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<i64>(result__)
}
}
pub fn RoundUInt64(&self, value: u64) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<u64>(result__)
}
}
pub fn RoundSingle(&self, value: f32) -> ::windows::core::Result<f32> {
let this = self;
unsafe {
let mut result__: f32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<f32>(result__)
}
}
pub fn RoundDouble(&self, value: f64) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<f64>(result__)
}
}
pub fn RoundingAlgorithm(&self) -> ::windows::core::Result<RoundingAlgorithm> {
let this = &::windows::core::Interface::cast::<IIncrementNumberRounder>(self)?;
unsafe {
let mut result__: RoundingAlgorithm = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RoundingAlgorithm>(result__)
}
}
pub fn SetRoundingAlgorithm(&self, value: RoundingAlgorithm) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IIncrementNumberRounder>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Increment(&self) -> ::windows::core::Result<f64> {
let this = &::windows::core::Interface::cast::<IIncrementNumberRounder>(self)?;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<f64>(result__)
}
}
pub fn SetIncrement(&self, value: f64) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IIncrementNumberRounder>(self)?;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for IncrementNumberRounder {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.NumberFormatting.IncrementNumberRounder;{5473c375-38ed-4631-b80c-ef34fc48b7f5})");
}
unsafe impl ::windows::core::Interface for IncrementNumberRounder {
type Vtable = INumberRounder_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5473c375_38ed_4631_b80c_ef34fc48b7f5);
}
impl ::windows::core::RuntimeName for IncrementNumberRounder {
const NAME: &'static str = "Windows.Globalization.NumberFormatting.IncrementNumberRounder";
}
impl ::core::convert::From<IncrementNumberRounder> for ::windows::core::IUnknown {
fn from(value: IncrementNumberRounder) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IncrementNumberRounder> for ::windows::core::IUnknown {
fn from(value: &IncrementNumberRounder) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IncrementNumberRounder {
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 IncrementNumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IncrementNumberRounder> for ::windows::core::IInspectable {
fn from(value: IncrementNumberRounder) -> Self {
value.0
}
}
impl ::core::convert::From<&IncrementNumberRounder> for ::windows::core::IInspectable {
fn from(value: &IncrementNumberRounder) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IncrementNumberRounder {
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 IncrementNumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IncrementNumberRounder> for INumberRounder {
fn from(value: IncrementNumberRounder) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IncrementNumberRounder> for INumberRounder {
fn from(value: &IncrementNumberRounder) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounder> for IncrementNumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounder> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounder> for &IncrementNumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounder> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
unsafe impl ::core::marker::Send for IncrementNumberRounder {}
unsafe impl ::core::marker::Sync for IncrementNumberRounder {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct NumeralSystemTranslator(pub ::windows::core::IInspectable);
impl NumeralSystemTranslator {
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<NumeralSystemTranslator, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "Foundation_Collections")]
pub fn Languages(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
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<::windows::core::HSTRING>>(result__)
}
}
pub fn ResolvedLanguage(&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).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn NumeralSystem(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetNumeralSystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn TranslateNumerals<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::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).10)(::core::mem::transmute_copy(this), value.into_param().abi(), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Create<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>>(languages: Param0) -> ::windows::core::Result<NumeralSystemTranslator> {
Self::INumeralSystemTranslatorFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languages.into_param().abi(), &mut result__).from_abi::<NumeralSystemTranslator>(result__)
})
}
pub fn INumeralSystemTranslatorFactory<R, F: FnOnce(&INumeralSystemTranslatorFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<NumeralSystemTranslator, INumeralSystemTranslatorFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for NumeralSystemTranslator {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.NumberFormatting.NumeralSystemTranslator;{28f5bc2c-8c23-4234-ad2e-fa5a3a426e9b})");
}
unsafe impl ::windows::core::Interface for NumeralSystemTranslator {
type Vtable = INumeralSystemTranslator_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x28f5bc2c_8c23_4234_ad2e_fa5a3a426e9b);
}
impl ::windows::core::RuntimeName for NumeralSystemTranslator {
const NAME: &'static str = "Windows.Globalization.NumberFormatting.NumeralSystemTranslator";
}
impl ::core::convert::From<NumeralSystemTranslator> for ::windows::core::IUnknown {
fn from(value: NumeralSystemTranslator) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&NumeralSystemTranslator> for ::windows::core::IUnknown {
fn from(value: &NumeralSystemTranslator) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for NumeralSystemTranslator {
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 NumeralSystemTranslator {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<NumeralSystemTranslator> for ::windows::core::IInspectable {
fn from(value: NumeralSystemTranslator) -> Self {
value.0
}
}
impl ::core::convert::From<&NumeralSystemTranslator> for ::windows::core::IInspectable {
fn from(value: &NumeralSystemTranslator) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for NumeralSystemTranslator {
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 NumeralSystemTranslator {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for NumeralSystemTranslator {}
unsafe impl ::core::marker::Sync for NumeralSystemTranslator {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PercentFormatter(pub ::windows::core::IInspectable);
impl PercentFormatter {
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<PercentFormatter, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn FormatInt(&self, value: i64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt(&self, value: u64) -> ::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).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble(&self, value: f64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatInt2(&self, value: i64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt2(&self, value: u64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble2(&self, value: f64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Languages(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(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<::windows::core::HSTRING>>(result__)
}
}
pub fn GeographicRegion(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IntegerDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetIntegerDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn FractionDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetFractionDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsGrouped(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsGrouped(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsDecimalPointAlwaysDisplayed(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsDecimalPointAlwaysDisplayed(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn NumeralSystem(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetNumeralSystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn ResolvedLanguage(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ResolvedGeographicRegion(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<i64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<i64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseUInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<u64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseDouble<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<f64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<f64>>(result__)
}
}
pub fn NumberRounder(&self) -> ::windows::core::Result<INumberRounder> {
let this = &::windows::core::Interface::cast::<INumberRounderOption>(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::<INumberRounder>(result__)
}
}
pub fn SetNumberRounder<'a, Param0: ::windows::core::IntoParam<'a, INumberRounder>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberRounderOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn IsZeroSigned(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ISignedZeroOption>(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 SetIsZeroSigned(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignedZeroOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn SignificantDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsOption>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetSignificantDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn CreatePercentFormatter<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(languages: Param0, geographicregion: Param1) -> ::windows::core::Result<PercentFormatter> {
Self::IPercentFormatterFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languages.into_param().abi(), geographicregion.into_param().abi(), &mut result__).from_abi::<PercentFormatter>(result__)
})
}
pub fn IPercentFormatterFactory<R, F: FnOnce(&IPercentFormatterFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PercentFormatter, IPercentFormatterFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for PercentFormatter {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.NumberFormatting.PercentFormatter;{a5007c49-7676-4db7-8631-1b6ff265caa9})");
}
unsafe impl ::windows::core::Interface for PercentFormatter {
type Vtable = INumberFormatter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa5007c49_7676_4db7_8631_1b6ff265caa9);
}
impl ::windows::core::RuntimeName for PercentFormatter {
const NAME: &'static str = "Windows.Globalization.NumberFormatting.PercentFormatter";
}
impl ::core::convert::From<PercentFormatter> for ::windows::core::IUnknown {
fn from(value: PercentFormatter) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PercentFormatter> for ::windows::core::IUnknown {
fn from(value: &PercentFormatter) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PercentFormatter {
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 PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PercentFormatter> for ::windows::core::IInspectable {
fn from(value: PercentFormatter) -> Self {
value.0
}
}
impl ::core::convert::From<&PercentFormatter> for ::windows::core::IInspectable {
fn from(value: &PercentFormatter) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PercentFormatter {
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 PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<PercentFormatter> for INumberFormatter {
fn from(value: PercentFormatter) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&PercentFormatter> for INumberFormatter {
fn from(value: &PercentFormatter) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter> for PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter> for &PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
impl ::core::convert::TryFrom<PercentFormatter> for INumberFormatter2 {
type Error = ::windows::core::Error;
fn try_from(value: PercentFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PercentFormatter> for INumberFormatter2 {
type Error = ::windows::core::Error;
fn try_from(value: &PercentFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter2> for PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter2> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter2> for &PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter2> {
::core::convert::TryInto::<INumberFormatter2>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PercentFormatter> for INumberFormatterOptions {
type Error = ::windows::core::Error;
fn try_from(value: PercentFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PercentFormatter> for INumberFormatterOptions {
type Error = ::windows::core::Error;
fn try_from(value: &PercentFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatterOptions> for PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatterOptions> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatterOptions> for &PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatterOptions> {
::core::convert::TryInto::<INumberFormatterOptions>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PercentFormatter> for INumberParser {
type Error = ::windows::core::Error;
fn try_from(value: PercentFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PercentFormatter> for INumberParser {
type Error = ::windows::core::Error;
fn try_from(value: &PercentFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberParser> for PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberParser> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberParser> for &PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberParser> {
::core::convert::TryInto::<INumberParser>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PercentFormatter> for INumberRounderOption {
type Error = ::windows::core::Error;
fn try_from(value: PercentFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PercentFormatter> for INumberRounderOption {
type Error = ::windows::core::Error;
fn try_from(value: &PercentFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounderOption> for PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounderOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounderOption> for &PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounderOption> {
::core::convert::TryInto::<INumberRounderOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PercentFormatter> for ISignedZeroOption {
type Error = ::windows::core::Error;
fn try_from(value: PercentFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PercentFormatter> for ISignedZeroOption {
type Error = ::windows::core::Error;
fn try_from(value: &PercentFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignedZeroOption> for PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignedZeroOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignedZeroOption> for &PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignedZeroOption> {
::core::convert::TryInto::<ISignedZeroOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PercentFormatter> for ISignificantDigitsOption {
type Error = ::windows::core::Error;
fn try_from(value: PercentFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PercentFormatter> for ISignificantDigitsOption {
type Error = ::windows::core::Error;
fn try_from(value: &PercentFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignificantDigitsOption> for PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignificantDigitsOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignificantDigitsOption> for &PercentFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignificantDigitsOption> {
::core::convert::TryInto::<ISignificantDigitsOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PercentFormatter {}
unsafe impl ::core::marker::Sync for PercentFormatter {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct PermilleFormatter(pub ::windows::core::IInspectable);
impl PermilleFormatter {
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<PermilleFormatter, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn FormatInt(&self, value: i64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt(&self, value: u64) -> ::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).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble(&self, value: f64) -> ::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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatInt2(&self, value: i64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatUInt2(&self, value: u64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn FormatDouble2(&self, value: f64) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatter2>(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), value, &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Languages(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(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<::windows::core::HSTRING>>(result__)
}
}
pub fn GeographicRegion(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn IntegerDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetIntegerDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn FractionDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetFractionDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsGrouped(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsGrouped(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn IsDecimalPointAlwaysDisplayed(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
pub fn SetIsDecimalPointAlwaysDisplayed(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn NumeralSystem(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetNumeralSystem<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn ResolvedLanguage(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ResolvedGeographicRegion(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<INumberFormatterOptions>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<i64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<i64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseUInt<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<u64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<u64>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ParseDouble<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, text: Param0) -> ::windows::core::Result<super::super::Foundation::IReference<f64>> {
let this = &::windows::core::Interface::cast::<INumberParser>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), text.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IReference<f64>>(result__)
}
}
pub fn NumberRounder(&self) -> ::windows::core::Result<INumberRounder> {
let this = &::windows::core::Interface::cast::<INumberRounderOption>(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::<INumberRounder>(result__)
}
}
pub fn SetNumberRounder<'a, Param0: ::windows::core::IntoParam<'a, INumberRounder>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<INumberRounderOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn IsZeroSigned(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<ISignedZeroOption>(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 SetIsZeroSigned(&self, value: bool) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignedZeroOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn SignificantDigits(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsOption>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn SetSignificantDigits(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsOption>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn CreatePermilleFormatter<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<::windows::core::HSTRING>>, Param1: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(languages: Param0, geographicregion: Param1) -> ::windows::core::Result<PermilleFormatter> {
Self::IPermilleFormatterFactory(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), languages.into_param().abi(), geographicregion.into_param().abi(), &mut result__).from_abi::<PermilleFormatter>(result__)
})
}
pub fn IPermilleFormatterFactory<R, F: FnOnce(&IPermilleFormatterFactory) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<PermilleFormatter, IPermilleFormatterFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for PermilleFormatter {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.NumberFormatting.PermilleFormatter;{a5007c49-7676-4db7-8631-1b6ff265caa9})");
}
unsafe impl ::windows::core::Interface for PermilleFormatter {
type Vtable = INumberFormatter_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa5007c49_7676_4db7_8631_1b6ff265caa9);
}
impl ::windows::core::RuntimeName for PermilleFormatter {
const NAME: &'static str = "Windows.Globalization.NumberFormatting.PermilleFormatter";
}
impl ::core::convert::From<PermilleFormatter> for ::windows::core::IUnknown {
fn from(value: PermilleFormatter) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&PermilleFormatter> for ::windows::core::IUnknown {
fn from(value: &PermilleFormatter) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for PermilleFormatter {
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 PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<PermilleFormatter> for ::windows::core::IInspectable {
fn from(value: PermilleFormatter) -> Self {
value.0
}
}
impl ::core::convert::From<&PermilleFormatter> for ::windows::core::IInspectable {
fn from(value: &PermilleFormatter) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for PermilleFormatter {
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 PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<PermilleFormatter> for INumberFormatter {
fn from(value: PermilleFormatter) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&PermilleFormatter> for INumberFormatter {
fn from(value: &PermilleFormatter) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter> for PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter> for &PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
impl ::core::convert::TryFrom<PermilleFormatter> for INumberFormatter2 {
type Error = ::windows::core::Error;
fn try_from(value: PermilleFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PermilleFormatter> for INumberFormatter2 {
type Error = ::windows::core::Error;
fn try_from(value: &PermilleFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter2> for PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter2> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatter2> for &PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatter2> {
::core::convert::TryInto::<INumberFormatter2>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PermilleFormatter> for INumberFormatterOptions {
type Error = ::windows::core::Error;
fn try_from(value: PermilleFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PermilleFormatter> for INumberFormatterOptions {
type Error = ::windows::core::Error;
fn try_from(value: &PermilleFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatterOptions> for PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatterOptions> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberFormatterOptions> for &PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberFormatterOptions> {
::core::convert::TryInto::<INumberFormatterOptions>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PermilleFormatter> for INumberParser {
type Error = ::windows::core::Error;
fn try_from(value: PermilleFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PermilleFormatter> for INumberParser {
type Error = ::windows::core::Error;
fn try_from(value: &PermilleFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberParser> for PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberParser> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberParser> for &PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberParser> {
::core::convert::TryInto::<INumberParser>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PermilleFormatter> for INumberRounderOption {
type Error = ::windows::core::Error;
fn try_from(value: PermilleFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PermilleFormatter> for INumberRounderOption {
type Error = ::windows::core::Error;
fn try_from(value: &PermilleFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounderOption> for PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounderOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounderOption> for &PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounderOption> {
::core::convert::TryInto::<INumberRounderOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PermilleFormatter> for ISignedZeroOption {
type Error = ::windows::core::Error;
fn try_from(value: PermilleFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PermilleFormatter> for ISignedZeroOption {
type Error = ::windows::core::Error;
fn try_from(value: &PermilleFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignedZeroOption> for PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignedZeroOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignedZeroOption> for &PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignedZeroOption> {
::core::convert::TryInto::<ISignedZeroOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
impl ::core::convert::TryFrom<PermilleFormatter> for ISignificantDigitsOption {
type Error = ::windows::core::Error;
fn try_from(value: PermilleFormatter) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&PermilleFormatter> for ISignificantDigitsOption {
type Error = ::windows::core::Error;
fn try_from(value: &PermilleFormatter) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignificantDigitsOption> for PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignificantDigitsOption> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, ISignificantDigitsOption> for &PermilleFormatter {
fn into_param(self) -> ::windows::core::Param<'a, ISignificantDigitsOption> {
::core::convert::TryInto::<ISignificantDigitsOption>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for PermilleFormatter {}
unsafe impl ::core::marker::Sync for PermilleFormatter {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct RoundingAlgorithm(pub i32);
impl RoundingAlgorithm {
pub const None: RoundingAlgorithm = RoundingAlgorithm(0i32);
pub const RoundDown: RoundingAlgorithm = RoundingAlgorithm(1i32);
pub const RoundUp: RoundingAlgorithm = RoundingAlgorithm(2i32);
pub const RoundTowardsZero: RoundingAlgorithm = RoundingAlgorithm(3i32);
pub const RoundAwayFromZero: RoundingAlgorithm = RoundingAlgorithm(4i32);
pub const RoundHalfDown: RoundingAlgorithm = RoundingAlgorithm(5i32);
pub const RoundHalfUp: RoundingAlgorithm = RoundingAlgorithm(6i32);
pub const RoundHalfTowardsZero: RoundingAlgorithm = RoundingAlgorithm(7i32);
pub const RoundHalfAwayFromZero: RoundingAlgorithm = RoundingAlgorithm(8i32);
pub const RoundHalfToEven: RoundingAlgorithm = RoundingAlgorithm(9i32);
pub const RoundHalfToOdd: RoundingAlgorithm = RoundingAlgorithm(10i32);
}
impl ::core::convert::From<i32> for RoundingAlgorithm {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for RoundingAlgorithm {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for RoundingAlgorithm {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Globalization.NumberFormatting.RoundingAlgorithm;i4)");
}
impl ::windows::core::DefaultType for RoundingAlgorithm {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct SignificantDigitsNumberRounder(pub ::windows::core::IInspectable);
impl SignificantDigitsNumberRounder {
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<SignificantDigitsNumberRounder, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn RoundInt32(&self, value: i32) -> ::windows::core::Result<i32> {
let this = self;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<i32>(result__)
}
}
pub fn RoundUInt32(&self, value: u32) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<u32>(result__)
}
}
pub fn RoundInt64(&self, value: i64) -> ::windows::core::Result<i64> {
let this = self;
unsafe {
let mut result__: i64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<i64>(result__)
}
}
pub fn RoundUInt64(&self, value: u64) -> ::windows::core::Result<u64> {
let this = self;
unsafe {
let mut result__: u64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<u64>(result__)
}
}
pub fn RoundSingle(&self, value: f32) -> ::windows::core::Result<f32> {
let this = self;
unsafe {
let mut result__: f32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<f32>(result__)
}
}
pub fn RoundDouble(&self, value: f64) -> ::windows::core::Result<f64> {
let this = self;
unsafe {
let mut result__: f64 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), value, &mut result__).from_abi::<f64>(result__)
}
}
pub fn RoundingAlgorithm(&self) -> ::windows::core::Result<RoundingAlgorithm> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsNumberRounder>(self)?;
unsafe {
let mut result__: RoundingAlgorithm = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<RoundingAlgorithm>(result__)
}
}
pub fn SetRoundingAlgorithm(&self, value: RoundingAlgorithm) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsNumberRounder>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn SignificantDigits(&self) -> ::windows::core::Result<u32> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsNumberRounder>(self)?;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SetSignificantDigits(&self, value: u32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ISignificantDigitsNumberRounder>(self)?;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), value).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for SignificantDigitsNumberRounder {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Globalization.NumberFormatting.SignificantDigitsNumberRounder;{5473c375-38ed-4631-b80c-ef34fc48b7f5})");
}
unsafe impl ::windows::core::Interface for SignificantDigitsNumberRounder {
type Vtable = INumberRounder_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5473c375_38ed_4631_b80c_ef34fc48b7f5);
}
impl ::windows::core::RuntimeName for SignificantDigitsNumberRounder {
const NAME: &'static str = "Windows.Globalization.NumberFormatting.SignificantDigitsNumberRounder";
}
impl ::core::convert::From<SignificantDigitsNumberRounder> for ::windows::core::IUnknown {
fn from(value: SignificantDigitsNumberRounder) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&SignificantDigitsNumberRounder> for ::windows::core::IUnknown {
fn from(value: &SignificantDigitsNumberRounder) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for SignificantDigitsNumberRounder {
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 SignificantDigitsNumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<SignificantDigitsNumberRounder> for ::windows::core::IInspectable {
fn from(value: SignificantDigitsNumberRounder) -> Self {
value.0
}
}
impl ::core::convert::From<&SignificantDigitsNumberRounder> for ::windows::core::IInspectable {
fn from(value: &SignificantDigitsNumberRounder) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for SignificantDigitsNumberRounder {
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 SignificantDigitsNumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<SignificantDigitsNumberRounder> for INumberRounder {
fn from(value: SignificantDigitsNumberRounder) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&SignificantDigitsNumberRounder> for INumberRounder {
fn from(value: &SignificantDigitsNumberRounder) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounder> for SignificantDigitsNumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounder> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, INumberRounder> for &SignificantDigitsNumberRounder {
fn into_param(self) -> ::windows::core::Param<'a, INumberRounder> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
unsafe impl ::core::marker::Send for SignificantDigitsNumberRounder {}
unsafe impl ::core::marker::Sync for SignificantDigitsNumberRounder {}
|
fn main() {
println!("usage: cargo run --bin day_*");
}
|
use super::xtunel_connect;
use super::XReqq;
use crate::config::{TunCfg, KEEP_ALIVE_INTERVAL};
use crate::lws::{RMessage, TMessage, WMessage};
use crate::tunnels::{Cmd, THeader, THEADER_SIZE};
use byte::*;
use failure::Error;
use futures_03::prelude::*;
use log::{debug, error, info};
use nix::sys::socket::{shutdown, Shutdown};
use std::cell::RefCell;
use std::os::unix::io::RawFd;
use std::rc::Rc;
use std::time::{Duration, Instant};
use stream_cancel::{Trigger, Tripwire};
use tokio::sync::mpsc::UnboundedSender;
pub type LongLive = Rc<RefCell<XTunnel>>;
pub struct XTunnel {
pub url_string: String,
pub token: String,
dns_server: String,
discarded: bool,
need_reconnect: bool,
tun_tx: Option<UnboundedSender<WMessage>>,
keepalive_trigger: Option<Trigger>,
ping_count: usize,
rawfd: Option<RawFd>,
time: Instant,
req_count: u16,
requests: XReqq,
pub req_cap: u16,
}
impl XTunnel {
pub fn new(cfg: &TunCfg) -> LongLive {
info!("[XTunnel]new XTunnel");
let req_cap = 128;
let url = &cfg.xport_url;
let tok = &cfg.token;
Rc::new(RefCell::new(XTunnel {
url_string: url.to_string(),
token: tok.to_string(),
dns_server: cfg.default_dns_server.to_string(),
discarded: false,
need_reconnect: false,
tun_tx: None,
keepalive_trigger: None,
ping_count: 0,
rawfd: None,
time: Instant::now(),
req_count: 0,
req_cap,
requests: XReqq::new(req_cap as usize),
}))
}
pub fn start(&mut self, s: LongLive) -> std::result::Result<(), Error> {
info!("[XTunnel]start XTunnel");
xtunel_connect(self, s.clone(), self.dns_server.to_string());
self.start_keepalive_timer(s);
Ok(())
}
pub fn stop(&mut self) {
info!("[XTunnel]stop XTunnel");
if self.discarded {
error!("[XTunnel]stop, XTunnel is already discarded");
return;
}
self.discarded = true;
self.close_rawfd();
self.keepalive_trigger = None;
}
pub fn on_tunnel_created(
&mut self,
rawfd: RawFd,
tx: UnboundedSender<WMessage>,
) -> std::result::Result<(), Error> {
info!("[XTunnel]on_tunnel_created");
if self.discarded != false {
error!("[XTunnel]on_tunnel_created, tunmgr is discarded, tun will be discarded");
return Err(failure::err_msg("XTunnel has discarded"));
}
self.rawfd = Some(rawfd);
self.tun_tx = Some(tx);
Ok(())
}
pub fn on_tunnel_closed(&mut self) {
info!("[XTunnel]on_tunnel_closed");
self.rawfd = None;
let t = self.tun_tx.take();
if t.is_some() {
if self.discarded {
info!("[XTunnel]on_tunnel_closed, XTunnel is discarded, tun will be discard");
return;
} else {
self.need_reconnect = true;
}
info!("[XTunnel]xtunnel closed, reconnect later");
}
let reqs = &mut self.requests;
reqs.clear_all();
}
pub fn on_tunnel_build_error(&mut self) {
info!("[XTunnel]on_tunnel_build_error");
if self.discarded != false {
error!(
"[XTunnel]on_tunnel_build_error, XTunnel is discarded, tun will be not reconnect"
);
return;
}
self.need_reconnect = true;
info!("[XTunnel]tunnel build error, rebuild later");
}
fn save_keepalive_trigger(&mut self, trigger: Trigger) {
self.keepalive_trigger = Some(trigger);
}
fn keepalive(&mut self, s: LongLive) {
if self.discarded != false {
error!("[XTunnel]keepalive, XTunnel is discarded, not do keepalive");
return;
}
self.send_ping();
self.process_reconnect(s.clone());
}
fn process_reconnect(&mut self, s: LongLive) {
if self.need_reconnect {
xtunel_connect(self, s, self.dns_server.to_string());
self.ping_count = 0;
self.need_reconnect = false;
}
}
fn start_keepalive_timer(&mut self, s2: LongLive) {
info!("[XTunnel]start_keepalive_timer");
let (trigger, tripwire) = Tripwire::new();
self.save_keepalive_trigger(trigger);
// tokio timer, every 3 seconds
let task = tokio::time::interval(Duration::from_millis(KEEP_ALIVE_INTERVAL))
.skip(1)
.take_until(tripwire)
.for_each(move |instant| {
debug!("[XTunnel]keepalive timer fire; instant={:?}", instant);
let mut rf = s2.borrow_mut();
rf.keepalive(s2.clone());
future::ready(())
});
let t_fut = async move {
task.await;
info!("[XTunnel] keepalive timer future completed");
()
};
tokio::task::spawn_local(t_fut);
}
fn send_ping(&mut self) {
let ping_count = self.ping_count;
if ping_count > 5 {
// exceed max ping count
info!("[XTunnel] ping exceed max, close rawfd");
self.close_rawfd();
return;
}
if self.tun_tx.is_none() {
return;
}
let timestamp = self.get_elapsed_milliseconds();
let mut bs1 = vec![0 as u8; 11]; // 2 bytes length, 1 byte cmd, 8 byte content
let bs = &mut bs1[..];
let offset = &mut 0;
bs.write_with::<u16>(offset, 11, LE).unwrap();
bs.write_with::<u8>(offset, Cmd::Ping as u8, LE).unwrap();
bs.write_with::<u64>(offset, timestamp, LE).unwrap();
let msg = WMessage::new(bs1, 0);
let r = self.tun_tx.as_ref().unwrap().send(msg);
match r {
Err(e) => {
error!("[XTunnel] tunnel send_ping error:{}", e);
}
_ => {
self.ping_count += 1;
}
}
}
fn close_rawfd(&mut self) {
info!("[XTunnel]close_rawfd");
if self.rawfd.is_none() {
return;
}
let r = shutdown(self.rawfd.take().unwrap(), Shutdown::Both);
match r {
Err(e) => {
info!("[XTunnel]close_rawfd failed:{}", e);
}
_ => {}
}
}
fn get_elapsed_milliseconds(&self) -> u64 {
let in_ms = self.time.elapsed().as_millis();
in_ms as u64
}
pub fn on_tunnel_msg(&mut self, msg: RMessage, ll: LongLive) {
// info!("[XTunnel]on_tunnel_msg");
let bs = msg.buf.as_ref().unwrap();
let bs = &bs[2..]; // skip the length
let offset = &mut 0;
let cmd = bs.read_with::<u8>(offset, LE).unwrap();
let bs = &bs[1..]; // skip cmd
let cmd = Cmd::from(cmd);
match cmd {
Cmd::Ping => {
// send to per
self.reply_ping(msg);
}
Cmd::Pong => {
self.on_pong(bs);
}
_ => {
self.on_tunnel_proxy_msg(cmd, msg, ll);
}
}
}
fn on_tunnel_proxy_msg(&mut self, cmd: Cmd, mut msg: RMessage, tl: LongLive) {
let vec = msg.buf.take().unwrap();
let bs = &vec[3..];
let th = THeader::read_from(&bs[..]);
let bs = &bs[THEADER_SIZE..];
match cmd {
Cmd::ReqData => {
// data
let req_idx = th.req_idx;
let req_tag = th.req_tag;
let tx = self.get_request_tx(req_idx, req_tag);
match tx {
None => {
info!("[XTunnel]no request found for: {}:{}", req_idx, req_tag);
return;
}
Some(tx) => {
// info!(
// "[XTunnel]{} proxy request msg, {}:{}",
// self.tunnel_id, req_idx, req_tag
// );
let wmsg = WMessage::new(vec, (3 + THEADER_SIZE) as u16);
let result = tx.send(wmsg);
match result {
Err(e) => {
info!("[XTunnel]tunnel msg send to request failed:{}", e);
return;
}
_ => {}
}
}
}
}
Cmd::ReqClientFinished => {
// client finished
let req_idx = th.req_idx;
let req_tag = th.req_tag;
info!(
"[XTunnel]ReqClientFinished, idx:{}, tag:{}",
req_idx, req_tag
);
self.free_request_tx(req_idx, req_tag);
}
Cmd::ReqClientClosed => {
// client closed
let req_idx = th.req_idx;
let req_tag = th.req_tag;
info!("[XTunnel]ReqClientClosed, idx:{}, tag:{}", req_idx, req_tag);
let reqs = &mut self.requests;
let r = reqs.free(req_idx, req_tag);
if r && self.req_count > 0 {
self.req_count -= 1;
}
}
Cmd::ReqCreated => {
let req_idx = th.req_idx;
let req_tag = th.req_tag;
let offset = &mut 0;
// port, u16
let port = bs.read_with::<u16>(offset, LE).unwrap();
self.requests.alloc(req_idx, req_tag);
// start connect to target
if super::proxy_request(self, tl, req_idx, req_tag, port) {
self.req_count += 1;
}
}
_ => {
error!("[XTunnel] unsupport cmd:{:?}, discard msg", cmd);
}
}
}
fn reply_ping(&mut self, mut msg: RMessage) {
if self.tun_tx.is_none() {
return;
}
//info!("[XTunnel] reply_ping");
let mut vec = msg.buf.take().unwrap();
let bs = &mut vec[2..];
let offset = &mut 0;
bs.write_with::<u8>(offset, Cmd::Pong as u8, LE).unwrap();
let wmsg = WMessage::new(vec, 0);
let tx = self.tun_tx.as_ref().unwrap();
let result = tx.send(wmsg);
match result {
Err(e) => {
error!(
"[XTunnel]reply_ping tun send error:{}, tun_tx maybe closed",
e
);
}
_ => {
//info!("[XTunnel]on_dns_reply unbounded_send request msg",)
}
}
}
fn on_pong(&mut self, bs: &[u8]) {
//info!("[XTunnel] on_pong");
let len = bs.len();
if len != 8 {
error!("[XTunnel]pong data length({}) != 8", len);
return;
}
// reset ping count
self.ping_count = 0;
let offset = &mut 0;
let timestamp = bs.read_with::<u64>(offset, LE).unwrap();
let in_ms = self.get_elapsed_milliseconds();
assert!(in_ms >= timestamp, "[XTunnel]pong timestamp > now!");
}
fn get_request_tx(&self, req_idx: u16, req_tag: u16) -> Option<UnboundedSender<WMessage>> {
let requests = &self.requests;
let req_idx = req_idx as usize;
if req_idx >= requests.elements.len() {
return None;
}
let req = &requests.elements[req_idx];
if req.tag == req_tag && req.request_tx.is_some() {
match req.request_tx {
None => {
return None;
}
Some(ref tx) => {
return Some(tx.clone());
}
}
}
None
}
fn free_request_tx(&mut self, req_idx: u16, req_tag: u16) {
let requests = &mut self.requests;
let req_idx = req_idx as usize;
if req_idx >= requests.elements.len() {
return;
}
let req = &mut requests.elements[req_idx];
if req.tag == req_tag && req.request_tx.is_some() {
info!(
"[XTunnel]free_request_tx, req_idx:{}, req_tag:{}",
req_idx, req_tag
);
req.request_tx = None;
}
}
pub fn on_request_connect_error(&mut self, req_idx: u16, req_tag: u16) {
info!("[XTunnel]on_request_connect_error, req_idx:{}", req_idx);
self.on_request_closed(req_idx, req_tag);
}
pub fn on_request_closed(&mut self, req_idx: u16, req_tag: u16) {
info!("[XTunnel]on_request_closed, req_idx:{}", req_idx);
if !self.check_req_valid(req_idx, req_tag) {
return;
}
if self.tun_tx.is_none() {
return;
}
let reqs = &mut self.requests;
let r = reqs.free(req_idx, req_tag);
if r {
info!(
"[XTunnel]on_request_closed, tun index:{}, sub req_count by 1",
req_idx
);
self.req_count -= 1;
// send request to agent
let hsize = 3 + THEADER_SIZE;
let mut buf = vec![0; hsize];
let offset = &mut 0;
let header = &mut buf[..];
header.write_with::<u16>(offset, hsize as u16, LE).unwrap();
header
.write_with::<u8>(offset, Cmd::ReqServerClosed as u8, LE)
.unwrap();
let th = THeader::new(req_idx, req_tag);
let msg_header = &mut buf[3..];
th.write_to(msg_header);
// websocket message
let wmsg = WMessage::new(buf, 0);
// send to peer, should always succeed
if let Err(e) = self.tun_tx.as_ref().unwrap().send(wmsg) {
error!(
"[XTunnel]send_request_closed_to_server tx send failed:{}",
e
);
}
}
}
pub fn on_request_recv_finished(&mut self, req_idx: u16, req_tag: u16) {
info!("[XTunnel] on_request_recv_finished:{}", req_idx);
if !self.check_req_valid(req_idx, req_tag) {
return;
}
if self.tun_tx.is_none() {
return;
}
// send request to agent
let hsize = 3 + THEADER_SIZE;
let mut buf = vec![0; hsize];
let offset = &mut 0;
let header = &mut buf[..];
header.write_with::<u16>(offset, hsize as u16, LE).unwrap();
header
.write_with::<u8>(offset, Cmd::ReqServerFinished as u8, LE)
.unwrap();
let th = THeader::new(req_idx, req_tag);
let msg_header = &mut buf[3..];
th.write_to(msg_header);
// websocket message
let wmsg = WMessage::new(buf, 0);
let result = self.tun_tx.as_ref().unwrap().send(wmsg);
match result {
Err(e) => {
error!(
"[XTunnel] on_request_recv_finished, tun send error:{}, tun_tx maybe closed",
e
);
}
_ => {}
}
}
pub fn on_request_msg(&mut self, mut message: TMessage, req_idx: u16, req_tag: u16) -> bool {
if !self.check_req_valid(req_idx, req_tag) {
error!("[XTunnel] on_request_msg failed, check_req_valid false");
return false;
}
if self.tun_tx.is_none() {
error!("[XTunnel] on_request_msg failed, tun_tx is none");
return false;
}
let mut vec = message.buf.take().unwrap();
let ll = vec.len();
let bs = &mut vec[..];
let offset = &mut 0;
bs.write_with::<u16>(offset, ll as u16, LE).unwrap();
bs.write_with::<u8>(offset, Cmd::ReqData as u8, LE).unwrap();
let th = THeader::new(req_idx, req_tag);
let msg_header = &mut vec[3..];
th.write_to(msg_header);
// info!(
// "[XTunnel] send request response to peer, len:{}",
// vec.len()
// );
let wmsg = WMessage::new(vec, 0);
let result = self.tun_tx.as_ref().unwrap().send(wmsg);
match result {
Err(e) => {
error!("[XTunnel]request tun send error:{}, tun_tx maybe closed", e);
return false;
}
_ => {
// info!("[XTunnel]unbounded_send request msg, req_idx:{}", req_idx);
}
}
true
}
pub fn save_request_tx(
&mut self,
tx: UnboundedSender<WMessage>,
trigger: Trigger,
req_idx: u16,
req_tag: u16,
) -> std::result::Result<(), Error> {
if self.discarded {
return Err(failure::err_msg("xtunnel has been discarded"));
}
let requests = &mut self.requests;
let req_idx = req_idx as usize;
if req_idx >= requests.elements.len() {
return Err(failure::err_msg("req_idx is invalid"));
}
let req = &mut requests.elements[req_idx];
if req.tag != req_tag {
return Err(failure::err_msg("req tag is invalid"));
}
req.trigger = Some(trigger);
req.request_tx = Some(tx);
Ok(())
}
fn check_req_valid(&self, req_idx: u16, req_tag: u16) -> bool {
let requests = &self.requests;
let req_idx2 = req_idx as usize;
if req_idx2 >= requests.elements.len() {
return false;
}
let req = &requests.elements[req_idx2];
if !req.is_inused {
return false;
}
if req.tag != req_tag {
return false;
}
true
}
}
|
#[doc = "Reader of register EEPASS0"]
pub type R = crate::R<u32, super::EEPASS0>;
#[doc = "Writer for register EEPASS0"]
pub type W = crate::W<u32, super::EEPASS0>;
#[doc = "Register EEPASS0 `reset()`'s with value 0"]
impl crate::ResetValue for super::EEPASS0 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `PASS`"]
pub type PASS_R = crate::R<u32, u32>;
#[doc = "Write proxy for field `PASS`"]
pub struct PASS_W<'a> {
w: &'a mut W,
}
impl<'a> PASS_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u32) -> &'a mut W {
self.w.bits = (self.w.bits & !0xffff_ffff) | ((value as u32) & 0xffff_ffff);
self.w
}
}
impl R {
#[doc = "Bits 0:31 - Password"]
#[inline(always)]
pub fn pass(&self) -> PASS_R {
PASS_R::new((self.bits & 0xffff_ffff) as u32)
}
}
impl W {
#[doc = "Bits 0:31 - Password"]
#[inline(always)]
pub fn pass(&mut self) -> PASS_W {
PASS_W { w: self }
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::collections::HashMap;
use common_exception::ErrorCode;
use common_exception::Result;
use super::group::GroupState;
use super::RelExpr;
use super::RelationalProperty;
use crate::optimizer::group::Group;
use crate::optimizer::m_expr::MExpr;
use crate::optimizer::s_expr::SExpr;
use crate::plans::RelOperator;
use crate::IndexType;
/// `Memo` is a search space which memoize possible plans of a query.
/// The plans inside `Memo` are organized with `Group`s.
/// Each `Group` is a set of logically equivalent relational expressions represented with `MExpr`.
#[derive(Clone)]
pub struct Memo {
pub groups: Vec<Group>,
pub root: Option<IndexType>,
/// Hash table for detecting duplicated expressions.
/// The entry is `(plan, children) -> (group_index, m_expr_index)`.
pub m_expr_lookup_table: HashMap<(RelOperator, Vec<IndexType>), (IndexType, IndexType)>,
}
impl Memo {
pub fn create() -> Self {
Memo {
groups: vec![],
root: None,
m_expr_lookup_table: HashMap::new(),
}
}
pub fn root(&self) -> Option<&Group> {
self.root.map(|index| &self.groups[index])
}
pub fn set_root(&mut self, group_index: IndexType) {
self.root = Some(group_index);
}
pub fn set_group_state(&mut self, group_index: IndexType, state: GroupState) -> Result<()> {
let group = self
.groups
.get_mut(group_index)
.ok_or_else(|| ErrorCode::Internal(format!("Group index {} not found", group_index)))?;
group.state = state;
Ok(())
}
// Initialize memo with given expression
pub fn init(&mut self, s_expr: SExpr) -> Result<()> {
let root = self.insert(None, s_expr)?;
self.set_root(root);
Ok(())
}
pub fn insert(&mut self, target_group: Option<IndexType>, s_expr: SExpr) -> Result<IndexType> {
let mut children_group = vec![];
for expr in s_expr.children() {
// Insert children expressions recursively and collect their group indices
let group = self.insert(None, expr.clone())?;
children_group.push(group);
}
if let Some((group_index, _)) = self
.m_expr_lookup_table
.get(&(s_expr.plan.clone(), children_group.clone()))
{
// If the expression already exists, return the group index of the existing expression
return Ok(*group_index);
}
if let Some(group_index) = s_expr.original_group() {
// The expression is extracted by PatternExtractor, no need to reinsert.
return Ok(group_index);
}
// Create new group if not specified
let group_index = match target_group {
Some(index) => index,
_ => {
let rel_expr = RelExpr::with_s_expr(&s_expr);
let relational_prop = rel_expr.derive_relational_prop()?;
self.add_group(relational_prop)
}
};
let m_expr = MExpr::create(
group_index,
self.group(group_index)?.num_exprs(),
s_expr.plan,
children_group,
s_expr.applied_rules,
);
self.insert_m_expr(group_index, m_expr)?;
Ok(group_index)
}
pub fn group(&self, index: IndexType) -> Result<&Group> {
self.groups
.get(index)
.ok_or_else(|| ErrorCode::Internal(format!("Group index {} not found", index)))
}
pub fn insert_m_expr(&mut self, group_index: IndexType, m_expr: MExpr) -> Result<()> {
self.m_expr_lookup_table.insert(
(m_expr.plan.clone(), m_expr.children.clone()),
(m_expr.group_index, m_expr.index),
);
self.group_mut(group_index)?.insert(m_expr)
}
pub fn group_mut(&mut self, index: IndexType) -> Result<&mut Group> {
self.groups
.get_mut(index)
.ok_or_else(|| ErrorCode::Internal(format!("Group index {} not found", index)))
}
fn add_group(&mut self, relational_prop: RelationalProperty) -> IndexType {
let group_index = self.groups.len();
let group = Group::create(group_index, relational_prop);
self.groups.push(group);
group_index
}
}
|
use super::Constant;
use super::run_fn;
pub fn map(args: Vec<Constant>) -> Constant {
let pair: (&Constant, &Constant) = (args.get(0).unwrap(), args.get(1).unwrap());
match pair {
(&Constant::Function(ref v1), &Constant::List(ref v2)) =>
Constant::List(v2.into_iter().map(|a| run_fn(Constant::Function(v1.clone()), vec![a.clone()])).collect()),
_ => {
eprintln!("Invalid arguments passed to \"map\"!");
panic!()
}
}
} |
use std::collections::HashMap;
use std::fs::File;
use std::io::{BufRead, BufReader};
pub fn run_puzzle() {
let file = File::open("input_day3.txt").expect("Failed to open input_day3.txt");
let br = BufReader::new(file);
let mut wires: HashMap<(i64, i64), (u64, u64)> = HashMap::new();
let mut curwire = 1;
for line in br.lines() {
let mut curpos = (0, 0);
let mut steps = 0;
let mut check_wire = |wire: &mut (u64, u64)| {
if (wire.0 & curwire) == 0 {
(*wire).0 |= curwire;
(*wire).1 += steps;
}
steps += 1;
};
for op in line.unwrap().split(',') {
let diff = i64::from_str_radix(&op[1..], 10).unwrap();
match op.get(0..1).unwrap() {
"L" => {
for x in (((curpos.0 + 1) - diff)..(curpos.0 + 1)).rev() {
let wire = wires.entry((x, curpos.1)).or_insert((0, 0));
check_wire(wire);
}
curpos.0 -= diff;
}
"R" => {
for x in curpos.0..curpos.0 + diff {
let wire = wires.entry((x, curpos.1)).or_insert((0, 0));
check_wire(wire);
}
curpos.0 += diff;
}
"U" => {
for y in (((curpos.1 + 1) - diff)..(curpos.1 + 1)).rev() {
let wire = wires.entry((curpos.0, y)).or_insert((0, 0));
check_wire(wire);
}
curpos.1 -= diff;
}
"D" => {
for y in curpos.1..curpos.1 + diff {
let wire = wires.entry((curpos.0, y)).or_insert((0, 0));
check_wire(wire);
}
curpos.1 += diff;
}
_ => panic!("Unsupported pattern!"),
}
}
curwire <<= 1;
}
let mut curdist: u64 = std::u64::MAX;
for point in wires {
if (point.1).0 == 3 {
if (point.1).1 != 0 && (point.1).1 < curdist {
curdist = (point.1).1;
}
}
}
println!("Result: {}", curdist);
}
|
#[doc = "Reader of register D2CCIP2R"]
pub type R = crate::R<u32, super::D2CCIP2R>;
#[doc = "Writer for register D2CCIP2R"]
pub type W = crate::W<u32, super::D2CCIP2R>;
#[doc = "Register D2CCIP2R `reset()`'s with value 0"]
impl crate::ResetValue for super::D2CCIP2R {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "USART2/3, UART4,5, 7/8 (APB1) kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum USART234578SEL_A {
#[doc = "0: rcc_pclk1 selected as peripheral clock"]
RCC_PCLK1 = 0,
#[doc = "1: pll2_q selected as peripheral clock"]
PLL2_Q = 1,
#[doc = "2: pll3_q selected as peripheral clock"]
PLL3_Q = 2,
#[doc = "3: hsi_ker selected as peripheral clock"]
HSI_KER = 3,
#[doc = "4: csi_ker selected as peripheral clock"]
CSI_KER = 4,
#[doc = "5: LSE selected as peripheral clock"]
LSE = 5,
}
impl From<USART234578SEL_A> for u8 {
#[inline(always)]
fn from(variant: USART234578SEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `USART234578SEL`"]
pub type USART234578SEL_R = crate::R<u8, USART234578SEL_A>;
impl USART234578SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, USART234578SEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(USART234578SEL_A::RCC_PCLK1),
1 => Val(USART234578SEL_A::PLL2_Q),
2 => Val(USART234578SEL_A::PLL3_Q),
3 => Val(USART234578SEL_A::HSI_KER),
4 => Val(USART234578SEL_A::CSI_KER),
5 => Val(USART234578SEL_A::LSE),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `RCC_PCLK1`"]
#[inline(always)]
pub fn is_rcc_pclk1(&self) -> bool {
*self == USART234578SEL_A::RCC_PCLK1
}
#[doc = "Checks if the value of the field is `PLL2_Q`"]
#[inline(always)]
pub fn is_pll2_q(&self) -> bool {
*self == USART234578SEL_A::PLL2_Q
}
#[doc = "Checks if the value of the field is `PLL3_Q`"]
#[inline(always)]
pub fn is_pll3_q(&self) -> bool {
*self == USART234578SEL_A::PLL3_Q
}
#[doc = "Checks if the value of the field is `HSI_KER`"]
#[inline(always)]
pub fn is_hsi_ker(&self) -> bool {
*self == USART234578SEL_A::HSI_KER
}
#[doc = "Checks if the value of the field is `CSI_KER`"]
#[inline(always)]
pub fn is_csi_ker(&self) -> bool {
*self == USART234578SEL_A::CSI_KER
}
#[doc = "Checks if the value of the field is `LSE`"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == USART234578SEL_A::LSE
}
}
#[doc = "Write proxy for field `USART234578SEL`"]
pub struct USART234578SEL_W<'a> {
w: &'a mut W,
}
impl<'a> USART234578SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USART234578SEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "rcc_pclk1 selected as peripheral clock"]
#[inline(always)]
pub fn rcc_pclk1(self) -> &'a mut W {
self.variant(USART234578SEL_A::RCC_PCLK1)
}
#[doc = "pll2_q selected as peripheral clock"]
#[inline(always)]
pub fn pll2_q(self) -> &'a mut W {
self.variant(USART234578SEL_A::PLL2_Q)
}
#[doc = "pll3_q selected as peripheral clock"]
#[inline(always)]
pub fn pll3_q(self) -> &'a mut W {
self.variant(USART234578SEL_A::PLL3_Q)
}
#[doc = "hsi_ker selected as peripheral clock"]
#[inline(always)]
pub fn hsi_ker(self) -> &'a mut W {
self.variant(USART234578SEL_A::HSI_KER)
}
#[doc = "csi_ker selected as peripheral clock"]
#[inline(always)]
pub fn csi_ker(self) -> &'a mut W {
self.variant(USART234578SEL_A::CSI_KER)
}
#[doc = "LSE selected as peripheral clock"]
#[inline(always)]
pub fn lse(self) -> &'a mut W {
self.variant(USART234578SEL_A::LSE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x07) | ((value as u32) & 0x07);
self.w
}
}
#[doc = "USART1 and 6 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum USART16SEL_A {
#[doc = "0: rcc_pclk2 selected as peripheral clock"]
RCC_PCLK2 = 0,
#[doc = "1: pll2_q selected as peripheral clock"]
PLL2_Q = 1,
#[doc = "2: pll3_q selected as peripheral clock"]
PLL3_Q = 2,
#[doc = "3: hsi_ker selected as peripheral clock"]
HSI_KER = 3,
#[doc = "4: csi_ker selected as peripheral clock"]
CSI_KER = 4,
#[doc = "5: LSE selected as peripheral clock"]
LSE = 5,
}
impl From<USART16SEL_A> for u8 {
#[inline(always)]
fn from(variant: USART16SEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `USART16SEL`"]
pub type USART16SEL_R = crate::R<u8, USART16SEL_A>;
impl USART16SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, USART16SEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(USART16SEL_A::RCC_PCLK2),
1 => Val(USART16SEL_A::PLL2_Q),
2 => Val(USART16SEL_A::PLL3_Q),
3 => Val(USART16SEL_A::HSI_KER),
4 => Val(USART16SEL_A::CSI_KER),
5 => Val(USART16SEL_A::LSE),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `RCC_PCLK2`"]
#[inline(always)]
pub fn is_rcc_pclk2(&self) -> bool {
*self == USART16SEL_A::RCC_PCLK2
}
#[doc = "Checks if the value of the field is `PLL2_Q`"]
#[inline(always)]
pub fn is_pll2_q(&self) -> bool {
*self == USART16SEL_A::PLL2_Q
}
#[doc = "Checks if the value of the field is `PLL3_Q`"]
#[inline(always)]
pub fn is_pll3_q(&self) -> bool {
*self == USART16SEL_A::PLL3_Q
}
#[doc = "Checks if the value of the field is `HSI_KER`"]
#[inline(always)]
pub fn is_hsi_ker(&self) -> bool {
*self == USART16SEL_A::HSI_KER
}
#[doc = "Checks if the value of the field is `CSI_KER`"]
#[inline(always)]
pub fn is_csi_ker(&self) -> bool {
*self == USART16SEL_A::CSI_KER
}
#[doc = "Checks if the value of the field is `LSE`"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == USART16SEL_A::LSE
}
}
#[doc = "Write proxy for field `USART16SEL`"]
pub struct USART16SEL_W<'a> {
w: &'a mut W,
}
impl<'a> USART16SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USART16SEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "rcc_pclk2 selected as peripheral clock"]
#[inline(always)]
pub fn rcc_pclk2(self) -> &'a mut W {
self.variant(USART16SEL_A::RCC_PCLK2)
}
#[doc = "pll2_q selected as peripheral clock"]
#[inline(always)]
pub fn pll2_q(self) -> &'a mut W {
self.variant(USART16SEL_A::PLL2_Q)
}
#[doc = "pll3_q selected as peripheral clock"]
#[inline(always)]
pub fn pll3_q(self) -> &'a mut W {
self.variant(USART16SEL_A::PLL3_Q)
}
#[doc = "hsi_ker selected as peripheral clock"]
#[inline(always)]
pub fn hsi_ker(self) -> &'a mut W {
self.variant(USART16SEL_A::HSI_KER)
}
#[doc = "csi_ker selected as peripheral clock"]
#[inline(always)]
pub fn csi_ker(self) -> &'a mut W {
self.variant(USART16SEL_A::CSI_KER)
}
#[doc = "LSE selected as peripheral clock"]
#[inline(always)]
pub fn lse(self) -> &'a mut W {
self.variant(USART16SEL_A::LSE)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 3)) | (((value as u32) & 0x07) << 3);
self.w
}
}
#[doc = "RNG kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RNGSEL_A {
#[doc = "0: HSI48 selected as peripheral clock"]
HSI48 = 0,
#[doc = "1: pll1_q selected as peripheral clock"]
PLL1_Q = 1,
#[doc = "2: LSE selected as peripheral clock"]
LSE = 2,
#[doc = "3: LSI selected as peripheral clock"]
LSI = 3,
}
impl From<RNGSEL_A> for u8 {
#[inline(always)]
fn from(variant: RNGSEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `RNGSEL`"]
pub type RNGSEL_R = crate::R<u8, RNGSEL_A>;
impl RNGSEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> RNGSEL_A {
match self.bits {
0 => RNGSEL_A::HSI48,
1 => RNGSEL_A::PLL1_Q,
2 => RNGSEL_A::LSE,
3 => RNGSEL_A::LSI,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `HSI48`"]
#[inline(always)]
pub fn is_hsi48(&self) -> bool {
*self == RNGSEL_A::HSI48
}
#[doc = "Checks if the value of the field is `PLL1_Q`"]
#[inline(always)]
pub fn is_pll1_q(&self) -> bool {
*self == RNGSEL_A::PLL1_Q
}
#[doc = "Checks if the value of the field is `LSE`"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == RNGSEL_A::LSE
}
#[doc = "Checks if the value of the field is `LSI`"]
#[inline(always)]
pub fn is_lsi(&self) -> bool {
*self == RNGSEL_A::LSI
}
}
#[doc = "Write proxy for field `RNGSEL`"]
pub struct RNGSEL_W<'a> {
w: &'a mut W,
}
impl<'a> RNGSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RNGSEL_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "HSI48 selected as peripheral clock"]
#[inline(always)]
pub fn hsi48(self) -> &'a mut W {
self.variant(RNGSEL_A::HSI48)
}
#[doc = "pll1_q selected as peripheral clock"]
#[inline(always)]
pub fn pll1_q(self) -> &'a mut W {
self.variant(RNGSEL_A::PLL1_Q)
}
#[doc = "LSE selected as peripheral clock"]
#[inline(always)]
pub fn lse(self) -> &'a mut W {
self.variant(RNGSEL_A::LSE)
}
#[doc = "LSI selected as peripheral clock"]
#[inline(always)]
pub fn lsi(self) -> &'a mut W {
self.variant(RNGSEL_A::LSI)
}
#[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 << 8)) | (((value as u32) & 0x03) << 8);
self.w
}
}
#[doc = "I2C1,2,3 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum I2C123SEL_A {
#[doc = "0: rcc_pclk1 selected as peripheral clock"]
RCC_PCLK1 = 0,
#[doc = "1: pll3_r selected as peripheral clock"]
PLL3_R = 1,
#[doc = "2: hsi_ker selected as peripheral clock"]
HSI_KER = 2,
#[doc = "3: csi_ker selected as peripheral clock"]
CSI_KER = 3,
}
impl From<I2C123SEL_A> for u8 {
#[inline(always)]
fn from(variant: I2C123SEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `I2C123SEL`"]
pub type I2C123SEL_R = crate::R<u8, I2C123SEL_A>;
impl I2C123SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> I2C123SEL_A {
match self.bits {
0 => I2C123SEL_A::RCC_PCLK1,
1 => I2C123SEL_A::PLL3_R,
2 => I2C123SEL_A::HSI_KER,
3 => I2C123SEL_A::CSI_KER,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `RCC_PCLK1`"]
#[inline(always)]
pub fn is_rcc_pclk1(&self) -> bool {
*self == I2C123SEL_A::RCC_PCLK1
}
#[doc = "Checks if the value of the field is `PLL3_R`"]
#[inline(always)]
pub fn is_pll3_r(&self) -> bool {
*self == I2C123SEL_A::PLL3_R
}
#[doc = "Checks if the value of the field is `HSI_KER`"]
#[inline(always)]
pub fn is_hsi_ker(&self) -> bool {
*self == I2C123SEL_A::HSI_KER
}
#[doc = "Checks if the value of the field is `CSI_KER`"]
#[inline(always)]
pub fn is_csi_ker(&self) -> bool {
*self == I2C123SEL_A::CSI_KER
}
}
#[doc = "Write proxy for field `I2C123SEL`"]
pub struct I2C123SEL_W<'a> {
w: &'a mut W,
}
impl<'a> I2C123SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: I2C123SEL_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "rcc_pclk1 selected as peripheral clock"]
#[inline(always)]
pub fn rcc_pclk1(self) -> &'a mut W {
self.variant(I2C123SEL_A::RCC_PCLK1)
}
#[doc = "pll3_r selected as peripheral clock"]
#[inline(always)]
pub fn pll3_r(self) -> &'a mut W {
self.variant(I2C123SEL_A::PLL3_R)
}
#[doc = "hsi_ker selected as peripheral clock"]
#[inline(always)]
pub fn hsi_ker(self) -> &'a mut W {
self.variant(I2C123SEL_A::HSI_KER)
}
#[doc = "csi_ker selected as peripheral clock"]
#[inline(always)]
pub fn csi_ker(self) -> &'a mut W {
self.variant(I2C123SEL_A::CSI_KER)
}
#[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 = "USBOTG 1 and 2 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum USBSEL_A {
#[doc = "0: Disable the kernel clock"]
DISABLE = 0,
#[doc = "1: pll1_q selected as peripheral clock"]
PLL1_Q = 1,
#[doc = "2: pll3_q selected as peripheral clock"]
PLL3_Q = 2,
#[doc = "3: HSI48 selected as peripheral clock"]
HSI48 = 3,
}
impl From<USBSEL_A> for u8 {
#[inline(always)]
fn from(variant: USBSEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `USBSEL`"]
pub type USBSEL_R = crate::R<u8, USBSEL_A>;
impl USBSEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> USBSEL_A {
match self.bits {
0 => USBSEL_A::DISABLE,
1 => USBSEL_A::PLL1_Q,
2 => USBSEL_A::PLL3_Q,
3 => USBSEL_A::HSI48,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `DISABLE`"]
#[inline(always)]
pub fn is_disable(&self) -> bool {
*self == USBSEL_A::DISABLE
}
#[doc = "Checks if the value of the field is `PLL1_Q`"]
#[inline(always)]
pub fn is_pll1_q(&self) -> bool {
*self == USBSEL_A::PLL1_Q
}
#[doc = "Checks if the value of the field is `PLL3_Q`"]
#[inline(always)]
pub fn is_pll3_q(&self) -> bool {
*self == USBSEL_A::PLL3_Q
}
#[doc = "Checks if the value of the field is `HSI48`"]
#[inline(always)]
pub fn is_hsi48(&self) -> bool {
*self == USBSEL_A::HSI48
}
}
#[doc = "Write proxy for field `USBSEL`"]
pub struct USBSEL_W<'a> {
w: &'a mut W,
}
impl<'a> USBSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USBSEL_A) -> &'a mut W {
{
self.bits(variant.into())
}
}
#[doc = "Disable the kernel clock"]
#[inline(always)]
pub fn disable(self) -> &'a mut W {
self.variant(USBSEL_A::DISABLE)
}
#[doc = "pll1_q selected as peripheral clock"]
#[inline(always)]
pub fn pll1_q(self) -> &'a mut W {
self.variant(USBSEL_A::PLL1_Q)
}
#[doc = "pll3_q selected as peripheral clock"]
#[inline(always)]
pub fn pll3_q(self) -> &'a mut W {
self.variant(USBSEL_A::PLL3_Q)
}
#[doc = "HSI48 selected as peripheral clock"]
#[inline(always)]
pub fn hsi48(self) -> &'a mut W {
self.variant(USBSEL_A::HSI48)
}
#[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 << 20)) | (((value as u32) & 0x03) << 20);
self.w
}
}
#[doc = "HDMI-CEC kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum CECSEL_A {
#[doc = "0: LSE selected as peripheral clock"]
LSE = 0,
#[doc = "1: LSI selected as peripheral clock"]
LSI = 1,
#[doc = "2: csi_ker selected as peripheral clock"]
CSI_KER = 2,
}
impl From<CECSEL_A> for u8 {
#[inline(always)]
fn from(variant: CECSEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `CECSEL`"]
pub type CECSEL_R = crate::R<u8, CECSEL_A>;
impl CECSEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, CECSEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(CECSEL_A::LSE),
1 => Val(CECSEL_A::LSI),
2 => Val(CECSEL_A::CSI_KER),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `LSE`"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == CECSEL_A::LSE
}
#[doc = "Checks if the value of the field is `LSI`"]
#[inline(always)]
pub fn is_lsi(&self) -> bool {
*self == CECSEL_A::LSI
}
#[doc = "Checks if the value of the field is `CSI_KER`"]
#[inline(always)]
pub fn is_csi_ker(&self) -> bool {
*self == CECSEL_A::CSI_KER
}
}
#[doc = "Write proxy for field `CECSEL`"]
pub struct CECSEL_W<'a> {
w: &'a mut W,
}
impl<'a> CECSEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: CECSEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "LSE selected as peripheral clock"]
#[inline(always)]
pub fn lse(self) -> &'a mut W {
self.variant(CECSEL_A::LSE)
}
#[doc = "LSI selected as peripheral clock"]
#[inline(always)]
pub fn lsi(self) -> &'a mut W {
self.variant(CECSEL_A::LSI)
}
#[doc = "csi_ker selected as peripheral clock"]
#[inline(always)]
pub fn csi_ker(self) -> &'a mut W {
self.variant(CECSEL_A::CSI_KER)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 22)) | (((value as u32) & 0x03) << 22);
self.w
}
}
#[doc = "LPTIM1 kernel clock source selection\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum LPTIM1SEL_A {
#[doc = "0: rcc_pclk1 selected as peripheral clock"]
RCC_PCLK1 = 0,
#[doc = "1: pll2_p selected as peripheral clock"]
PLL2_P = 1,
#[doc = "2: pll3_r selected as peripheral clock"]
PLL3_R = 2,
#[doc = "3: LSE selected as peripheral clock"]
LSE = 3,
#[doc = "4: LSI selected as peripheral clock"]
LSI = 4,
#[doc = "5: PER selected as peripheral clock"]
PER = 5,
}
impl From<LPTIM1SEL_A> for u8 {
#[inline(always)]
fn from(variant: LPTIM1SEL_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `LPTIM1SEL`"]
pub type LPTIM1SEL_R = crate::R<u8, LPTIM1SEL_A>;
impl LPTIM1SEL_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, LPTIM1SEL_A> {
use crate::Variant::*;
match self.bits {
0 => Val(LPTIM1SEL_A::RCC_PCLK1),
1 => Val(LPTIM1SEL_A::PLL2_P),
2 => Val(LPTIM1SEL_A::PLL3_R),
3 => Val(LPTIM1SEL_A::LSE),
4 => Val(LPTIM1SEL_A::LSI),
5 => Val(LPTIM1SEL_A::PER),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `RCC_PCLK1`"]
#[inline(always)]
pub fn is_rcc_pclk1(&self) -> bool {
*self == LPTIM1SEL_A::RCC_PCLK1
}
#[doc = "Checks if the value of the field is `PLL2_P`"]
#[inline(always)]
pub fn is_pll2_p(&self) -> bool {
*self == LPTIM1SEL_A::PLL2_P
}
#[doc = "Checks if the value of the field is `PLL3_R`"]
#[inline(always)]
pub fn is_pll3_r(&self) -> bool {
*self == LPTIM1SEL_A::PLL3_R
}
#[doc = "Checks if the value of the field is `LSE`"]
#[inline(always)]
pub fn is_lse(&self) -> bool {
*self == LPTIM1SEL_A::LSE
}
#[doc = "Checks if the value of the field is `LSI`"]
#[inline(always)]
pub fn is_lsi(&self) -> bool {
*self == LPTIM1SEL_A::LSI
}
#[doc = "Checks if the value of the field is `PER`"]
#[inline(always)]
pub fn is_per(&self) -> bool {
*self == LPTIM1SEL_A::PER
}
}
#[doc = "Write proxy for field `LPTIM1SEL`"]
pub struct LPTIM1SEL_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM1SEL_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM1SEL_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "rcc_pclk1 selected as peripheral clock"]
#[inline(always)]
pub fn rcc_pclk1(self) -> &'a mut W {
self.variant(LPTIM1SEL_A::RCC_PCLK1)
}
#[doc = "pll2_p selected as peripheral clock"]
#[inline(always)]
pub fn pll2_p(self) -> &'a mut W {
self.variant(LPTIM1SEL_A::PLL2_P)
}
#[doc = "pll3_r selected as peripheral clock"]
#[inline(always)]
pub fn pll3_r(self) -> &'a mut W {
self.variant(LPTIM1SEL_A::PLL3_R)
}
#[doc = "LSE selected as peripheral clock"]
#[inline(always)]
pub fn lse(self) -> &'a mut W {
self.variant(LPTIM1SEL_A::LSE)
}
#[doc = "LSI selected as peripheral clock"]
#[inline(always)]
pub fn lsi(self) -> &'a mut W {
self.variant(LPTIM1SEL_A::LSI)
}
#[doc = "PER selected as peripheral clock"]
#[inline(always)]
pub fn per(self) -> &'a mut W {
self.variant(LPTIM1SEL_A::PER)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x07 << 28)) | (((value as u32) & 0x07) << 28);
self.w
}
}
impl R {
#[doc = "Bits 0:2 - USART2/3, UART4,5, 7/8 (APB1) kernel clock source selection"]
#[inline(always)]
pub fn usart234578sel(&self) -> USART234578SEL_R {
USART234578SEL_R::new((self.bits & 0x07) as u8)
}
#[doc = "Bits 3:5 - USART1 and 6 kernel clock source selection"]
#[inline(always)]
pub fn usart16sel(&self) -> USART16SEL_R {
USART16SEL_R::new(((self.bits >> 3) & 0x07) as u8)
}
#[doc = "Bits 8:9 - RNG kernel clock source selection"]
#[inline(always)]
pub fn rngsel(&self) -> RNGSEL_R {
RNGSEL_R::new(((self.bits >> 8) & 0x03) as u8)
}
#[doc = "Bits 12:13 - I2C1,2,3 kernel clock source selection"]
#[inline(always)]
pub fn i2c123sel(&self) -> I2C123SEL_R {
I2C123SEL_R::new(((self.bits >> 12) & 0x03) as u8)
}
#[doc = "Bits 20:21 - USBOTG 1 and 2 kernel clock source selection"]
#[inline(always)]
pub fn usbsel(&self) -> USBSEL_R {
USBSEL_R::new(((self.bits >> 20) & 0x03) as u8)
}
#[doc = "Bits 22:23 - HDMI-CEC kernel clock source selection"]
#[inline(always)]
pub fn cecsel(&self) -> CECSEL_R {
CECSEL_R::new(((self.bits >> 22) & 0x03) as u8)
}
#[doc = "Bits 28:30 - LPTIM1 kernel clock source selection"]
#[inline(always)]
pub fn lptim1sel(&self) -> LPTIM1SEL_R {
LPTIM1SEL_R::new(((self.bits >> 28) & 0x07) as u8)
}
}
impl W {
#[doc = "Bits 0:2 - USART2/3, UART4,5, 7/8 (APB1) kernel clock source selection"]
#[inline(always)]
pub fn usart234578sel(&mut self) -> USART234578SEL_W {
USART234578SEL_W { w: self }
}
#[doc = "Bits 3:5 - USART1 and 6 kernel clock source selection"]
#[inline(always)]
pub fn usart16sel(&mut self) -> USART16SEL_W {
USART16SEL_W { w: self }
}
#[doc = "Bits 8:9 - RNG kernel clock source selection"]
#[inline(always)]
pub fn rngsel(&mut self) -> RNGSEL_W {
RNGSEL_W { w: self }
}
#[doc = "Bits 12:13 - I2C1,2,3 kernel clock source selection"]
#[inline(always)]
pub fn i2c123sel(&mut self) -> I2C123SEL_W {
I2C123SEL_W { w: self }
}
#[doc = "Bits 20:21 - USBOTG 1 and 2 kernel clock source selection"]
#[inline(always)]
pub fn usbsel(&mut self) -> USBSEL_W {
USBSEL_W { w: self }
}
#[doc = "Bits 22:23 - HDMI-CEC kernel clock source selection"]
#[inline(always)]
pub fn cecsel(&mut self) -> CECSEL_W {
CECSEL_W { w: self }
}
#[doc = "Bits 28:30 - LPTIM1 kernel clock source selection"]
#[inline(always)]
pub fn lptim1sel(&mut self) -> LPTIM1SEL_W {
LPTIM1SEL_W { w: self }
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
bitfield::bitfield,
failure::{bail, format_err, Error, ResultExt},
fidl::endpoints::ClientEnd,
fidl_fuchsia_media::{
AudioSampleFormat, AudioStreamType, MediumSpecificStreamType, SimpleStreamSinkProxy,
StreamPacket, StreamType, AUDIO_ENCODING_SBC, NO_TIMESTAMP,
STREAM_PACKET_FLAG_DISCONTINUITY,
},
fidl_fuchsia_media_playback::{
PlayerEvent, PlayerEventStream, PlayerMarker, PlayerProxy, SourceMarker,
},
fuchsia_zircon::{self as zx, HandleBased},
futures::{stream, StreamExt},
};
const DEFAULT_BUFFER_LEN: usize = 65536;
/// Players are configured and accept media frames, which are sent to the
/// media subsystem.
pub struct Player {
buffer: zx::Vmo,
buffer_len: usize,
codec: String,
current_offset: usize,
stream_source: SimpleStreamSinkProxy,
player: PlayerProxy,
events: PlayerEventStream,
playing: bool,
next_packet_flags: u32,
}
#[derive(Debug, PartialEq)]
enum ChannelMode {
Mono,
DualChannel,
Stereo,
JointStereo,
}
impl From<u8> for ChannelMode {
fn from(bits: u8) -> Self {
match bits {
0 => ChannelMode::Mono,
1 => ChannelMode::DualChannel,
2 => ChannelMode::Stereo,
3 => ChannelMode::JointStereo,
_ => panic!("invalid channel mode"),
}
}
}
bitfield! {
pub struct SbcHeader(u32);
impl Debug;
u8;
syncword, _: 7, 0;
subbands, _: 8;
allocation_method, _: 9;
into ChannelMode, channel_mode, _: 11, 10;
blocks_bits, _: 13, 12;
frequency_bits, _: 15, 14;
bitpool_bits, _: 23, 16;
crccheck, _: 31, 24;
}
impl SbcHeader {
/// The number of channels, based on the channel mode in the header.
/// From Table 12.18 in the A2DP Spec.
fn channels(&self) -> usize {
match self.channel_mode() {
ChannelMode::Mono => 1,
_ => 2,
}
}
fn has_syncword(&self) -> bool {
const SBC_SYNCWORD: u8 = 0x9c;
self.syncword() == SBC_SYNCWORD
}
/// The number of blocks, based on tbe bits in the header.
/// From Table 12.17 in the A2DP Spec.
fn blocks(&self) -> usize {
4 * (self.blocks_bits() + 1) as usize
}
fn bitpool(&self) -> usize {
self.bitpool_bits() as usize
}
/// Number of subbands based on the header bit.
/// From Table 12.20 in the A2DP Spec.
fn num_subbands(&self) -> usize {
if self.subbands() {
8
} else {
4
}
}
/// Calculates the frame length.
/// Formula from Section 12.9 of the A2DP Spec.
fn frame_length(&self) -> Result<usize, Error> {
if !self.has_syncword() {
return Err(format_err!("syncword does not match"));
}
let len = 4 + (4 * self.num_subbands() * self.channels()) / 8;
let rest = (match self.channel_mode() {
ChannelMode::Mono | ChannelMode::DualChannel => {
self.blocks() * self.channels() * self.bitpool()
}
ChannelMode::Stereo => self.blocks() * self.bitpool(),
ChannelMode::JointStereo => self.num_subbands() + (self.blocks() * self.bitpool()),
} as f64
/ 8.0)
.ceil() as usize;
Ok(len + rest)
}
}
impl Player {
/// Attempt to make a new player that decodes and plays frames encoded in the
/// `codec`
pub async fn new(codec: String) -> Result<Player, Error> {
let player = fuchsia_component::client::connect_to_service::<PlayerMarker>()
.context("Failed to connect to media player")?;
Self::from_proxy(codec, player).await
}
/// Build a Player given a PlayerProxy.
/// Used in tests.
async fn from_proxy(codec: String, player: PlayerProxy) -> Result<Player, Error> {
let (source_proxy, source) = fidl::endpoints::create_proxy()?;
player.create_elementary_source(0, false, false, None, source)?;
let audio_stream_type = AudioStreamType {
sample_format: AudioSampleFormat::Signed16,
channels: 2, // Stereo
frames_per_second: 44100, // 44.1kHz
};
let mut stream_type = StreamType {
medium_specific: MediumSpecificStreamType::Audio(audio_stream_type),
encoding: codec.clone(),
encoding_parameters: None,
};
let (stream_source, stream_source_server) = fidl::endpoints::create_proxy()?;
source_proxy.add_stream(&mut stream_type, 44100, 1, stream_source_server)?;
let buffer = zx::Vmo::create(DEFAULT_BUFFER_LEN as u64)?;
stream_source.add_payload_buffer(0, buffer.duplicate_handle(zx::Rights::SAME_RIGHTS)?)?;
let mut player_event_stream = player.take_event_stream();
let source_client_channel = source_proxy.into_channel().unwrap().into_zx_channel();
let upcasted_source = ClientEnd::<SourceMarker>::new(source_client_channel);
player.set_source(Some(upcasted_source))?;
// We should be able to wait until either
// (1) audio is connected or
// (2) there is a Problem.
loop {
let x = player_event_stream.next().await;
if x.is_none() {
// The player closed the event stream, something is wrong.
return Err(format_err!("MediaPlayer closed"));
}
let evt = x.unwrap();
if evt.is_err() {
return Err(evt.unwrap_err().into());
}
let PlayerEvent::OnStatusChanged { player_status } = evt.unwrap();
if let Some(problem) = player_status.problem {
return Err(format_err!(
"Problem setting up: {} - {:?}",
problem.type_,
problem.details
));
}
if player_status.audio_connected {
break;
}
}
Ok(Player {
buffer,
buffer_len: DEFAULT_BUFFER_LEN,
codec,
stream_source,
player,
events: player_event_stream,
current_offset: 0,
playing: false,
next_packet_flags: 0,
})
}
/// Interpret the first four octets of the slice in `bytes` as a little-endian u32
/// Panics if the slice is not at least four octets.
fn as_u32_le(bytes: &[u8]) -> u32 {
((bytes[3] as u32) << 24)
+ ((bytes[2] as u32) << 16)
+ ((bytes[1] as u32) << 8)
+ ((bytes[0] as u32) << 0)
}
/// Given a buffer with an SBC frame at the start, find the length of the
/// SBC frame.
fn find_sbc_frame_len(buf: &[u8]) -> Result<usize, Error> {
if buf.len() < 4 {
return Err(format_err!("Buffer too short for header"));
}
SbcHeader(Player::as_u32_le(&buf[0..4])).frame_length()
}
/// Accepts a payload which may contain multiple frames and breaks it into
/// frames and sends it to media.
pub fn push_payload(&mut self, payload: &[u8]) -> Result<(), Error> {
let mut offset = 13;
while offset < payload.len() {
if self.codec == AUDIO_ENCODING_SBC {
let len = Player::find_sbc_frame_len(&payload[offset..]).or_else(|e| {
self.next_packet_flags |= STREAM_PACKET_FLAG_DISCONTINUITY;
Err(e)
})?;
if offset + len > payload.len() {
self.next_packet_flags |= STREAM_PACKET_FLAG_DISCONTINUITY;
return Err(format_err!("Ran out of buffer for SBC frame"));
}
self.send_frame(&payload[offset..offset + len])?;
offset += len;
} else {
return Err(format_err!("Unrecognized codec!"));
}
}
Ok(())
}
/// Push an encoded media frame into the buffer and signal that it's there to media.
pub fn send_frame(&mut self, frame: &[u8]) -> Result<(), Error> {
if frame.len() > self.buffer_len {
self.stream_source.end_of_stream()?;
bail!("frame is too large for buffer");
}
if self.current_offset + frame.len() > self.buffer_len {
self.current_offset = 0;
}
self.buffer.write(frame, self.current_offset as u64)?;
let mut packet = StreamPacket {
pts: NO_TIMESTAMP,
payload_buffer_id: 0,
payload_offset: self.current_offset as u64,
payload_size: frame.len() as u64,
buffer_config: 0,
flags: self.next_packet_flags,
stream_segment_id: 0,
};
self.stream_source.send_packet_no_reply(&mut packet)?;
self.current_offset += frame.len();
self.next_packet_flags = 0;
Ok(())
}
pub fn playing(&self) -> bool {
self.playing
}
pub fn play(&mut self) -> Result<(), Error> {
self.player.play()?;
self.playing = true;
Ok(())
}
pub fn pause(&mut self) -> Result<(), Error> {
self.player.pause()?;
self.playing = false;
Ok(())
}
pub fn next_event<'a>(&'a mut self) -> stream::Next<PlayerEventStream> {
self.events.next()
}
}
impl Drop for Player {
fn drop(&mut self) {
self.pause().unwrap_or_else(|e| println!("Error in drop: {:}", e));
}
}
#[cfg(test)]
mod tests {
use super::*;
use {
fidl::endpoints::{create_proxy_and_stream, RequestStream},
fidl_fuchsia_media::{SimpleStreamSinkRequest, SimpleStreamSinkRequestStream},
fidl_fuchsia_media_playback::{
ElementarySourceRequest, PlayerMarker, PlayerRequest, PlayerRequestStream, PlayerStatus,
},
fuchsia_async as fasync,
futures::Poll,
};
#[test]
fn test_frame_length() {
// 44.1, 16 blocks, Joint Stereo, Loudness, 8 subbands, 53 bitpool (Android P)
let header1 = [0x9c, 0xBD, 0x35, 0xA2];
const HEADER1_FRAMELEN: usize = 119;
let head = SbcHeader(Player::as_u32_le(&header1));
assert!(head.has_syncword());
assert_eq!(16, head.blocks());
assert_eq!(ChannelMode::JointStereo, head.channel_mode());
assert_eq!(2, head.channels());
assert_eq!(53, head.bitpool());
assert_eq!(HEADER1_FRAMELEN, head.frame_length().unwrap());
assert_eq!(
HEADER1_FRAMELEN,
Player::find_sbc_frame_len(&[0x9c, 0xBD, 0x35, 0xA2]).unwrap()
);
// 44.1, 16 blocks, Stereo, Loudness, 8 subbands, 53 bitpool (OS X)
let header2 = [0x9c, 0xB9, 0x35, 0xA2];
const HEADER2_FRAMELEN: usize = 118;
let head = SbcHeader(Player::as_u32_le(&header2));
assert!(head.has_syncword());
assert_eq!(16, head.blocks());
assert_eq!(ChannelMode::Stereo, head.channel_mode());
assert_eq!(2, head.channels());
assert_eq!(53, head.bitpool());
assert_eq!(HEADER2_FRAMELEN, head.frame_length().unwrap());
assert_eq!(HEADER2_FRAMELEN, Player::find_sbc_frame_len(&header2).unwrap());
}
/// Runs through the setup sequence of a Player, returning the player,
/// SimpleStreamSinkRequestStream and PlayerRequestStream that it is communicating with, and
/// the VMO payload buffer that was provided to the SimpleStreamSink.
fn setup_player(
exec: &mut fasync::Executor,
) -> (Player, SimpleStreamSinkRequestStream, PlayerRequestStream, zx::Vmo) {
let (player_proxy, mut player_request_stream) =
create_proxy_and_stream::<PlayerMarker>().expect("proxy pair creation");
let mut player_new_fut = Box::pin(Player::from_proxy("test".to_string(), player_proxy));
assert!(exec.run_until_stalled(&mut player_new_fut).is_pending());
let player_req = exec
.run_singlethreaded(player_request_stream.select_next_some())
.expect("player request");
let mut source_request_stream = match player_req {
PlayerRequest::CreateElementarySource { source_request, .. } => source_request,
_ => panic!("should be CreateElementarySource"),
}
.into_stream()
.expect("a source request stream to be created from the request");
let source_req = exec
.run_singlethreaded(source_request_stream.select_next_some())
.expect("a source request");
let mut sink_request_stream = match source_req {
ElementarySourceRequest::AddStream { sink_request, .. } => sink_request,
_ => panic!("should be AddStream"),
}
.into_stream()
.expect("a sink request stream to be created from the request");
let sink_req =
exec.run_singlethreaded(sink_request_stream.select_next_some()).expect("sink request");
let sink_vmo = match sink_req {
SimpleStreamSinkRequest::AddPayloadBuffer { payload_buffer, .. } => payload_buffer,
_ => panic!("should have a PayloadBuffer"),
};
let player_req = exec
.run_singlethreaded(player_request_stream.select_next_some())
.expect("player request");
match player_req {
PlayerRequest::SetSource { .. } => (),
_ => panic!("should be CreateElementarySource"),
};
player_request_stream
.control_handle()
.send_on_status_changed(&mut PlayerStatus {
duration: 0,
can_pause: false,
can_seek: false,
has_audio: true,
has_video: false,
ready: true,
metadata: None,
problem: None,
audio_connected: true,
video_connected: false,
video_size: None,
pixel_aspect_ratio: None,
timeline_function: None,
end_of_stream: false,
})
.expect("status changed to send");
let player = match exec.run_until_stalled(&mut player_new_fut) {
Poll::Ready(Ok(player)) => player,
_ => panic!("player should be done"),
};
(player, sink_request_stream, player_request_stream, sink_vmo)
}
#[test]
fn test_player_setup() {
let mut exec = fasync::Executor::new().expect("executor should build");
setup_player(&mut exec);
}
#[test]
/// Tests that the creation of a player executes with the expected interaction with the
/// Player and stream setup.
/// This tests that the buffer is sent correctly and that data "sent" through the shared
/// VMO is readable by the receiver of the VMO.
/// We do this by mocking the Player and SimpleSourceStream interfaces that are used.
fn test_send_frame() {
let mut exec = fasync::Executor::new().expect("executor should build");
let (mut player, mut sink_request_stream, _, sink_vmo) = setup_player(&mut exec);
let payload = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
player.send_frame(payload).expect("send happens okay");
let sink_req =
exec.run_singlethreaded(sink_request_stream.select_next_some()).expect("sink request");
let (offset, size) = match sink_req {
SimpleStreamSinkRequest::SendPacketNoReply { packet, .. } => {
(packet.payload_offset, packet.payload_size as usize)
}
_ => panic!("should have received a packet"),
};
let mut recv = Vec::with_capacity(size);
recv.resize(size, 0);
sink_vmo.read(recv.as_mut_slice(), offset).expect("should be able to read packet data");
assert_eq!(recv, payload, "received didn't match payload");
}
#[test]
#[should_panic(expected = "out of bounds")]
fn test_as_u32_le_len() {
let _ = Player::as_u32_le(&[0, 1, 2]);
}
#[test]
fn test_as_u32_le() {
assert_eq!(1, Player::as_u32_le(&[1, 0, 0, 0]));
assert_eq!(0xff00ff00, Player::as_u32_le(&[0, 0xff, 0, 0xff]));
assert_eq!(0xffffffff, Player::as_u32_le(&[0xff, 0xff, 0xff, 0xff]));
}
}
|
use std::env::current_dir;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::time::Duration;
use process_control::{ChildExt, ExitStatus, Output, Timeout};
#[allow(unused_macros)]
macro_rules! test_stdout {
($func_name:ident, $expected_stdout:literal) => {
#[test]
fn $func_name() {
let (command, output) = $crate::test::output(file!(), stringify!($func_name));
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let formatted_code = match output.status.code() {
Some(code) => code.to_string(),
None => "".to_string(),
};
let formatted_signal = $crate::test::signal(output.status);
assert_eq!(
stdout,
$expected_stdout,
"\nCommands:\ncd {}\n{:?}\nstdout: {}\nstderr: {}\nStatus code: {}\nSignal: {}",
std::env::current_dir().unwrap().to_string_lossy(),
command,
stdout,
stderr,
formatted_code,
formatted_signal
);
}
};
}
#[allow(unused_macros)]
macro_rules! test_stdout_substrings {
($func_name:ident, $expected_stdout_substrings:expr) => {
test_substrings!(
$func_name,
$expected_stdout_substrings,
Vec::<&str>::default()
);
};
}
#[allow(unused_macros)]
macro_rules! test_stderr_substrings {
($func_name:ident, $expected_stderr_substrings:expr) => {
test_substrings!(
$func_name,
Vec::<&str>::default(),
$expected_stderr_substrings
);
};
}
#[allow(unused_macros)]
macro_rules! test_substrings {
($func_name:ident, $expected_stdout_substrings:expr, $expected_stderr_substrings:expr) => {
#[test]
fn $func_name() {
let (command, output) = $crate::test::output(file!(), stringify!($func_name));
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let stripped_stderr_byte_vec = strip_ansi_escapes::strip(output.stderr.clone()).unwrap();
let stripped_stderr = String::from_utf8_lossy(&stripped_stderr_byte_vec);
let formatted_code = match output.status.code() {
Some(code) => code.to_string(),
None => "".to_string(),
};
let formatted_signal = $crate::test::signal(output.status);
let expected_stdout_substrings: Vec<&str> = $expected_stdout_substrings;
for expected_stdout_substring in expected_stdout_substrings {
assert!(
stdout.contains(expected_stdout_substring),
"stdout does not contain substring\nCommands:\ncd {}\n{:?}\nsubstring: {}\nstdout: {}\nstderr: {}\nStatus code: {}\nSignal: {}",
std::env::current_dir().unwrap().to_string_lossy(),
command,
expected_stdout_substring,
stdout,
stderr,
formatted_code,
formatted_signal
);
}
let expected_stderr_substrings: Vec<&str> = $expected_stderr_substrings;
for expected_stderr_substring in expected_stderr_substrings {
assert!(
stripped_stderr.contains(expected_stderr_substring),
"stderr does not contain substring\nCommands:\ncd {}\n{:?}\nsubstring: {}\nstdout: {}\nstderr: {}\nStatus code: {}\nSignal: {}",
std::env::current_dir().unwrap().to_string_lossy(),
command,
expected_stderr_substring,
stdout,
stderr,
formatted_code,
formatted_signal
);
}
}
}
}
pub struct Compilation<'a> {
pub command: &'a mut Command,
pub test_directory_path: &'a Path,
}
pub fn command_failed(
message: &'static str,
working_directory: PathBuf,
command: Command,
output: Output,
) -> ! {
let stdout = String::from_utf8_lossy(&output.stdout);
let stderr = String::from_utf8_lossy(&output.stderr);
let formatted_code = match output.status.code() {
Some(code) => code.to_string(),
None => "".to_string(),
};
let formatted_signal = signal(output.status);
panic!(
"{} failed\nCommands:\ncd {}\n{:?}\n\nstdout: {}\nstderr: {}\nStatus code: {}\nSignal: {}",
message,
working_directory.display(),
command,
stdout,
stderr,
formatted_code,
formatted_signal
);
}
pub fn compiled_path_buf<F>(file: &str, name: &str, compilation_mutator: F) -> PathBuf
where
F: FnOnce(Compilation),
{
match compile(file, name, compilation_mutator) {
Ok(path_buf) => path_buf,
Err((command, output)) => command_failed(
"Compilation",
std::env::current_dir().unwrap(),
command,
output,
),
}
}
fn compile<F>(file: &str, name: &str, compilation_mutator: F) -> Result<PathBuf, (Command, Output)>
where
F: FnOnce(Compilation),
{
let cwd = std::env::current_dir().unwrap();
let build_path = cwd.join("tests/_build");
// `file!()` starts with path relative to workspace root, but the `current_dir` will be inside
// the crate root, so need to strip the relative crate root.
let file_path = Path::new(file);
let crate_relative_file_path = file_path.strip_prefix("native_implemented/otp").unwrap();
let crate_relative_directory_path = crate_relative_file_path.parent().unwrap();
let tests_relative_directory_path =
crate_relative_directory_path.strip_prefix("tests").unwrap();
let file_stem = file_path.file_stem().unwrap();
let output_directory_path = build_path
.join(tests_relative_directory_path)
.join(file_stem)
.join(name);
let output_path = output_directory_path.join("bin").join(name);
let test_directory_path = crate_relative_directory_path.join(file_stem).join(name);
let mut command = Command::new("../../bin/lumen");
command
.arg("compile")
.arg("--output")
.arg(&output_path)
.arg("--output-dir")
.arg(&output_directory_path)
.arg("-O0");
if std::env::var_os("DEBUG").is_some() {
command.arg("--emit=all");
}
compilation_mutator(Compilation {
command: &mut command,
test_directory_path: &test_directory_path,
});
timeout("Compilation", cwd, command, Duration::from_secs(30)).map(|_| output_path)
}
pub fn timeout(
message: &'static str,
working_directory: PathBuf,
mut command: Command,
time_limit: Duration,
) -> Result<(), (Command, Output)> {
let process = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap();
match process
.with_output_timeout(time_limit)
.terminating()
.wait()
.unwrap()
{
Some(output) => {
if output.status.success() {
Ok(())
} else {
Err((command, output))
}
}
None => {
panic!(
"{} timed out after {:?}\nCommands:\ncd {}\n{:?}",
message,
time_limit,
working_directory.display(),
command,
);
}
}
}
#[allow(dead_code)]
pub fn output(file: &str, name: &str) -> (Command, Output) {
let bin_path_buf = compiled_path_buf(
file,
name,
|Compilation {
command,
test_directory_path,
}| {
let erlang_src_path = test_directory_path.join("src");
let input_path = if erlang_src_path.is_dir() {
erlang_src_path
} else {
test_directory_path.join("init.erl")
};
let shared_path = current_dir().unwrap().join("tests/shared/src");
command.arg(shared_path).arg(input_path);
},
);
let mut command = Command::new(&bin_path_buf);
let process = command
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.unwrap_or_else(|error| panic!("Could not run {:?}: {:?}", bin_path_buf, error));
let time_limit = Duration::from_secs(10);
let output = process
.with_output_timeout(time_limit)
.terminating()
.wait()
.unwrap()
.unwrap();
std::fs::remove_file(&bin_path_buf).ok();
(command, output)
}
#[cfg(unix)]
pub fn signal(exit_status: ExitStatus) -> String {
exit_status
.signal()
.map(|i| match i as libc::c_int {
libc::SIGHUP => "hang up".to_string(),
libc::SIGINT => "interrupt (Ctrl+C)".to_string(),
libc::SIGQUIT => "quit (Ctrl+D)".to_string(),
libc::SIGILL => "illegal instruction".to_string(),
libc::SIGABRT => "abort program".to_string(),
libc::SIGFPE => "floating point exception".to_string(),
libc::SIGKILL => "killed".to_string(),
libc::SIGSEGV => "segmentation fault (invalid address)".to_string(),
libc::SIGBUS => "bus error (stack may not have enough pages)".to_string(),
libc::SIGPIPE => "write on a pipe with no reader".to_string(),
libc::SIGALRM => "alarm".to_string(),
libc::SIGTERM => "terminated".to_string(),
n => n.to_string(),
})
.unwrap_or("".to_string())
}
#[cfg(not(unix))]
pub fn signal(exit_status: ExitStatus) -> String {
"".to_string()
}
|
#[doc = "Reader of register DIFSEL"]
pub type R = crate::R<u32, super::DIFSEL>;
#[doc = "Writer for register DIFSEL"]
pub type W = crate::W<u32, super::DIFSEL>;
#[doc = "Register DIFSEL `reset()`'s with value 0"]
impl crate::ResetValue for super::DIFSEL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Differential mode for channels 0\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DIFSEL_0_A {
#[doc = "0: Input channel is configured in single-ended mode"]
SINGLEENDED = 0,
#[doc = "1: Input channel is configured in differential mode"]
DIFFERENTIAL = 1,
}
impl From<DIFSEL_0_A> for bool {
#[inline(always)]
fn from(variant: DIFSEL_0_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `DIFSEL_0`"]
pub type DIFSEL_0_R = crate::R<bool, DIFSEL_0_A>;
impl DIFSEL_0_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> DIFSEL_0_A {
match self.bits {
false => DIFSEL_0_A::SINGLEENDED,
true => DIFSEL_0_A::DIFFERENTIAL,
}
}
#[doc = "Checks if the value of the field is `SINGLEENDED`"]
#[inline(always)]
pub fn is_single_ended(&self) -> bool {
*self == DIFSEL_0_A::SINGLEENDED
}
#[doc = "Checks if the value of the field is `DIFFERENTIAL`"]
#[inline(always)]
pub fn is_differential(&self) -> bool {
*self == DIFSEL_0_A::DIFFERENTIAL
}
}
#[doc = "Write proxy for field `DIFSEL_0`"]
pub struct DIFSEL_0_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_0_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_0_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_1_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_1`"]
pub type DIFSEL_1_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_1`"]
pub struct DIFSEL_1_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_1_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_1_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_2_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_2`"]
pub type DIFSEL_2_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_2`"]
pub struct DIFSEL_2_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_2_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_2_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_3_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_3`"]
pub type DIFSEL_3_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_3`"]
pub struct DIFSEL_3_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_3_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_3_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_4_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_4`"]
pub type DIFSEL_4_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_4`"]
pub struct DIFSEL_4_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_4_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_4_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 = "Differential mode for channels 0"]
pub type DIFSEL_5_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_5`"]
pub type DIFSEL_5_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_5`"]
pub struct DIFSEL_5_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_5_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_5_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_6_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_6`"]
pub type DIFSEL_6_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_6`"]
pub struct DIFSEL_6_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_6_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_6_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_7_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_7`"]
pub type DIFSEL_7_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_7`"]
pub struct DIFSEL_7_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_7_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_7_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 = "Differential mode for channels 0"]
pub type DIFSEL_8_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_8`"]
pub type DIFSEL_8_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_8`"]
pub struct DIFSEL_8_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_8_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_8_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_9_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_9`"]
pub type DIFSEL_9_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_9`"]
pub struct DIFSEL_9_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_9_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_9_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_10_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_10`"]
pub type DIFSEL_10_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_10`"]
pub struct DIFSEL_10_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_10_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_10_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_11_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_11`"]
pub type DIFSEL_11_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_11`"]
pub struct DIFSEL_11_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_11_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_11_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 = "Differential mode for channels 0"]
pub type DIFSEL_12_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_12`"]
pub type DIFSEL_12_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_12`"]
pub struct DIFSEL_12_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_12_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_12_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Differential mode for channels 0"]
pub type DIFSEL_13_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_13`"]
pub type DIFSEL_13_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_13`"]
pub struct DIFSEL_13_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_13_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_13_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 = "Differential mode for channels 0"]
pub type DIFSEL_14_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_14`"]
pub type DIFSEL_14_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_14`"]
pub struct DIFSEL_14_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_14_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_14_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 = "Differential mode for channels 0"]
pub type DIFSEL_15_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_15`"]
pub type DIFSEL_15_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_15`"]
pub struct DIFSEL_15_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_15_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_15_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 = "Differential mode for channels 0"]
pub type DIFSEL_16_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_16`"]
pub type DIFSEL_16_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_16`"]
pub struct DIFSEL_16_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_16_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_16_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 = "Differential mode for channels 0"]
pub type DIFSEL_17_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_17`"]
pub type DIFSEL_17_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_17`"]
pub struct DIFSEL_17_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_17_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_17_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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 = "Differential mode for channels 0"]
pub type DIFSEL_18_A = DIFSEL_0_A;
#[doc = "Reader of field `DIFSEL_18`"]
pub type DIFSEL_18_R = crate::R<bool, DIFSEL_0_A>;
#[doc = "Write proxy for field `DIFSEL_18`"]
pub struct DIFSEL_18_W<'a> {
w: &'a mut W,
}
impl<'a> DIFSEL_18_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DIFSEL_18_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "Input channel is configured in single-ended mode"]
#[inline(always)]
pub fn single_ended(self) -> &'a mut W {
self.variant(DIFSEL_0_A::SINGLEENDED)
}
#[doc = "Input channel is configured in differential mode"]
#[inline(always)]
pub fn differential(self) -> &'a mut W {
self.variant(DIFSEL_0_A::DIFFERENTIAL)
}
#[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
}
}
impl R {
#[doc = "Bit 0 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_0(&self) -> DIFSEL_0_R {
DIFSEL_0_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_1(&self) -> DIFSEL_1_R {
DIFSEL_1_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_2(&self) -> DIFSEL_2_R {
DIFSEL_2_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_3(&self) -> DIFSEL_3_R {
DIFSEL_3_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_4(&self) -> DIFSEL_4_R {
DIFSEL_4_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_5(&self) -> DIFSEL_5_R {
DIFSEL_5_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_6(&self) -> DIFSEL_6_R {
DIFSEL_6_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_7(&self) -> DIFSEL_7_R {
DIFSEL_7_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_8(&self) -> DIFSEL_8_R {
DIFSEL_8_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_9(&self) -> DIFSEL_9_R {
DIFSEL_9_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_10(&self) -> DIFSEL_10_R {
DIFSEL_10_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_11(&self) -> DIFSEL_11_R {
DIFSEL_11_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_12(&self) -> DIFSEL_12_R {
DIFSEL_12_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_13(&self) -> DIFSEL_13_R {
DIFSEL_13_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_14(&self) -> DIFSEL_14_R {
DIFSEL_14_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_15(&self) -> DIFSEL_15_R {
DIFSEL_15_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_16(&self) -> DIFSEL_16_R {
DIFSEL_16_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_17(&self) -> DIFSEL_17_R {
DIFSEL_17_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_18(&self) -> DIFSEL_18_R {
DIFSEL_18_R::new(((self.bits >> 18) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_0(&mut self) -> DIFSEL_0_W {
DIFSEL_0_W { w: self }
}
#[doc = "Bit 1 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_1(&mut self) -> DIFSEL_1_W {
DIFSEL_1_W { w: self }
}
#[doc = "Bit 2 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_2(&mut self) -> DIFSEL_2_W {
DIFSEL_2_W { w: self }
}
#[doc = "Bit 3 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_3(&mut self) -> DIFSEL_3_W {
DIFSEL_3_W { w: self }
}
#[doc = "Bit 4 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_4(&mut self) -> DIFSEL_4_W {
DIFSEL_4_W { w: self }
}
#[doc = "Bit 5 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_5(&mut self) -> DIFSEL_5_W {
DIFSEL_5_W { w: self }
}
#[doc = "Bit 6 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_6(&mut self) -> DIFSEL_6_W {
DIFSEL_6_W { w: self }
}
#[doc = "Bit 7 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_7(&mut self) -> DIFSEL_7_W {
DIFSEL_7_W { w: self }
}
#[doc = "Bit 8 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_8(&mut self) -> DIFSEL_8_W {
DIFSEL_8_W { w: self }
}
#[doc = "Bit 9 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_9(&mut self) -> DIFSEL_9_W {
DIFSEL_9_W { w: self }
}
#[doc = "Bit 10 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_10(&mut self) -> DIFSEL_10_W {
DIFSEL_10_W { w: self }
}
#[doc = "Bit 11 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_11(&mut self) -> DIFSEL_11_W {
DIFSEL_11_W { w: self }
}
#[doc = "Bit 12 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_12(&mut self) -> DIFSEL_12_W {
DIFSEL_12_W { w: self }
}
#[doc = "Bit 13 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_13(&mut self) -> DIFSEL_13_W {
DIFSEL_13_W { w: self }
}
#[doc = "Bit 14 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_14(&mut self) -> DIFSEL_14_W {
DIFSEL_14_W { w: self }
}
#[doc = "Bit 15 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_15(&mut self) -> DIFSEL_15_W {
DIFSEL_15_W { w: self }
}
#[doc = "Bit 16 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_16(&mut self) -> DIFSEL_16_W {
DIFSEL_16_W { w: self }
}
#[doc = "Bit 17 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_17(&mut self) -> DIFSEL_17_W {
DIFSEL_17_W { w: self }
}
#[doc = "Bit 18 - Differential mode for channels 0"]
#[inline(always)]
pub fn difsel_18(&mut self) -> DIFSEL_18_W {
DIFSEL_18_W { w: self }
}
}
|
pub use self::path::{ReadPath, WritePath};
pub use self::state::State;
use std::fmt::Debug;
use std::future::Future;
use std::pin::Pin;
use deck_core::FilesystemId;
mod path;
mod state;
// NOTE: All this noise has been to work fine with a simple `async fn`, with no need for associated
// types, this type alias, or `Pin<Box<_>>`. Replace _immediately_ once `async fn` in traits is
// stabilized in Rust.
pub type DirFuture<'a, T> = Pin<Box<dyn Future<Output = Result<T, ()>> + Send + 'a>>;
pub trait Directory: Debug + Send + Sync {
type Id: FilesystemId;
type Input: Send;
type Output: Send;
const NAME: &'static str;
fn precompute_id<'a>(&'a self, input: &'a Self::Input) -> DirFuture<'a, Self::Id>;
fn compute_id<'a>(&'a self, path: &'a ReadPath) -> DirFuture<'a, Self::Id>;
fn read<'a>(&'a self, path: &'a ReadPath) -> DirFuture<'a, Option<Self::Output>>;
fn write<'a>(
&'a self,
path: &'a mut WritePath,
input: Self::Input,
) -> DirFuture<'a, Self::Output>;
}
|
extern crate fiber;
use fiber::Fiber;
#[test]
fn basic_usage() {
fn fiber_proc(suspended: Fiber) -> ! {
println!("Suspended fiber: {:?}", suspended);
unsafe { suspended.resume(); }
panic!("Uh-oh, shouldn't have resumed this fiber again");
}
let fiber = Fiber::new(1024, fiber_proc);
let fiber_id = fiber.id();
let prev = unsafe { fiber.resume() };
assert_eq!(fiber_id, prev.id());
}
|
#[path = "spawn_link_1/with_function.rs"]
pub mod with_function;
// `without_function_errors_badarg` in unit tests
|
use std::io::{Read, Result as IOResult};
use nalgebra::{Vector2, Vector3};
use crate::{PrimitiveRead, BoneWeight};
#[derive(Clone)]
pub struct Vertex {
pub bone_weights: BoneWeight,
pub vec_position: Vector3<f32>,
pub vec_normal: Vector3<f32>,
pub vec_tex_coord: Vector2<f32>,
}
impl Vertex {
pub fn read(read: &mut dyn Read) -> IOResult<Self> {
let bone_weights = BoneWeight::read(read)?;
let vec_position = Vector3::<f32>::new(read.read_f32()?, read.read_f32()?, read.read_f32()?);
let vec_normal = Vector3::<f32>::new(read.read_f32()?, read.read_f32()?, read.read_f32()?);
let vec_tex_coord = Vector2::<f32>::new(read.read_f32()?, read.read_f32()?);
Ok(Self {
bone_weights,
vec_position,
vec_normal,
vec_tex_coord
})
}
}
|
pub mod entity;
pub mod camera;
|
// Code generated by software.amazon.smithy.rust.codegen.smithy-rs. DO NOT EDIT.
pub fn serialize_operation_create_replication_set(
input: &crate::input::CreateReplicationSetInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_replication_set_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_response_plan(
input: &crate::input::CreateResponsePlanInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_response_plan_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_create_timeline_event(
input: &crate::input::CreateTimelineEventInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_create_timeline_event_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_incident_record(
input: &crate::input::DeleteIncidentRecordInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_incident_record_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_resource_policy(
input: &crate::input::DeleteResourcePolicyInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_resource_policy_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_response_plan(
input: &crate::input::DeleteResponsePlanInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_response_plan_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_delete_timeline_event(
input: &crate::input::DeleteTimelineEventInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_delete_timeline_event_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_get_resource_policies(
input: &crate::input::GetResourcePoliciesInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_get_resource_policies_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_incident_records(
input: &crate::input::ListIncidentRecordsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_incident_records_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_related_items(
input: &crate::input::ListRelatedItemsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_related_items_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_replication_sets(
input: &crate::input::ListReplicationSetsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_replication_sets_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_response_plans(
input: &crate::input::ListResponsePlansInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_response_plans_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_list_timeline_events(
input: &crate::input::ListTimelineEventsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_list_timeline_events_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_put_resource_policy(
input: &crate::input::PutResourcePolicyInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_put_resource_policy_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_start_incident(
input: &crate::input::StartIncidentInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_start_incident_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_tag_resource(
input: &crate::input::TagResourceInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_tag_resource_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_deletion_protection(
input: &crate::input::UpdateDeletionProtectionInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_deletion_protection_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_incident_record(
input: &crate::input::UpdateIncidentRecordInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_incident_record_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_related_items(
input: &crate::input::UpdateRelatedItemsInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_related_items_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_replication_set(
input: &crate::input::UpdateReplicationSetInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_replication_set_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_response_plan(
input: &crate::input::UpdateResponsePlanInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_response_plan_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
pub fn serialize_operation_update_timeline_event(
input: &crate::input::UpdateTimelineEventInput,
) -> Result<smithy_http::body::SdkBody, smithy_types::Error> {
let mut out = String::new();
let mut object = smithy_json::serialize::JsonObjectWriter::new(&mut out);
crate::json_ser::serialize_structure_update_timeline_event_input(&mut object, input);
object.finish();
Ok(smithy_http::body::SdkBody::from(out))
}
|
// auto generated, do not modify.
// created: Wed Jan 20 00:44:03 2016
// src-file: /QtNetwork/qnetworkaccessmanager.h
// dst-file: /src/network/qnetworkaccessmanager.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::super::core::qobject::QObject; // 771
use std::ops::Deref;
use super::qnetworkcookiejar::QNetworkCookieJar; // 773
use super::qnetworkrequest::QNetworkRequest; // 773
use super::qhttpmultipart::QHttpMultiPart; // 773
use super::qnetworkreply::QNetworkReply; // 773
use super::super::core::qiodevice::QIODevice; // 771
use super::qnetworkconfiguration::QNetworkConfiguration; // 773
use super::super::core::qbytearray::QByteArray; // 771
use super::super::core::qstring::QString; // 771
use super::qsslconfiguration::QSslConfiguration; // 773
use super::qnetworkproxy::QNetworkProxyFactory; // 773
use super::qabstractnetworkcache::QAbstractNetworkCache; // 773
use super::qnetworkproxy::QNetworkProxy; // 773
use super::qauthenticator::QAuthenticator; // 773
use super::qsslpresharedkeyauthenticator::QSslPreSharedKeyAuthenticator; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QNetworkAccessManager_Class_Size() -> c_int;
// proto: void QNetworkAccessManager::setCookieJar(QNetworkCookieJar * cookieJar);
fn _ZN21QNetworkAccessManager12setCookieJarEP17QNetworkCookieJar(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QNetworkReply * QNetworkAccessManager::put(const QNetworkRequest & request, QHttpMultiPart * multiPart);
fn _ZN21QNetworkAccessManager3putERK15QNetworkRequestP14QHttpMultiPart(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: QNetworkCookieJar * QNetworkAccessManager::cookieJar();
fn _ZNK21QNetworkAccessManager9cookieJarEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: const QMetaObject * QNetworkAccessManager::metaObject();
fn _ZNK21QNetworkAccessManager10metaObjectEv(qthis: u64 /* *mut c_void*/);
// proto: QStringList QNetworkAccessManager::supportedSchemes();
fn _ZNK21QNetworkAccessManager16supportedSchemesEv(qthis: u64 /* *mut c_void*/);
// proto: QAbstractNetworkCache * QNetworkAccessManager::cache();
fn _ZNK21QNetworkAccessManager5cacheEv(qthis: u64 /* *mut c_void*/);
// proto: QNetworkReply * QNetworkAccessManager::put(const QNetworkRequest & request, QIODevice * data);
fn _ZN21QNetworkAccessManager3putERK15QNetworkRequestP9QIODevice(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QNetworkAccessManager::QNetworkAccessManager(QObject * parent);
fn _ZN21QNetworkAccessManagerC2EP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QNetworkReply * QNetworkAccessManager::get(const QNetworkRequest & request);
fn _ZN21QNetworkAccessManager3getERK15QNetworkRequest(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QNetworkReply * QNetworkAccessManager::deleteResource(const QNetworkRequest & request);
fn _ZN21QNetworkAccessManager14deleteResourceERK15QNetworkRequest(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QNetworkReply * QNetworkAccessManager::head(const QNetworkRequest & request);
fn _ZN21QNetworkAccessManager4headERK15QNetworkRequest(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QNetworkConfiguration QNetworkAccessManager::configuration();
fn _ZNK21QNetworkAccessManager13configurationEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QNetworkAccessManager::setConfiguration(const QNetworkConfiguration & config);
fn _ZN21QNetworkAccessManager16setConfigurationERK21QNetworkConfiguration(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QNetworkReply * QNetworkAccessManager::post(const QNetworkRequest & request, QIODevice * data);
fn _ZN21QNetworkAccessManager4postERK15QNetworkRequestP9QIODevice(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: QNetworkReply * QNetworkAccessManager::post(const QNetworkRequest & request, const QByteArray & data);
fn _ZN21QNetworkAccessManager4postERK15QNetworkRequestRK10QByteArray(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: QNetworkReply * QNetworkAccessManager::sendCustomRequest(const QNetworkRequest & request, const QByteArray & verb, QIODevice * data);
fn _ZN21QNetworkAccessManager17sendCustomRequestERK15QNetworkRequestRK10QByteArrayP9QIODevice(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
// proto: void QNetworkAccessManager::connectToHostEncrypted(const QString & hostName, quint16 port, const QSslConfiguration & sslConfiguration);
fn _ZN21QNetworkAccessManager22connectToHostEncryptedERK7QStringtRK17QSslConfiguration(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_ushort, arg2: *mut c_void);
// proto: void QNetworkAccessManager::clearAccessCache();
fn _ZN21QNetworkAccessManager16clearAccessCacheEv(qthis: u64 /* *mut c_void*/);
// proto: QNetworkConfiguration QNetworkAccessManager::activeConfiguration();
fn _ZNK21QNetworkAccessManager19activeConfigurationEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QNetworkAccessManager::setProxyFactory(QNetworkProxyFactory * factory);
fn _ZN21QNetworkAccessManager15setProxyFactoryEP20QNetworkProxyFactory(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkAccessManager::~QNetworkAccessManager();
fn _ZN21QNetworkAccessManagerD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QNetworkReply * QNetworkAccessManager::put(const QNetworkRequest & request, const QByteArray & data);
fn _ZN21QNetworkAccessManager3putERK15QNetworkRequestRK10QByteArray(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QNetworkAccessManager::setCache(QAbstractNetworkCache * cache);
fn _ZN21QNetworkAccessManager8setCacheEP21QAbstractNetworkCache(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QNetworkAccessManager::connectToHost(const QString & hostName, quint16 port);
fn _ZN21QNetworkAccessManager13connectToHostERK7QStringt(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: c_ushort);
// proto: void QNetworkAccessManager::setProxy(const QNetworkProxy & proxy);
fn _ZN21QNetworkAccessManager8setProxyERK13QNetworkProxy(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QNetworkProxy QNetworkAccessManager::proxy();
fn _ZNK21QNetworkAccessManager5proxyEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QNetworkReply * QNetworkAccessManager::post(const QNetworkRequest & request, QHttpMultiPart * multiPart);
fn _ZN21QNetworkAccessManager4postERK15QNetworkRequestP14QHttpMultiPart(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: QNetworkProxyFactory * QNetworkAccessManager::proxyFactory();
fn _ZNK21QNetworkAccessManager12proxyFactoryEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
fn QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager23networkSessionConnectedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager27proxyAuthenticationRequiredERK13QNetworkProxyP14QAuthenticator(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager34preSharedKeyAuthenticationRequiredEP13QNetworkReplyP29QSslPreSharedKeyAuthenticator(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager8finishedEP13QNetworkReply(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager9encryptedEP13QNetworkReply(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager22authenticationRequiredEP13QNetworkReplyP14QAuthenticator(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QNetworkAccessManager)=1
#[derive(Default)]
pub struct QNetworkAccessManager {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
pub _encrypted: QNetworkAccessManager_encrypted_signal,
pub _sslErrors: QNetworkAccessManager_sslErrors_signal,
pub _networkAccessibleChanged: QNetworkAccessManager_networkAccessibleChanged_signal,
pub _preSharedKeyAuthenticationRequired: QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal,
pub _finished: QNetworkAccessManager_finished_signal,
pub _proxyAuthenticationRequired: QNetworkAccessManager_proxyAuthenticationRequired_signal,
pub _authenticationRequired: QNetworkAccessManager_authenticationRequired_signal,
pub _networkSessionConnected: QNetworkAccessManager_networkSessionConnected_signal,
}
impl /*struct*/ QNetworkAccessManager {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QNetworkAccessManager {
return QNetworkAccessManager{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QNetworkAccessManager {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QNetworkAccessManager {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QNetworkAccessManager::setCookieJar(QNetworkCookieJar * cookieJar);
impl /*struct*/ QNetworkAccessManager {
pub fn setCookieJar<RetType, T: QNetworkAccessManager_setCookieJar<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCookieJar(self);
// return 1;
}
}
pub trait QNetworkAccessManager_setCookieJar<RetType> {
fn setCookieJar(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: void QNetworkAccessManager::setCookieJar(QNetworkCookieJar * cookieJar);
impl<'a> /*trait*/ QNetworkAccessManager_setCookieJar<()> for (&'a QNetworkCookieJar) {
fn setCookieJar(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager12setCookieJarEP17QNetworkCookieJar()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN21QNetworkAccessManager12setCookieJarEP17QNetworkCookieJar(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::put(const QNetworkRequest & request, QHttpMultiPart * multiPart);
impl /*struct*/ QNetworkAccessManager {
pub fn put<RetType, T: QNetworkAccessManager_put<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.put(self);
// return 1;
}
}
pub trait QNetworkAccessManager_put<RetType> {
fn put(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkReply * QNetworkAccessManager::put(const QNetworkRequest & request, QHttpMultiPart * multiPart);
impl<'a> /*trait*/ QNetworkAccessManager_put<QNetworkReply> for (&'a QNetworkRequest, &'a QHttpMultiPart) {
fn put(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager3putERK15QNetworkRequestP14QHttpMultiPart()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager3putERK15QNetworkRequestP14QHttpMultiPart(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QNetworkCookieJar * QNetworkAccessManager::cookieJar();
impl /*struct*/ QNetworkAccessManager {
pub fn cookieJar<RetType, T: QNetworkAccessManager_cookieJar<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.cookieJar(self);
// return 1;
}
}
pub trait QNetworkAccessManager_cookieJar<RetType> {
fn cookieJar(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkCookieJar * QNetworkAccessManager::cookieJar();
impl<'a> /*trait*/ QNetworkAccessManager_cookieJar<QNetworkCookieJar> for () {
fn cookieJar(self , rsthis: & QNetworkAccessManager) -> QNetworkCookieJar {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK21QNetworkAccessManager9cookieJarEv()};
let mut ret = unsafe {_ZNK21QNetworkAccessManager9cookieJarEv(rsthis.qclsinst)};
let mut ret1 = QNetworkCookieJar::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: const QMetaObject * QNetworkAccessManager::metaObject();
impl /*struct*/ QNetworkAccessManager {
pub fn metaObject<RetType, T: QNetworkAccessManager_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QNetworkAccessManager_metaObject<RetType> {
fn metaObject(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: const QMetaObject * QNetworkAccessManager::metaObject();
impl<'a> /*trait*/ QNetworkAccessManager_metaObject<()> for () {
fn metaObject(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK21QNetworkAccessManager10metaObjectEv()};
unsafe {_ZNK21QNetworkAccessManager10metaObjectEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QStringList QNetworkAccessManager::supportedSchemes();
impl /*struct*/ QNetworkAccessManager {
pub fn supportedSchemes<RetType, T: QNetworkAccessManager_supportedSchemes<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.supportedSchemes(self);
// return 1;
}
}
pub trait QNetworkAccessManager_supportedSchemes<RetType> {
fn supportedSchemes(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QStringList QNetworkAccessManager::supportedSchemes();
impl<'a> /*trait*/ QNetworkAccessManager_supportedSchemes<()> for () {
fn supportedSchemes(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK21QNetworkAccessManager16supportedSchemesEv()};
unsafe {_ZNK21QNetworkAccessManager16supportedSchemesEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QAbstractNetworkCache * QNetworkAccessManager::cache();
impl /*struct*/ QNetworkAccessManager {
pub fn cache<RetType, T: QNetworkAccessManager_cache<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.cache(self);
// return 1;
}
}
pub trait QNetworkAccessManager_cache<RetType> {
fn cache(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QAbstractNetworkCache * QNetworkAccessManager::cache();
impl<'a> /*trait*/ QNetworkAccessManager_cache<()> for () {
fn cache(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK21QNetworkAccessManager5cacheEv()};
unsafe {_ZNK21QNetworkAccessManager5cacheEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::put(const QNetworkRequest & request, QIODevice * data);
impl<'a> /*trait*/ QNetworkAccessManager_put<QNetworkReply> for (&'a QNetworkRequest, &'a QIODevice) {
fn put(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager3putERK15QNetworkRequestP9QIODevice()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager3putERK15QNetworkRequestP9QIODevice(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkAccessManager::QNetworkAccessManager(QObject * parent);
impl /*struct*/ QNetworkAccessManager {
pub fn new<T: QNetworkAccessManager_new>(value: T) -> QNetworkAccessManager {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QNetworkAccessManager_new {
fn new(self) -> QNetworkAccessManager;
}
// proto: void QNetworkAccessManager::QNetworkAccessManager(QObject * parent);
impl<'a> /*trait*/ QNetworkAccessManager_new for (&'a QObject) {
fn new(self) -> QNetworkAccessManager {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManagerC2EP7QObject()};
let ctysz: c_int = unsafe{QNetworkAccessManager_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN21QNetworkAccessManagerC2EP7QObject(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QNetworkAccessManager{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::get(const QNetworkRequest & request);
impl /*struct*/ QNetworkAccessManager {
pub fn get<RetType, T: QNetworkAccessManager_get<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.get(self);
// return 1;
}
}
pub trait QNetworkAccessManager_get<RetType> {
fn get(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkReply * QNetworkAccessManager::get(const QNetworkRequest & request);
impl<'a> /*trait*/ QNetworkAccessManager_get<QNetworkReply> for (&'a QNetworkRequest) {
fn get(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager3getERK15QNetworkRequest()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager3getERK15QNetworkRequest(rsthis.qclsinst, arg0)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::deleteResource(const QNetworkRequest & request);
impl /*struct*/ QNetworkAccessManager {
pub fn deleteResource<RetType, T: QNetworkAccessManager_deleteResource<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.deleteResource(self);
// return 1;
}
}
pub trait QNetworkAccessManager_deleteResource<RetType> {
fn deleteResource(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkReply * QNetworkAccessManager::deleteResource(const QNetworkRequest & request);
impl<'a> /*trait*/ QNetworkAccessManager_deleteResource<QNetworkReply> for (&'a QNetworkRequest) {
fn deleteResource(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager14deleteResourceERK15QNetworkRequest()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager14deleteResourceERK15QNetworkRequest(rsthis.qclsinst, arg0)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::head(const QNetworkRequest & request);
impl /*struct*/ QNetworkAccessManager {
pub fn head<RetType, T: QNetworkAccessManager_head<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.head(self);
// return 1;
}
}
pub trait QNetworkAccessManager_head<RetType> {
fn head(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkReply * QNetworkAccessManager::head(const QNetworkRequest & request);
impl<'a> /*trait*/ QNetworkAccessManager_head<QNetworkReply> for (&'a QNetworkRequest) {
fn head(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager4headERK15QNetworkRequest()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager4headERK15QNetworkRequest(rsthis.qclsinst, arg0)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QNetworkConfiguration QNetworkAccessManager::configuration();
impl /*struct*/ QNetworkAccessManager {
pub fn configuration<RetType, T: QNetworkAccessManager_configuration<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.configuration(self);
// return 1;
}
}
pub trait QNetworkAccessManager_configuration<RetType> {
fn configuration(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkConfiguration QNetworkAccessManager::configuration();
impl<'a> /*trait*/ QNetworkAccessManager_configuration<QNetworkConfiguration> for () {
fn configuration(self , rsthis: & QNetworkAccessManager) -> QNetworkConfiguration {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK21QNetworkAccessManager13configurationEv()};
let mut ret = unsafe {_ZNK21QNetworkAccessManager13configurationEv(rsthis.qclsinst)};
let mut ret1 = QNetworkConfiguration::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkAccessManager::setConfiguration(const QNetworkConfiguration & config);
impl /*struct*/ QNetworkAccessManager {
pub fn setConfiguration<RetType, T: QNetworkAccessManager_setConfiguration<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setConfiguration(self);
// return 1;
}
}
pub trait QNetworkAccessManager_setConfiguration<RetType> {
fn setConfiguration(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: void QNetworkAccessManager::setConfiguration(const QNetworkConfiguration & config);
impl<'a> /*trait*/ QNetworkAccessManager_setConfiguration<()> for (&'a QNetworkConfiguration) {
fn setConfiguration(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager16setConfigurationERK21QNetworkConfiguration()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN21QNetworkAccessManager16setConfigurationERK21QNetworkConfiguration(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::post(const QNetworkRequest & request, QIODevice * data);
impl /*struct*/ QNetworkAccessManager {
pub fn post<RetType, T: QNetworkAccessManager_post<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.post(self);
// return 1;
}
}
pub trait QNetworkAccessManager_post<RetType> {
fn post(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkReply * QNetworkAccessManager::post(const QNetworkRequest & request, QIODevice * data);
impl<'a> /*trait*/ QNetworkAccessManager_post<QNetworkReply> for (&'a QNetworkRequest, &'a QIODevice) {
fn post(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager4postERK15QNetworkRequestP9QIODevice()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager4postERK15QNetworkRequestP9QIODevice(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::post(const QNetworkRequest & request, const QByteArray & data);
impl<'a> /*trait*/ QNetworkAccessManager_post<QNetworkReply> for (&'a QNetworkRequest, &'a QByteArray) {
fn post(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager4postERK15QNetworkRequestRK10QByteArray()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager4postERK15QNetworkRequestRK10QByteArray(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::sendCustomRequest(const QNetworkRequest & request, const QByteArray & verb, QIODevice * data);
impl /*struct*/ QNetworkAccessManager {
pub fn sendCustomRequest<RetType, T: QNetworkAccessManager_sendCustomRequest<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sendCustomRequest(self);
// return 1;
}
}
pub trait QNetworkAccessManager_sendCustomRequest<RetType> {
fn sendCustomRequest(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkReply * QNetworkAccessManager::sendCustomRequest(const QNetworkRequest & request, const QByteArray & verb, QIODevice * data);
impl<'a> /*trait*/ QNetworkAccessManager_sendCustomRequest<QNetworkReply> for (&'a QNetworkRequest, &'a QByteArray, &'a QIODevice) {
fn sendCustomRequest(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager17sendCustomRequestERK15QNetworkRequestRK10QByteArrayP9QIODevice()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let arg2 = self.2.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager17sendCustomRequestERK15QNetworkRequestRK10QByteArrayP9QIODevice(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkAccessManager::connectToHostEncrypted(const QString & hostName, quint16 port, const QSslConfiguration & sslConfiguration);
impl /*struct*/ QNetworkAccessManager {
pub fn connectToHostEncrypted<RetType, T: QNetworkAccessManager_connectToHostEncrypted<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.connectToHostEncrypted(self);
// return 1;
}
}
pub trait QNetworkAccessManager_connectToHostEncrypted<RetType> {
fn connectToHostEncrypted(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: void QNetworkAccessManager::connectToHostEncrypted(const QString & hostName, quint16 port, const QSslConfiguration & sslConfiguration);
impl<'a> /*trait*/ QNetworkAccessManager_connectToHostEncrypted<()> for (&'a QString, u16, &'a QSslConfiguration) {
fn connectToHostEncrypted(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager22connectToHostEncryptedERK7QStringtRK17QSslConfiguration()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_ushort;
let arg2 = self.2.qclsinst as *mut c_void;
unsafe {_ZN21QNetworkAccessManager22connectToHostEncryptedERK7QStringtRK17QSslConfiguration(rsthis.qclsinst, arg0, arg1, arg2)};
// return 1;
}
}
// proto: void QNetworkAccessManager::clearAccessCache();
impl /*struct*/ QNetworkAccessManager {
pub fn clearAccessCache<RetType, T: QNetworkAccessManager_clearAccessCache<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clearAccessCache(self);
// return 1;
}
}
pub trait QNetworkAccessManager_clearAccessCache<RetType> {
fn clearAccessCache(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: void QNetworkAccessManager::clearAccessCache();
impl<'a> /*trait*/ QNetworkAccessManager_clearAccessCache<()> for () {
fn clearAccessCache(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager16clearAccessCacheEv()};
unsafe {_ZN21QNetworkAccessManager16clearAccessCacheEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: QNetworkConfiguration QNetworkAccessManager::activeConfiguration();
impl /*struct*/ QNetworkAccessManager {
pub fn activeConfiguration<RetType, T: QNetworkAccessManager_activeConfiguration<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.activeConfiguration(self);
// return 1;
}
}
pub trait QNetworkAccessManager_activeConfiguration<RetType> {
fn activeConfiguration(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkConfiguration QNetworkAccessManager::activeConfiguration();
impl<'a> /*trait*/ QNetworkAccessManager_activeConfiguration<QNetworkConfiguration> for () {
fn activeConfiguration(self , rsthis: & QNetworkAccessManager) -> QNetworkConfiguration {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK21QNetworkAccessManager19activeConfigurationEv()};
let mut ret = unsafe {_ZNK21QNetworkAccessManager19activeConfigurationEv(rsthis.qclsinst)};
let mut ret1 = QNetworkConfiguration::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkAccessManager::setProxyFactory(QNetworkProxyFactory * factory);
impl /*struct*/ QNetworkAccessManager {
pub fn setProxyFactory<RetType, T: QNetworkAccessManager_setProxyFactory<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setProxyFactory(self);
// return 1;
}
}
pub trait QNetworkAccessManager_setProxyFactory<RetType> {
fn setProxyFactory(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: void QNetworkAccessManager::setProxyFactory(QNetworkProxyFactory * factory);
impl<'a> /*trait*/ QNetworkAccessManager_setProxyFactory<()> for (&'a QNetworkProxyFactory) {
fn setProxyFactory(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager15setProxyFactoryEP20QNetworkProxyFactory()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN21QNetworkAccessManager15setProxyFactoryEP20QNetworkProxyFactory(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkAccessManager::~QNetworkAccessManager();
impl /*struct*/ QNetworkAccessManager {
pub fn free<RetType, T: QNetworkAccessManager_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QNetworkAccessManager_free<RetType> {
fn free(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: void QNetworkAccessManager::~QNetworkAccessManager();
impl<'a> /*trait*/ QNetworkAccessManager_free<()> for () {
fn free(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManagerD2Ev()};
unsafe {_ZN21QNetworkAccessManagerD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::put(const QNetworkRequest & request, const QByteArray & data);
impl<'a> /*trait*/ QNetworkAccessManager_put<QNetworkReply> for (&'a QNetworkRequest, &'a QByteArray) {
fn put(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager3putERK15QNetworkRequestRK10QByteArray()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager3putERK15QNetworkRequestRK10QByteArray(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QNetworkAccessManager::setCache(QAbstractNetworkCache * cache);
impl /*struct*/ QNetworkAccessManager {
pub fn setCache<RetType, T: QNetworkAccessManager_setCache<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setCache(self);
// return 1;
}
}
pub trait QNetworkAccessManager_setCache<RetType> {
fn setCache(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: void QNetworkAccessManager::setCache(QAbstractNetworkCache * cache);
impl<'a> /*trait*/ QNetworkAccessManager_setCache<()> for (&'a QAbstractNetworkCache) {
fn setCache(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager8setCacheEP21QAbstractNetworkCache()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN21QNetworkAccessManager8setCacheEP21QAbstractNetworkCache(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QNetworkAccessManager::connectToHost(const QString & hostName, quint16 port);
impl /*struct*/ QNetworkAccessManager {
pub fn connectToHost<RetType, T: QNetworkAccessManager_connectToHost<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.connectToHost(self);
// return 1;
}
}
pub trait QNetworkAccessManager_connectToHost<RetType> {
fn connectToHost(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: void QNetworkAccessManager::connectToHost(const QString & hostName, quint16 port);
impl<'a> /*trait*/ QNetworkAccessManager_connectToHost<()> for (&'a QString, u16) {
fn connectToHost(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager13connectToHostERK7QStringt()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1 as c_ushort;
unsafe {_ZN21QNetworkAccessManager13connectToHostERK7QStringt(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: void QNetworkAccessManager::setProxy(const QNetworkProxy & proxy);
impl /*struct*/ QNetworkAccessManager {
pub fn setProxy<RetType, T: QNetworkAccessManager_setProxy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setProxy(self);
// return 1;
}
}
pub trait QNetworkAccessManager_setProxy<RetType> {
fn setProxy(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: void QNetworkAccessManager::setProxy(const QNetworkProxy & proxy);
impl<'a> /*trait*/ QNetworkAccessManager_setProxy<()> for (&'a QNetworkProxy) {
fn setProxy(self , rsthis: & QNetworkAccessManager) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager8setProxyERK13QNetworkProxy()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN21QNetworkAccessManager8setProxyERK13QNetworkProxy(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QNetworkProxy QNetworkAccessManager::proxy();
impl /*struct*/ QNetworkAccessManager {
pub fn proxy<RetType, T: QNetworkAccessManager_proxy<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.proxy(self);
// return 1;
}
}
pub trait QNetworkAccessManager_proxy<RetType> {
fn proxy(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkProxy QNetworkAccessManager::proxy();
impl<'a> /*trait*/ QNetworkAccessManager_proxy<QNetworkProxy> for () {
fn proxy(self , rsthis: & QNetworkAccessManager) -> QNetworkProxy {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK21QNetworkAccessManager5proxyEv()};
let mut ret = unsafe {_ZNK21QNetworkAccessManager5proxyEv(rsthis.qclsinst)};
let mut ret1 = QNetworkProxy::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QNetworkReply * QNetworkAccessManager::post(const QNetworkRequest & request, QHttpMultiPart * multiPart);
impl<'a> /*trait*/ QNetworkAccessManager_post<QNetworkReply> for (&'a QNetworkRequest, &'a QHttpMultiPart) {
fn post(self , rsthis: & QNetworkAccessManager) -> QNetworkReply {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN21QNetworkAccessManager4postERK15QNetworkRequestP14QHttpMultiPart()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {_ZN21QNetworkAccessManager4postERK15QNetworkRequestP14QHttpMultiPart(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QNetworkReply::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QNetworkProxyFactory * QNetworkAccessManager::proxyFactory();
impl /*struct*/ QNetworkAccessManager {
pub fn proxyFactory<RetType, T: QNetworkAccessManager_proxyFactory<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.proxyFactory(self);
// return 1;
}
}
pub trait QNetworkAccessManager_proxyFactory<RetType> {
fn proxyFactory(self , rsthis: & QNetworkAccessManager) -> RetType;
}
// proto: QNetworkProxyFactory * QNetworkAccessManager::proxyFactory();
impl<'a> /*trait*/ QNetworkAccessManager_proxyFactory<QNetworkProxyFactory> for () {
fn proxyFactory(self , rsthis: & QNetworkAccessManager) -> QNetworkProxyFactory {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK21QNetworkAccessManager12proxyFactoryEv()};
let mut ret = unsafe {_ZNK21QNetworkAccessManager12proxyFactoryEv(rsthis.qclsinst)};
let mut ret1 = QNetworkProxyFactory::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
#[derive(Default)] // for QNetworkAccessManager_encrypted
pub struct QNetworkAccessManager_encrypted_signal{poi:u64}
impl /* struct */ QNetworkAccessManager {
pub fn encrypted(&self) -> QNetworkAccessManager_encrypted_signal {
return QNetworkAccessManager_encrypted_signal{poi:self.qclsinst};
}
}
impl /* struct */ QNetworkAccessManager_encrypted_signal {
pub fn connect<T: QNetworkAccessManager_encrypted_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QNetworkAccessManager_encrypted_signal_connect {
fn connect(self, sigthis: QNetworkAccessManager_encrypted_signal);
}
#[derive(Default)] // for QNetworkAccessManager_sslErrors
pub struct QNetworkAccessManager_sslErrors_signal{poi:u64}
impl /* struct */ QNetworkAccessManager {
pub fn sslErrors(&self) -> QNetworkAccessManager_sslErrors_signal {
return QNetworkAccessManager_sslErrors_signal{poi:self.qclsinst};
}
}
impl /* struct */ QNetworkAccessManager_sslErrors_signal {
pub fn connect<T: QNetworkAccessManager_sslErrors_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QNetworkAccessManager_sslErrors_signal_connect {
fn connect(self, sigthis: QNetworkAccessManager_sslErrors_signal);
}
#[derive(Default)] // for QNetworkAccessManager_networkAccessibleChanged
pub struct QNetworkAccessManager_networkAccessibleChanged_signal{poi:u64}
impl /* struct */ QNetworkAccessManager {
pub fn networkAccessibleChanged(&self) -> QNetworkAccessManager_networkAccessibleChanged_signal {
return QNetworkAccessManager_networkAccessibleChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QNetworkAccessManager_networkAccessibleChanged_signal {
pub fn connect<T: QNetworkAccessManager_networkAccessibleChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QNetworkAccessManager_networkAccessibleChanged_signal_connect {
fn connect(self, sigthis: QNetworkAccessManager_networkAccessibleChanged_signal);
}
#[derive(Default)] // for QNetworkAccessManager_preSharedKeyAuthenticationRequired
pub struct QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal{poi:u64}
impl /* struct */ QNetworkAccessManager {
pub fn preSharedKeyAuthenticationRequired(&self) -> QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal {
return QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal{poi:self.qclsinst};
}
}
impl /* struct */ QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal {
pub fn connect<T: QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal_connect {
fn connect(self, sigthis: QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal);
}
#[derive(Default)] // for QNetworkAccessManager_finished
pub struct QNetworkAccessManager_finished_signal{poi:u64}
impl /* struct */ QNetworkAccessManager {
pub fn finished(&self) -> QNetworkAccessManager_finished_signal {
return QNetworkAccessManager_finished_signal{poi:self.qclsinst};
}
}
impl /* struct */ QNetworkAccessManager_finished_signal {
pub fn connect<T: QNetworkAccessManager_finished_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QNetworkAccessManager_finished_signal_connect {
fn connect(self, sigthis: QNetworkAccessManager_finished_signal);
}
#[derive(Default)] // for QNetworkAccessManager_proxyAuthenticationRequired
pub struct QNetworkAccessManager_proxyAuthenticationRequired_signal{poi:u64}
impl /* struct */ QNetworkAccessManager {
pub fn proxyAuthenticationRequired(&self) -> QNetworkAccessManager_proxyAuthenticationRequired_signal {
return QNetworkAccessManager_proxyAuthenticationRequired_signal{poi:self.qclsinst};
}
}
impl /* struct */ QNetworkAccessManager_proxyAuthenticationRequired_signal {
pub fn connect<T: QNetworkAccessManager_proxyAuthenticationRequired_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QNetworkAccessManager_proxyAuthenticationRequired_signal_connect {
fn connect(self, sigthis: QNetworkAccessManager_proxyAuthenticationRequired_signal);
}
#[derive(Default)] // for QNetworkAccessManager_authenticationRequired
pub struct QNetworkAccessManager_authenticationRequired_signal{poi:u64}
impl /* struct */ QNetworkAccessManager {
pub fn authenticationRequired(&self) -> QNetworkAccessManager_authenticationRequired_signal {
return QNetworkAccessManager_authenticationRequired_signal{poi:self.qclsinst};
}
}
impl /* struct */ QNetworkAccessManager_authenticationRequired_signal {
pub fn connect<T: QNetworkAccessManager_authenticationRequired_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QNetworkAccessManager_authenticationRequired_signal_connect {
fn connect(self, sigthis: QNetworkAccessManager_authenticationRequired_signal);
}
#[derive(Default)] // for QNetworkAccessManager_networkSessionConnected
pub struct QNetworkAccessManager_networkSessionConnected_signal{poi:u64}
impl /* struct */ QNetworkAccessManager {
pub fn networkSessionConnected(&self) -> QNetworkAccessManager_networkSessionConnected_signal {
return QNetworkAccessManager_networkSessionConnected_signal{poi:self.qclsinst};
}
}
impl /* struct */ QNetworkAccessManager_networkSessionConnected_signal {
pub fn connect<T: QNetworkAccessManager_networkSessionConnected_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QNetworkAccessManager_networkSessionConnected_signal_connect {
fn connect(self, sigthis: QNetworkAccessManager_networkSessionConnected_signal);
}
// networkSessionConnected()
extern fn QNetworkAccessManager_networkSessionConnected_signal_connect_cb_0(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QNetworkAccessManager_networkSessionConnected_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QNetworkAccessManager_networkSessionConnected_signal_connect for fn() {
fn connect(self, sigthis: QNetworkAccessManager_networkSessionConnected_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_networkSessionConnected_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager23networkSessionConnectedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QNetworkAccessManager_networkSessionConnected_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QNetworkAccessManager_networkSessionConnected_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_networkSessionConnected_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager23networkSessionConnectedEv(arg0, arg1, arg2)};
}
}
// proxyAuthenticationRequired(const class QNetworkProxy &, class QAuthenticator *)
extern fn QNetworkAccessManager_proxyAuthenticationRequired_signal_connect_cb_1(rsfptr:fn(QNetworkProxy, QAuthenticator), arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QNetworkProxy::inheritFrom(arg0 as u64);
let rsarg1 = QAuthenticator::inheritFrom(arg1 as u64);
rsfptr(rsarg0,rsarg1);
}
extern fn QNetworkAccessManager_proxyAuthenticationRequired_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(QNetworkProxy, QAuthenticator)>, arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QNetworkProxy::inheritFrom(arg0 as u64);
let rsarg1 = QAuthenticator::inheritFrom(arg1 as u64);
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QNetworkAccessManager_proxyAuthenticationRequired_signal_connect for fn(QNetworkProxy, QAuthenticator) {
fn connect(self, sigthis: QNetworkAccessManager_proxyAuthenticationRequired_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_proxyAuthenticationRequired_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager27proxyAuthenticationRequiredERK13QNetworkProxyP14QAuthenticator(arg0, arg1, arg2)};
}
}
impl /* trait */ QNetworkAccessManager_proxyAuthenticationRequired_signal_connect for Box<Fn(QNetworkProxy, QAuthenticator)> {
fn connect(self, sigthis: QNetworkAccessManager_proxyAuthenticationRequired_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_proxyAuthenticationRequired_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager27proxyAuthenticationRequiredERK13QNetworkProxyP14QAuthenticator(arg0, arg1, arg2)};
}
}
// preSharedKeyAuthenticationRequired(class QNetworkReply *, class QSslPreSharedKeyAuthenticator *)
extern fn QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal_connect_cb_2(rsfptr:fn(QNetworkReply, QSslPreSharedKeyAuthenticator), arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QNetworkReply::inheritFrom(arg0 as u64);
let rsarg1 = QSslPreSharedKeyAuthenticator::inheritFrom(arg1 as u64);
rsfptr(rsarg0,rsarg1);
}
extern fn QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal_connect_cb_box_2(rsfptr_raw:*mut Box<Fn(QNetworkReply, QSslPreSharedKeyAuthenticator)>, arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QNetworkReply::inheritFrom(arg0 as u64);
let rsarg1 = QSslPreSharedKeyAuthenticator::inheritFrom(arg1 as u64);
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal_connect for fn(QNetworkReply, QSslPreSharedKeyAuthenticator) {
fn connect(self, sigthis: QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal_connect_cb_2 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager34preSharedKeyAuthenticationRequiredEP13QNetworkReplyP29QSslPreSharedKeyAuthenticator(arg0, arg1, arg2)};
}
}
impl /* trait */ QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal_connect for Box<Fn(QNetworkReply, QSslPreSharedKeyAuthenticator)> {
fn connect(self, sigthis: QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_preSharedKeyAuthenticationRequired_signal_connect_cb_box_2 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager34preSharedKeyAuthenticationRequiredEP13QNetworkReplyP29QSslPreSharedKeyAuthenticator(arg0, arg1, arg2)};
}
}
// finished(class QNetworkReply *)
extern fn QNetworkAccessManager_finished_signal_connect_cb_3(rsfptr:fn(QNetworkReply), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QNetworkReply::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QNetworkAccessManager_finished_signal_connect_cb_box_3(rsfptr_raw:*mut Box<Fn(QNetworkReply)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QNetworkReply::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QNetworkAccessManager_finished_signal_connect for fn(QNetworkReply) {
fn connect(self, sigthis: QNetworkAccessManager_finished_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_finished_signal_connect_cb_3 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager8finishedEP13QNetworkReply(arg0, arg1, arg2)};
}
}
impl /* trait */ QNetworkAccessManager_finished_signal_connect for Box<Fn(QNetworkReply)> {
fn connect(self, sigthis: QNetworkAccessManager_finished_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_finished_signal_connect_cb_box_3 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager8finishedEP13QNetworkReply(arg0, arg1, arg2)};
}
}
// encrypted(class QNetworkReply *)
extern fn QNetworkAccessManager_encrypted_signal_connect_cb_4(rsfptr:fn(QNetworkReply), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QNetworkReply::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QNetworkAccessManager_encrypted_signal_connect_cb_box_4(rsfptr_raw:*mut Box<Fn(QNetworkReply)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QNetworkReply::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QNetworkAccessManager_encrypted_signal_connect for fn(QNetworkReply) {
fn connect(self, sigthis: QNetworkAccessManager_encrypted_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_encrypted_signal_connect_cb_4 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager9encryptedEP13QNetworkReply(arg0, arg1, arg2)};
}
}
impl /* trait */ QNetworkAccessManager_encrypted_signal_connect for Box<Fn(QNetworkReply)> {
fn connect(self, sigthis: QNetworkAccessManager_encrypted_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_encrypted_signal_connect_cb_box_4 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager9encryptedEP13QNetworkReply(arg0, arg1, arg2)};
}
}
// authenticationRequired(class QNetworkReply *, class QAuthenticator *)
extern fn QNetworkAccessManager_authenticationRequired_signal_connect_cb_5(rsfptr:fn(QNetworkReply, QAuthenticator), arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QNetworkReply::inheritFrom(arg0 as u64);
let rsarg1 = QAuthenticator::inheritFrom(arg1 as u64);
rsfptr(rsarg0,rsarg1);
}
extern fn QNetworkAccessManager_authenticationRequired_signal_connect_cb_box_5(rsfptr_raw:*mut Box<Fn(QNetworkReply, QAuthenticator)>, arg0: *mut c_void, arg1: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QNetworkReply::inheritFrom(arg0 as u64);
let rsarg1 = QAuthenticator::inheritFrom(arg1 as u64);
// rsfptr(rsarg0,rsarg1);
unsafe{(*rsfptr_raw)(rsarg0,rsarg1)};
}
impl /* trait */ QNetworkAccessManager_authenticationRequired_signal_connect for fn(QNetworkReply, QAuthenticator) {
fn connect(self, sigthis: QNetworkAccessManager_authenticationRequired_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_authenticationRequired_signal_connect_cb_5 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager22authenticationRequiredEP13QNetworkReplyP14QAuthenticator(arg0, arg1, arg2)};
}
}
impl /* trait */ QNetworkAccessManager_authenticationRequired_signal_connect for Box<Fn(QNetworkReply, QAuthenticator)> {
fn connect(self, sigthis: QNetworkAccessManager_authenticationRequired_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QNetworkAccessManager_authenticationRequired_signal_connect_cb_box_5 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QNetworkAccessManager_SlotProxy_connect__ZN21QNetworkAccessManager22authenticationRequiredEP13QNetworkReplyP14QAuthenticator(arg0, arg1, arg2)};
}
}
// <= body block end
|
use std::fmt;
use std::iter;
use std::ops::{Index, Mul};
use super::tools::iter_complement;
/// Naive representation of a matrix as a single consecutive chunk of memory.
pub struct Matrix<T> {
height: usize,
width: usize,
data: Vec<T>,
}
// Custom trait for matrices that can be right-multiplied by a column vector.
pub trait ColMul<U> {
fn col_mul(&self, column: &Vec<U>) -> Vec<U>;
}
impl<'a, T> Matrix<T>
where
T: Copy + Default,
{
/// Create a matrix filled with one value.
pub fn new(height: usize, width: usize, value: T) -> Matrix<T> {
Matrix {
width,
height,
data: vec![value; width * height],
}
}
pub fn get_height(&self) -> usize {
self.height
}
pub fn get_width(&self) -> usize {
self.width
}
/// Mutable access to an element of the matrix.
pub fn at(&mut self, row: usize, col: usize) -> &mut T {
let index = self.data_index(row, col);
&mut self.data[index]
}
/// Get an iterator over a column of the matrix.
pub fn iter_col(&self, col: usize) -> impl Iterator<Item = &T> {
debug_assert!(col < self.width);
self.data
.iter()
.skip(col)
.step_by(self.width)
.take(self.height)
}
/// Get an iterator over a row of the matrix.
pub fn iter_row(&self, row: usize) -> impl Iterator<Item = &T> {
debug_assert!(row < self.height);
self.data.iter().skip(row * self.width).take(self.width)
}
/// Truncate rows and columns from a matrix.
pub fn truncate<U, V>(&self, del_rows: U, del_cols: V) -> Matrix<T>
where
U: Iterator<Item = usize>,
V: Iterator<Item = usize>,
{
let kept_rows = iter_complement(0, self.height, del_rows);
let kept_cols = iter_complement(0, self.width, del_cols);
self.submatrix_sorted(kept_rows, kept_cols)
}
pub fn del_row(&self, row: usize) -> Matrix<T> {
self.truncate(iter::once(row), iter::empty())
}
pub fn del_col(&self, col: usize) -> Matrix<T> {
self.truncate(iter::empty(), iter::once(col))
}
/// Get the index of a cell in the data vector.
fn data_index(&self, row: usize, col: usize) -> usize {
debug_assert!(col < self.width);
debug_assert!(row < self.height);
col + (row * self.width)
}
/// Get a submatrix containing only some rows and columns given as sorted
/// iterator.
fn submatrix_sorted<U, V>(&self, rows: U, cols: V) -> Matrix<T>
where
U: Iterator<Item = usize> + Clone,
V: Iterator<Item = usize> + Clone,
T: Clone,
{
let mut all_data_iter = self.data.iter();
let indices = rows
.clone()
.map(|row| cols.clone().map(move |col| self.data_index(row, col)))
.flatten();
let data: Vec<_> = indices
.scan(0, |expected_index, index| {
let val = all_data_iter.nth(index - *expected_index);
*expected_index = index + 1;
val.cloned()
})
.collect();
Matrix {
width: cols.count(),
height: rows.count(),
data,
}
}
}
impl<T> Index<(usize, usize)> for Matrix<T>
where
T: Copy + Default,
{
type Output = T;
fn index(&self, (row, col): (usize, usize)) -> &T {
&self.data[self.data_index(row, col)]
}
}
// ____ _
// | __ ) ___ ___ | | ___ __ _ _ __
// | _ \ / _ \ / _ \| |/ _ \/ _` | '_ \
// | |_) | (_) | (_) | | __/ (_| | | | |
// |____/ \___/ \___/|_|\___|\__,_|_| |_|
// __ __ _ _
// | \/ | __ _| |_ _ __(_)_ __
// | |\/| |/ _` | __| '__| \ \/ /
// | | | | (_| | |_| | | |> <
// |_| |_|\__,_|\__|_| |_/_/\_\
//
impl Mul for &Matrix<bool> {
type Output = Matrix<bool>;
fn mul(self, other: &Matrix<bool>) -> Matrix<bool> {
let data = (0..self.height)
.map(|row| {
(0..other.width).map(move |col| {
let row_iter = self.iter_row(row);
let col_iter = other.iter_col(col);
row_iter.zip(col_iter).any(|(&x, &y)| x && y)
})
})
.flatten()
.collect();
Matrix {
width: other.width,
height: self.height,
data,
}
}
}
impl ColMul<bool> for Matrix<bool> {
fn col_mul(&self, column: &Vec<bool>) -> Vec<bool> {
(0..self.height)
.map(|row| {
let row_iter = self.iter_row(row);
let col_iter = column.iter();
row_iter.zip(col_iter).any(|(&x, &y)| x && y)
})
.collect()
}
}
// ____ _
// | _ \ ___| |__ _ _ __ _
// | | | |/ _ \ '_ \| | | |/ _` |
// | |_| | __/ |_) | |_| | (_| |
// |____/ \___|_.__/ \__,_|\__, |
// |___/
impl fmt::Debug for Matrix<bool> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let content = (0..self.height)
.map(|row| {
let row = self
.iter_row(row)
.map(|x| match x {
true => "T",
false => "F",
})
.collect::<Vec<_>>()
.join(", ");
format!("[{}]", row)
})
.collect::<Vec<_>>()
.join(",\n ");
write!(f, "[{}]\n", content)
}
}
|
use std::mem::ManuallyDrop;
use win32_error::Win32Error;
use winapi::um::{
handleapi::CloseHandle,
memoryapi::{ReadProcessMemory, VirtualAllocEx, VirtualFreeEx, WriteProcessMemory},
processthreadsapi::CreateRemoteThread,
synchapi::WaitForSingleObject,
winbase::*,
winnt::*,
};
use crate::os::windows::{MemAccessExt, ProcessExt};
use crate::process::MemAccess;
use crate::{Error, Result};
pub struct Process {
handle: HANDLE,
}
impl ProcessExt for Process {
fn to_raw_handle(&self) -> HANDLE {
self.handle
}
fn into_raw_handle(self) -> HANDLE {
let guard = ManuallyDrop::new(self);
guard.handle
}
unsafe fn from_raw_handle(handle: HANDLE) -> Self {
Process { handle }
}
}
impl Process {
pub unsafe fn alloc_memory(&mut self, size: usize, access: MemAccess) -> Result<usize> {
// TODO: memory protection control
let ptr = VirtualAllocEx(
self.handle,
std::ptr::null_mut(),
size,
MEM_RESERVE | MEM_COMMIT,
access.into_page_protect_loose(),
);
if !ptr.is_null() {
Ok(ptr as usize)
} else {
Err(Error::Win32Error(Win32Error::new()))
}
}
pub unsafe fn dealloc_memory(&mut self, addr: usize) -> Result<()> {
let result = VirtualFreeEx(self.handle, addr as *mut _, 0, MEM_RELEASE);
if result != 0 {
Ok(())
} else {
Err(Error::Win32Error(Win32Error::new()))
}
}
pub unsafe fn read_memory_raw<T>(
&mut self,
addr: usize,
data: *mut T,
num_bytes: usize,
) -> Result<()> {
let mut bytes_read = 0;
let result = ReadProcessMemory(
self.handle,
addr as *const _,
data as *mut _,
num_bytes,
&mut bytes_read,
);
if result == 0 {
return Err(Error::Win32Error(Win32Error::new()));
}
assert_eq!(bytes_read, num_bytes);
Ok(())
}
pub unsafe fn write_memory_raw<T>(
&mut self,
addr: usize,
data: *const T,
num_bytes: usize,
) -> Result<()> {
let mut bytes_written = 0;
let result = WriteProcessMemory(
self.handle,
addr as *mut _,
data as *const _,
num_bytes,
&mut bytes_written,
);
if result == 0 {
return Err(Error::Win32Error(Win32Error::new()));
}
assert_eq!(bytes_written, num_bytes);
Ok(())
}
pub unsafe fn call_function(&mut self, addr: usize, arg: usize) -> Result<()> {
let handle = CreateRemoteThread(
self.handle,
std::ptr::null_mut(),
0,
Some(std::mem::transmute(addr)),
arg as *mut _,
0,
std::ptr::null_mut(),
);
if handle.is_null() {
return Err(Error::CreateThreadError(Win32Error::new()));
}
let result = WaitForSingleObject(handle, INFINITE);
if result == WAIT_OBJECT_0 {
Ok(())
} else if result == WAIT_FAILED {
Err(Error::WaitForThreadError(Win32Error::new()))
} else {
panic!(format!(
"unexpected return value from WaitForSingleObject: {:#X}",
result
))
}
}
}
impl Drop for Process {
fn drop(&mut self) {
unsafe {
CloseHandle(self.handle);
// the return value is silently ignored
}
}
}
|
use super::super::constants::*;
use super::FileTypeTrait;
use libc::c_int;
use std::fs;
#[derive(Debug, Clone)]
pub enum FileType {
File,
Directory,
Symlink,
Unknown,
}
impl FileType {
pub fn from_ftw(ftw: c_int) -> Self {
match ftw {
FTW_F => FileType::File,
FTW_D => FileType::File,
FTW_DNR => FileType::Directory,
FTW_DP => FileType::Directory,
FTW_SL => FileType::Symlink,
FTW_SLN => FileType::Symlink,
FTW_NS => FileType::Unknown,
_ => FileType::Unknown,
}
}
pub fn from_file_type(file_type: &fs::FileType) -> Self {
if file_type.is_file() {
FileType::File
} else if file_type.is_dir() {
FileType::Directory
} else if file_type.is_symlink() {
FileType::Symlink
} else {
FileType::Unknown
}
}
}
impl FileTypeTrait for FileType {
fn is_dir(&self) -> bool {
match *self {
FileType::File => false,
FileType::Directory => true,
FileType::Symlink => false,
FileType::Unknown => false,
}
}
fn is_file(&self) -> bool {
match *self {
FileType::File => true,
FileType::Directory => false,
FileType::Symlink => false,
FileType::Unknown => false,
}
}
fn is_symlink(&self) -> bool {
match *self {
FileType::File => false,
FileType::Directory => false,
FileType::Symlink => true,
FileType::Unknown => false,
}
}
}
|
use std::collections::HashSet;
use crate::{
fixture,
vector::{sql, Geometry},
Dataset,
};
#[test]
fn test_sql() {
let ds = Dataset::open(fixture!("roads.geojson")).unwrap();
let query = "SELECT kind, is_bridge, highway FROM roads WHERE highway = 'pedestrian'";
let mut result_set = ds
.execute_sql(query, None, sql::Dialect::DEFAULT)
.unwrap()
.unwrap();
let field_names: HashSet<_> = result_set
.defn()
.fields()
.map(|field| field.name())
.collect();
let mut correct_field_names = HashSet::new();
correct_field_names.insert("kind".into());
correct_field_names.insert("is_bridge".into());
correct_field_names.insert("highway".into());
assert_eq!(correct_field_names, field_names);
assert_eq!(10, result_set.feature_count());
for feature in result_set.features() {
let highway = feature
.field("highway")
.unwrap()
.unwrap()
.into_string()
.unwrap();
assert_eq!("pedestrian", highway);
}
}
#[test]
fn test_sql_with_spatial_filter() {
let query = "SELECT * FROM roads WHERE highway = 'pedestrian'";
let ds = Dataset::open(fixture!("roads.geojson")).unwrap();
let bbox = Geometry::bbox(26.1017, 44.4297, 26.1025, 44.4303).unwrap();
let mut result_set = ds
.execute_sql(query, Some(&bbox), sql::Dialect::DEFAULT)
.unwrap()
.unwrap();
assert_eq!(2, result_set.feature_count());
let mut correct_fids = HashSet::new();
correct_fids.insert(252725993);
correct_fids.insert(23489656);
let mut fids = HashSet::new();
for feature in result_set.features() {
let highway = feature
.field("highway")
.unwrap()
.unwrap()
.into_string()
.unwrap();
assert_eq!("pedestrian", highway);
fids.insert(feature.fid().unwrap());
}
assert_eq!(correct_fids, fids);
}
#[test]
fn test_sql_with_dialect() {
let query = "SELECT * FROM roads WHERE highway = 'pedestrian' and NumPoints(GEOMETRY) = 3";
let ds = Dataset::open(fixture!("roads.geojson")).unwrap();
let bbox = Geometry::bbox(26.1017, 44.4297, 26.1025, 44.4303).unwrap();
let mut result_set = ds
.execute_sql(query, Some(&bbox), sql::Dialect::SQLITE)
.unwrap()
.unwrap();
assert_eq!(1, result_set.feature_count());
let mut features: Vec<_> = result_set.features().collect();
let feature = features.pop().unwrap();
let highway = feature
.field("highway")
.unwrap()
.unwrap()
.into_string()
.unwrap();
assert_eq!("pedestrian", highway);
}
#[test]
fn test_sql_empty_result() {
let ds = Dataset::open(fixture!("roads.geojson")).unwrap();
let query = "SELECT kind, is_bridge, highway FROM roads WHERE highway = 'jazz hands 👐'";
let mut result_set = ds
.execute_sql(query, None, sql::Dialect::DEFAULT)
.unwrap()
.unwrap();
assert_eq!(0, result_set.feature_count());
assert_eq!(0, result_set.features().count());
}
#[test]
fn test_sql_no_result() {
let ds = Dataset::open(fixture!("roads.geojson")).unwrap();
let query = "ALTER TABLE roads ADD COLUMN fun integer";
let result_set = ds.execute_sql(query, None, sql::Dialect::DEFAULT).unwrap();
assert!(result_set.is_none());
}
#[test]
fn test_sql_bad_query() {
let ds = Dataset::open(fixture!("roads.geojson")).unwrap();
let query = "SELECT nope FROM roads";
let result_set = ds.execute_sql(query, None, sql::Dialect::DEFAULT);
assert!(result_set.is_err());
let query = "SELECT nope FROM";
let result_set = ds.execute_sql(query, None, sql::Dialect::DEFAULT);
assert!(result_set.is_err());
let query = "SELECT ninetynineredballoons(highway) FROM roads";
let result_set = ds.execute_sql(query, None, sql::Dialect::DEFAULT);
assert!(result_set.is_err());
}
|
use solana_program::{
program_error::ProgramError,
pubkey::Pubkey,
};
use std::mem::size_of;
use arrayref::array_ref;
use gravity_misc::validation::{build_range_from_alloc, extract_from_range, retrieve_oracles};
use gravity_misc::ports::{
state::ForeignAddress,
instruction::ATTACH_VALUE_INSTRUCTION_INDEX
};
use crate::relay::allocs::allocation_by_instruction_index;
use solana_gravity_contract::gravity::error::GravityError::InvalidInstruction;
pub enum RelayContractInstruction {
// InitContract {
// nebula_address: Pubkey,
// token_address: Pubkey,
// token_mint: Pubkey,
// oracles: Vec<Pubkey>,
// },
ExternalTransfer {
request_id: [u8; 16],
amount: f64,
receiver: ForeignAddress,
},
AttachValue {
byte_data: Vec<u8>,
},
}
impl RelayContractInstruction {
pub const PUBKEY_ALLOC: usize = 32;
pub const DEST_AMOUNT_ALLOC: usize = 8;
pub const FOREIGN_ADDRESS_ALLOC: usize = 32;
pub const ATTACHED_DATA_ALLOC: usize = 64;
pub fn unpack(input: &[u8]) -> Result<Self, ProgramError> {
let (tag, rest) = input.split_first().ok_or(InvalidInstruction)?;
Ok(match tag {
// AttachValue
ATTACH_VALUE_INSTRUCTION_INDEX => {
let byte_data = rest.to_vec();
Self::AttachValue { byte_data }
}
// InitContract
0 => {
let allocs = allocation_by_instruction_index((*tag).into(), None)?;
let ranges = build_range_from_alloc(&allocs);
let (nebula_address, token_address, token_mint) = (
Pubkey::new(&rest[ranges[0].clone()]),
Pubkey::new(&rest[ranges[1].clone()]),
Pubkey::new(&rest[ranges[2].clone()]),
);
let mut offset = 32 * 3;
let oracles_bft_range = offset..offset + 1;
let oracles_bft = extract_from_range(rest, oracles_bft_range, |x: &[u8]| {
u8::from_le_bytes(*array_ref![x, 0, 1])
})?;
offset += 1;
let oracles = retrieve_oracles(rest, offset..offset + (oracles_bft as usize * 32), oracles_bft)?;
Self::InitContract {
nebula_address,
token_address,
token_mint,
oracles,
}
}
// CreateTransferUnwrapRequest
1 => {
let allocs = allocation_by_instruction_index((*tag).into(), None)?;
let ranges = build_range_from_alloc(&allocs);
let (amount, receiver, request_id) = (
f64::from_le_bytes(*array_ref![rest[ranges[0].clone()], 0, 8]),
*array_ref![rest[ranges[1].clone()], 0, 32],
*array_ref![rest[ranges[2].clone()], 0, 16],
);
Self::CreateTransferUnwrapRequest {
request_id,
amount,
receiver,
}
}
_ => return Err(InvalidInstruction.into()),
})
}
}
impl RelayContractInstruction {
pub fn pack(&self) -> Vec<u8> {
let buf = Vec::with_capacity(size_of::<Self>());
match self {
&Self::AttachValue {
ref byte_data,
} => {
let mut buf = byte_data.clone();
buf.insert(0, *ATTACH_VALUE_INSTRUCTION_INDEX);
buf
},
_ => buf
}
}
}
|
use ::Payload;
use byteorder::{self, ByteOrder};
use core::cmp::PartialEq;
use core::fmt::{self, Debug, Formatter};
use core::ops::Deref;
use crc16;
/// A checksum algorithm configuration to use when encoding data.
#[derive(Clone, Debug)]
pub enum Checksum {
/// Use no checksum.
None,
/// CRC-16/CDMA2000 as [implemented in crate `crc16`][impl].
/// This is the default checksum.
///
/// [impl]: https://docs.rs/crc16/0.3.4/crc16/enum.CDMA2000.html
Crc16Cdma2000,
}
impl Default for Checksum {
fn default() -> Checksum {
Checksum::Crc16Cdma2000
}
}
pub(crate) const MAX_CHECKSUM_LEN: usize = 2;
#[derive(Eq)]
pub(crate) struct ChecksumValue {
data: [u8; MAX_CHECKSUM_LEN],
len: usize,
}
impl Checksum {
pub(crate) fn len(&self) -> usize {
match *self {
Checksum::None => 0,
Checksum::Crc16Cdma2000 => 2,
}
}
pub(crate) fn calculate(&self, payload: &Payload) -> ChecksumValue {
let mut v = ChecksumValue {
data: [0u8; MAX_CHECKSUM_LEN],
len: self.len(),
};
match *self {
Checksum::None => (),
Checksum::Crc16Cdma2000 => {
let u16 = crc16::State::<crc16::CDMA2000>::calculate(payload);
byteorder::NetworkEndian::write_u16(&mut v.data, u16);
},
};
v
}
}
impl Deref for ChecksumValue {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.data[0..self.len]
}
}
impl PartialEq for ChecksumValue {
fn eq(&self, other: &ChecksumValue) -> bool {
self.deref() == other.deref()
}
}
impl Debug for ChecksumValue {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
write!(f, "{:?}", self.deref())
}
}
|
#[cfg(feature = "screen")]
use framebuffer::Framebuffer;
#[cfg(feature = "screen")]
use image::{Rgb, RgbImage};
use crate::Ev3Result;
/// Represents the device screen.
/// Advanced drawing operations can be performed with the `imageproc` crate.
#[cfg(feature = "screen")]
#[derive(Debug)]
pub struct Screen {
/// Direct reference to the framebuffer
pub buffer: Framebuffer,
/// Convenience layer to access the framebuffer
/// For drawing operations the `imageproc` crate can be used.
pub image: RgbImage,
}
#[cfg(feature = "screen")]
impl Screen {
/// Create a reference to the device screen
pub fn new() -> Ev3Result<Self> {
let buffer = Framebuffer::new("/dev/fb0")?;
let image = RgbImage::from_pixel(
buffer.fix_screen_info.line_length * 8 / buffer.var_screen_info.bits_per_pixel,
buffer.var_screen_info.yres,
Rgb([255, 255, 255]),
);
Ok(Self { buffer, image })
}
/// Horizontal screen resolution
pub fn xres(&self) -> u32 {
self.buffer.var_screen_info.xres
}
/// Vertical screen resolution
pub fn yres(&self) -> u32 {
self.buffer.var_screen_info.yres
}
/// Dimensions of the screen.
pub fn shape(&self) -> (u32, u32) {
(self.xres(), self.yres())
}
/// Clears the screen
pub fn clear(&mut self) {
for (_, _, pixel) in self.image.enumerate_pixels_mut() {
*pixel = Rgb([255, 255, 255]);
}
}
fn update_1bpp(&mut self) {
let mut buffer = vec![0u8; ((self.xres() * self.yres() + 7) / 8) as usize];
let mut byte: usize = 0;
let mut bit: u8 = 0x80;
for (_, _, pixel) in self.image.enumerate_pixels() {
let sum = pixel.0[0] as u32 + pixel.0[1] as u32 + pixel.0[2] as u32;
buffer[byte] |= if sum >= 0x30 { bit } else { 0x00 };
bit >>= 1;
if bit == 0 {
byte += 1;
bit = 0x80;
}
}
self.buffer.write_frame(&buffer);
}
/// Convert red, green, blue components to a 16-bit 565 RGB value. Components
/// should be values 0 to 255.
fn color565(r: u8, g: u8, b: u8) -> (u8, u8) {
let c = (((r as u16) & 0xF8) << 8) | (((g as u16) & 0xFC) << 3) | ((b as u16) >> 3);
((c >> 8) as u8, c as u8)
}
fn update_16bpp(&mut self) {
let mut buffer = vec![0u8; (2 * self.xres() * self.yres()) as usize];
let mut byte: usize = 0;
for (_, _, pixel) in self.image.enumerate_pixels() {
let (p1, p2) = Screen::color565(pixel.0[0], pixel.0[1], pixel.0[2]);
buffer[byte] = p1;
buffer[byte + 1] = p2;
byte += 2;
}
self.buffer.write_frame(&buffer);
}
fn update_32bpp(&mut self) {
let mut buffer = vec![0u8; (4 * self.xres() * self.yres()) as usize];
let mut byte: usize = 1;
for (_, _, pixel) in self.image.enumerate_pixels() {
buffer[byte..(byte + 2)].copy_from_slice(&pixel.0[0..2]);
byte += 4;
}
self.buffer.write_frame(&buffer);
}
/// Applies pending changes to the screen.
/// Nothing will be drawn on the screen until this function is called.
pub fn update(&mut self) {
if self.buffer.var_screen_info.bits_per_pixel == 1 {
self.update_1bpp();
} else if self.buffer.var_screen_info.bits_per_pixel == 16 {
self.update_16bpp();
} else if self.buffer.var_screen_info.bits_per_pixel == 32 {
self.update_32bpp();
}
}
}
|
// Copyright 2018 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under the MIT license <LICENSE-MIT
// http://opensource.org/licenses/MIT> or the Modified BSD license <LICENSE-BSD
// https://opensource.org/licenses/BSD-3-Clause>, at your option. This file may not be copied,
// modified, or distributed except according to those terms. Please review the Licences for the
// specific language governing permissions and limitations relating to use of the SAFE Network
// Software.
//! Command line tool for generating and validating resource proofs.
// For explanation of lint checks, run `rustc -W help` or see
// https://github.com/maidsafe/QA/blob/master/Documentation/Rust%20Lint%20Checks.md
#![forbid(
bad_style,
exceeding_bitshifts,
mutable_transmutes,
no_mangle_const_items,
unknown_crate_types,
warnings
)]
#![deny(
deprecated,
improper_ctypes,
missing_docs,
non_shorthand_field_patterns,
overflowing_literals,
plugin_as_library,
stable_features,
unconditional_recursion,
unknown_lints,
unsafe_code,
unused,
unused_allocation,
unused_attributes,
unused_comparisons,
unused_features,
unused_parens,
while_true
)]
#![warn(
trivial_casts,
trivial_numeric_casts,
unused_extern_crates,
unused_import_braces,
unused_qualifications,
unused_results
)]
#![allow(
box_pointers,
missing_copy_implementations,
missing_debug_implementations,
variant_size_differences
)]
#[macro_use]
extern crate clap;
use clap::{App, Arg};
use resource_proof::ResourceProof;
use std::time::Instant;
#[cfg(not(windows))]
use termion::color;
fn test_it(dif: u8, size: usize, nonce: [u8; 32]) {
let create = Instant::now();
let rp = ResourceProof::new(size, dif);
let data = rp.create_proof_data(&nonce);
let mut prover = rp.create_prover(data.clone());
let expected_steps = prover.expected_steps();
let proof = prover.solve();
let create_time = create.elapsed().as_secs();
let check = Instant::now();
if !rp.validate_proof(&nonce, proof) {
println!("FAILED TO CONFIRM PROOF - POSSIBLE VIOLATION");
}
if !rp.validate_data(&nonce, &data) {
println!("FAILED TO CONFIRM PROOF DATA - POSSIBLE VIOLATION");
}
if !rp.validate_all(&nonce, &data, proof) {
println!("FAILED TO CONFIRM PROOF & DATA - POSSIBLE VIOLATION");
}
println!(
"Difficulty = {} expected_steps = {} size = {} create = {} seconds check = {} \
seconds num of steps = {:?}",
dif,
expected_steps,
size,
create_time,
check.elapsed().as_secs(),
proof
);
}
#[cfg(not(windows))]
fn print_red(message: &str) {
println!();
println!();
println!(
"{}{}{}",
color::Fg(color::Red),
message,
color::Fg(color::Reset)
);
}
#[cfg(windows)]
fn print_red(message: &str) {
println!();
println!();
println!("{}", message);
}
fn main() {
let matches = App::new(
"=============================\nSimple Resource Proof \
example\n=============================\n",
)
.about("______________________________\nPlease set the size and difficulty to test")
.author(crate_authors!())
.version(crate_version!())
.before_help("Resource proof testing framework")
.after_help(
"_____________________________________________________________\nSeveral \
proofs may be chained, i.e. a large difficulty and small size or large size \
and small difficulty to check specifically CPU And BW seperately",
)
.arg(
Arg::with_name("Difficulty")
.short("d")
.required(true)
.long("difficulty")
.help(
"Set difficulty, i.e. the number of leading zeros of the proof when hashed \
with SHA3",
)
.takes_value(true),
)
.arg(
Arg::with_name("Size")
.required(true)
.short("s")
.long("size")
.help("Set size, i.e. the minimum size of the proof in bytes")
.takes_value(true),
)
.arg(Arg::with_name("Increase").short("i").long("increase").help(
"Will run continuously, increasing difficulty with every invocation. Note \
this will likley not stop in your lifetime :-)",
))
.get_matches();
print_red("Running analysis ....");
let repeat = matches.is_present("Increase");
let dif = value_t!(matches, "Difficulty", u8).unwrap_or(1);
let size = value_t!(matches, "Size", usize).unwrap_or(10);
let nonce = [rand::random::<u8>(); 32];
if repeat {
for i in dif.. {
test_it(i, size, nonce);
}
} else {
test_it(dif, size, nonce);
}
}
|
use std::fs::File;
use std::collections::HashMap;
use std::io::Read;
type Input<'a> = HashMap<&'a str, Vec<&'a str>>;
pub fn parse(s: &str) -> Input {
s.lines()
.map(|line| {
let split: Vec<_> = line.split("->").collect();
let name = split[0].split_whitespace().collect::<Vec<_>>()[0];
let mut sublist = Vec::new();
if let Some(sublist_str) = split.get(1) {
sublist.extend(sublist_str.split(",").map(str::trim));
}
(name, sublist)
})
.collect()
}
pub fn find_root<'a>(input: &Input<'a>) -> Option<&'a str> {
let mut map: HashMap<_, _> = input.keys().map(|key| (key, 1)).collect();
input.values().flat_map(|v| v.iter()).for_each(|name| {
*map.get_mut(name).expect("No name") += 1;
});
map.iter()
.find(|&(key, &value)| value == 1)
.map(|(&&name, _)| name)
}
fn main() {
let mut file = File::open("src/bin/day7.input").expect("file");
let mut input = String::new();
file.read_to_string(&mut input).expect("read");
let map = parse(&input);
println!("Part 1 {:?}", find_root(&map));
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::any::Any;
use std::sync::Arc;
use common_expression::BlockMetaInfo;
use common_expression::BlockMetaInfoDowncast;
use common_expression::BlockMetaInfoPtr;
use storages_common_table_meta::meta::BlockMeta;
use crate::operations::merge_into::mutation_meta::mutation_log::BlockMetaIndex;
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
pub struct CompactSourceMeta {
pub block: Arc<BlockMeta>,
pub index: BlockMetaIndex,
}
#[typetag::serde(name = "compact_source_meta")]
impl BlockMetaInfo for CompactSourceMeta {
fn as_any(&self) -> &dyn Any {
self
}
fn equals(&self, info: &Box<dyn BlockMetaInfo>) -> bool {
match CompactSourceMeta::downcast_ref_from(info) {
None => false,
Some(other) => self == other,
}
}
fn clone_self(&self) -> Box<dyn BlockMetaInfo> {
Box::new(self.clone())
}
}
impl CompactSourceMeta {
pub fn create(index: BlockMetaIndex, block: Arc<BlockMeta>) -> BlockMetaInfoPtr {
Box::new(CompactSourceMeta { index, block })
}
}
|
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is 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.
// You may not use this file except in accordance with one or both of these
// licenses.
pub mod background_processor;
pub mod bubble_gossip_route_handler;
pub mod node_announcer;
pub mod node_info;
pub mod peer_connector;
pub mod router;
pub mod utils;
use lightning::{
chain::{
self,
keysinterface::{KeysInterface, KeysManager, Recipient},
},
ln::peer_handler::{ErroringMessageHandler, IgnoringMessageHandler, MessageHandler},
};
use lightning_invoice::utils::DefaultRouter;
use rand::RngCore;
use std::{
sync::{atomic::AtomicBool, Arc, Mutex},
time::SystemTime,
};
use tokio::task::JoinHandle;
use crate::{
config::{P2PConfig, SenseiConfig},
database::SenseiDatabase,
disk::FilesystemLogger,
node::{LightningNode, NetworkGraph, NetworkGraphMessageHandler, RoutingPeerManager},
persist::{AnyKVStore, DatabaseStore, SenseiPersister},
};
use self::{
background_processor::BackgroundProcessor,
bubble_gossip_route_handler::AnyP2PGossipHandler,
node_announcer::NodeAnnouncer,
node_info::NodeInfoLookup,
peer_connector::PeerConnector,
router::{AnyRouter, AnyScorer},
utils::parse_peer_info,
};
pub struct SenseiP2P {
pub config: Arc<SenseiConfig>,
pub persister: Arc<SenseiPersister>,
pub network_graph: Arc<NetworkGraph>,
pub p2p_gossip: Arc<AnyP2PGossipHandler>,
pub scorer: Arc<Mutex<AnyScorer>>,
pub logger: Arc<FilesystemLogger>,
pub peer_manager: Option<Arc<RoutingPeerManager>>,
pub peer_connector: Arc<PeerConnector>,
pub node_announcer: Arc<NodeAnnouncer>,
pub runtime_handle: tokio::runtime::Handle,
pub stop_signal: Arc<AtomicBool>,
pub join_handles: Arc<Mutex<Vec<JoinHandle<()>>>>,
}
impl SenseiP2P {
pub async fn new(
config: Arc<SenseiConfig>,
database: Arc<SenseiDatabase>,
logger: Arc<FilesystemLogger>,
runtime_handle: tokio::runtime::Handle,
stop_signal: Arc<AtomicBool>,
) -> Self {
let p2p_node_id = config.instance_name.clone();
let persistence_store =
AnyKVStore::Database(DatabaseStore::new(database.clone(), p2p_node_id.clone()));
let persister = Arc::new(SenseiPersister::new(
persistence_store,
config.network,
logger.clone(),
));
let network_graph = Arc::new(persister.read_network_graph());
let scorer = match config.get_p2p_config() {
P2PConfig::Remote(host, token) => Arc::new(Mutex::new(AnyScorer::new_remote(
host,
token,
runtime_handle.clone(),
))),
_ => Arc::new(Mutex::new(AnyScorer::Local(
persister.read_scorer(Arc::clone(&network_graph)),
))),
};
let node_info_lookup = match config.get_p2p_config() {
P2PConfig::Remote(host, token) => Arc::new(NodeInfoLookup::new_remote(
host,
token,
runtime_handle.clone(),
)),
_ => Arc::new(NodeInfoLookup::Local(network_graph.clone())),
};
let p2p_gossip = match config.get_p2p_config() {
P2PConfig::Remote(host, token) => Arc::new(AnyP2PGossipHandler::new_remote(
host,
token,
runtime_handle.clone(),
)),
P2PConfig::RapidGossipSync(_) => Arc::new(AnyP2PGossipHandler::None),
P2PConfig::Local => {
Arc::new(AnyP2PGossipHandler::Local(NetworkGraphMessageHandler::new(
Arc::clone(&network_graph),
None::<Arc<dyn chain::Access + Send + Sync>>,
logger.clone(),
)))
}
};
let lightning_msg_handler = MessageHandler {
chan_handler: Arc::new(ErroringMessageHandler::new()),
route_handler: p2p_gossip.clone(),
};
let mut entropy: [u8; 32] = [0; 32];
rand::thread_rng().fill_bytes(&mut entropy);
match database.get_entropy_sync(p2p_node_id.clone()).unwrap() {
Some(entropy_vec) => {
entropy.copy_from_slice(entropy_vec.as_slice());
}
None => {
let _res = database.set_entropy_sync(p2p_node_id, entropy.to_vec());
}
}
let seed = LightningNode::get_seed_from_entropy(config.network, &entropy);
let cur = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap();
let keys_manager = Arc::new(KeysManager::new(&seed, cur.as_secs(), cur.subsec_nanos()));
let mut ephemeral_bytes = [0; 32];
rand::thread_rng().fill_bytes(&mut ephemeral_bytes);
let peer_manager = match config.get_p2p_config() {
P2PConfig::RapidGossipSync(_) => None,
_ => Some(Arc::new(RoutingPeerManager::new(
lightning_msg_handler,
keys_manager.get_node_secret(Recipient::Node).unwrap(),
&ephemeral_bytes,
logger.clone(),
Arc::new(IgnoringMessageHandler {}),
))),
};
let peer_connector = Arc::new(PeerConnector::new(
database,
node_info_lookup,
peer_manager.clone(),
));
for gossip_peer in config.gossip_peers.split(',') {
if let Ok((pubkey, peer_addr)) = parse_peer_info(gossip_peer.to_string()).await {
let _res = peer_connector.connect_routing_peer(pubkey, peer_addr).await;
}
}
let node_announcer = Arc::new(NodeAnnouncer::new());
let p2p_background_processor = BackgroundProcessor::new(
peer_manager.clone(),
scorer.clone(),
network_graph.clone(),
persister.clone(),
stop_signal.clone(),
config.rapid_gossip_sync_server_host.clone(),
);
let bg_join_handle = tokio::spawn(async move { p2p_background_processor.process().await });
let peer_connector_run = peer_connector.clone();
tokio::spawn(async move { peer_connector_run.run().await });
let node_announcer_run = node_announcer.clone();
tokio::spawn(async move { node_announcer_run.run().await });
Self {
config,
persister,
logger,
network_graph,
scorer,
p2p_gossip,
peer_manager,
peer_connector,
node_announcer,
runtime_handle,
stop_signal,
join_handles: Arc::new(Mutex::new(vec![bg_join_handle])),
}
}
pub fn get_router(&self) -> AnyRouter {
match (
self.config.remote_p2p_host.as_ref(),
self.config.remote_p2p_token.as_ref(),
) {
(Some(host), Some(token)) => {
AnyRouter::new_remote(host.clone(), token.clone(), self.runtime_handle.clone())
}
_ => {
let mut randomness: [u8; 32] = [0; 32];
rand::thread_rng().fill_bytes(&mut randomness);
let local_router =
DefaultRouter::new(self.network_graph.clone(), self.logger.clone(), randomness);
AnyRouter::Local(local_router)
}
}
}
pub async fn stop(&self) {
let mut join_handles = {
let mut p2p_join_handles = self.join_handles.lock().unwrap();
p2p_join_handles.drain(..).collect::<Vec<JoinHandle<()>>>()
};
for join_handle in join_handles.iter_mut() {
let _res = join_handle.await;
}
}
}
|
pub fn raindrops(n: u32) -> String {
let mut result = String::new();
if n % 3 == 0 {
result.push_str("Pling");
}
if n % 5 == 0 {
result.push_str("Plang");
}
if n % 7 == 0 {
result.push_str("Plong");
}
if result.is_empty() {
n.to_string()
}else {
result
}
}
#[cfg(test)]
mod tests {
use crate::raindrops;
#[test]
fn raindrops_test() {
assert_eq!(raindrops(3), String::from("Pling"));
assert_eq!(raindrops(5), String::from("Plang"));
assert_eq!(raindrops(7), String::from("Plong"));
assert_eq!(raindrops(15), String::from("PlingPlang"));
assert_eq!(raindrops(17), String::from("17"));
}
} |
extern crate day10;
use std::fmt;
use std::io::Write;
use day10::*;
pub fn count_used(key: &str) -> usize {
let mut sum: usize = 0;
let mut buf: Vec<u8> = Vec::with_capacity(key.len() + 4);
for n in 0..128 {
write!(&mut buf, "{}-{}", key, n).unwrap();
let hash = KnotHash::hash(&buf).hash;
buf.clear();
hash.iter()
.for_each(|b| sum += b.count_ones() as usize);
}
sum
}
struct Grid {
grid: [u8; 2048],
}
impl Grid {
fn new() -> Grid {
Grid { grid: [0u8; 2048]}
}
fn with_key(key: &str) -> Grid {
let mut grid = [0u8; 2048];
{
let mut grid_it = grid.iter_mut();
let mut buf: Vec<u8> = Vec::with_capacity(key.len() + 4);
for n in 0..128 {
write!(&mut buf, "{}-{}", key, n).unwrap();
let hash = KnotHash::hash(&buf).hash;
buf.clear();
for b in hash.iter() {
*grid_it.next().unwrap() = *b;
}
}
}
Grid { grid }
}
fn set(&mut self, x: usize, y: usize) {
let i = y * 16 + (x >> 3);
let b = self.grid[i];
self.grid[i] = b | (0x80 >> (x & 0x07))
}
fn is_set(&self, x: usize, y: usize) -> bool {
let i = y * 16 + (x >> 3);
let b = self.grid[i];
0 != b & (0x80 >> (x & 0x07))
}
}
pub fn count_regions(key: &str) -> usize {
let mut sum: usize = 0;
let grid = Grid::with_key(key);
let mut regions = Grid::new();
for x in 0..128 {
for y in 0..128 {
if set_neighbors(x, y, &grid, &mut regions) {
sum += 1;
}
}
}
sum
}
fn set_neighbors(x: usize, y: usize, grid: &Grid, regions: &mut Grid) -> bool {
if !grid.is_set(x, y) {
return false;
}
if !regions.is_set(x, y) {
regions.set(x, y);
if x > 0 {
set_neighbors(x - 1, y, grid, regions);
}
if x < 127 {
set_neighbors(x + 1, y, grid, regions);
}
if y > 0 {
set_neighbors(x, y - 1, grid, regions);
}
if y < 127 {
set_neighbors(x, y + 1, grid, regions);
}
true
} else {
false
}
}
impl fmt::Display for Grid {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for y in 0..128 {
for x in 0..128 {
if self.is_set(x, y) {
write!(f, "#")?;
} else {
write!(f, ".")?;
}
}
write!(f, "\n")?;
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_part_1() {
assert_eq!(8108, count_used("flqrgnkx"));
}
#[test]
fn puzzle_part_1() {
assert_eq!(8074, count_used("jzgqcdpd"));
}
#[test]
fn test_part_2() {
assert_eq!(1242, count_regions("flqrgnkx"));
}
#[test]
fn puzzle_part_2() {
assert_eq!(1212, count_regions("jzgqcdpd"));
}
}
|
#![feature(test)]
extern crate test;
use smaz::{compress};
use lz4_flex::{compress_prepend_size};
pub const INPUT: &str = "Put request on \"/boot-source\" with body \"{\\n \\\"kernel_image_path\\\": \\\"/home/elavtob/tmp/hello-vmlinux.bin\\\",\\n \\\"boot_args\\\": \\\"console=ttyS0 reboot=k panic=1 pci=off\\\"\\n }\"";
pub fn no_compress(input: String, list: &mut Vec<String>) {
list.push(input);
}
pub fn smaz_compress(input: String, list: &mut Vec<Vec<u8>>) {
let compressed = compress(&input.as_bytes());
list.push(compressed);
}
pub fn lz4_flex_compress(input: String, list: &mut Vec<Vec<u8>>) {
let compressed = compress_prepend_size(&input.as_bytes());
list.push(compressed);
}
#[cfg(test)]
mod tests {
use super::*;
use test::Bencher;
const NBR_RUNS: usize = 1;
#[bench]
fn bench_no_compress(b: &mut Bencher) {
let mut list: Vec<String> = Vec::new();
b.iter(|| {
for _ in 0..NBR_RUNS {
no_compress(INPUT.to_string(), &mut list)
}
});
}
#[bench]
fn bench_smaz_compress(b: &mut Bencher) {
let mut list: Vec<Vec<u8>> = Vec::new();
b.iter(|| {
for _ in 0..NBR_RUNS {
smaz_compress(INPUT.to_string(), &mut list)
}
});
}
#[bench]
fn bench_lz4_flex_compress(b: &mut Bencher) {
let mut list: Vec<Vec<u8>> = Vec::new();
b.iter(|| {
for _ in 0..NBR_RUNS {
lz4_flex_compress(INPUT.to_string(), &mut list)
}
});
}
}
|
pub struct Solution;
impl Solution {
pub fn rob(nums: Vec<i32>) -> i32 {
if nums.len() == 0 {
return 0;
}
if nums.len() == 1 {
return nums[0];
}
let case_use_0 = {
let mut a = nums[0];
let mut b = nums[0];
for i in 2..nums.len() - 1 {
let c = b.max(a + nums[i]);
a = b;
b = c;
}
b
};
let case_not_use_0 = {
let mut a = 0;
let mut b = 0;
for i in 1..nums.len() {
let c = b.max(a + nums[i]);
a = b;
b = c;
}
b
};
case_use_0.max(case_not_use_0)
}
}
#[test]
fn test0213() {
fn case(nums: Vec<i32>, want: i32) {
let got = Solution::rob(nums);
assert_eq!(got, want);
}
case(vec![2, 3, 2], 3);
case(vec![1, 2, 3, 1], 4);
}
|
use error;
use ffi;
use MantleObject;
use std::mem;
use std::ptr;
use std::ffi::CStr;
use std::slice::Iter;
use std::iter::Take;
use std::sync::{Once, ONCE_INIT};
static mut GPUS: [ffi::GR_PHYSICAL_GPU; ffi::GR_MAX_PHYSICAL_GPUS] = [0; ffi::GR_MAX_PHYSICAL_GPUS];
static mut GPUS_COUNT: ffi::GR_UINT = 0;
#[derive(Debug, Copy, Clone)]
pub struct Gpu {
gpu: ffi::GR_PHYSICAL_GPU,
}
impl MantleObject for Gpu {
type Id = ffi::GR_PHYSICAL_GPU;
fn get_id(&self) -> &ffi::GR_PHYSICAL_GPU {
&self.gpu
}
}
// FIXME: cache the list of gpus
pub fn get_gpus() -> GpusIterator {
static INIT: Once = ONCE_INIT;
INIT.call_once(|| {
unsafe {
error::check_result(ffi::grDbgRegisterMsgCallback(debug_callback,
ptr::null_mut())).unwrap();
let mut appinfos: ffi::GR_APPLICATION_INFO = mem::zeroed();
appinfos.apiVersion = ffi::GR_API_VERSION;
let result = ffi::grInitAndEnumerateGpus(&appinfos, ptr::null(), &mut GPUS_COUNT,
GPUS.as_mut_ptr());
error::check_result(result).unwrap();
}
});
GpusIterator {
iter: unsafe { GPUS.iter().take(GPUS_COUNT as usize) },
}
}
pub struct GpusIterator {
iter: Take<Iter<'static, ffi::GR_PHYSICAL_GPU>>,
}
impl Iterator for GpusIterator {
type Item = Gpu;
fn next(&mut self) -> Option<Gpu> {
self.iter.next().map(|&g| Gpu { gpu: g })
}
}
unsafe extern "stdcall" fn debug_callback(_msg_type: ffi::GR_ENUM, _validation_level: ffi::GR_ENUM,
_src_object: ffi::GR_BASE_OBJECT, _location: ffi::GR_SIZE,
_msg_code: ffi::GR_ENUM, msg: *const ffi::GR_CHAR,
_user_data: *mut ffi::GR_VOID)
{
unsafe {
let msg = CStr::from_ptr(msg);
println!("Mantle debug message: {}", String::from_utf8(msg.to_bytes().to_vec()).unwrap());
}
}
|
use std::convert::TryInto;
use proptest::prop_assert_eq;
use proptest::strategy::Just;
use liblumen_alloc::erts::term::prelude::*;
use crate::erlang::setelement_3::result;
use crate::test::strategy;
#[test]
fn without_tuple_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::is_integer(arc_process.clone()),
strategy::term::is_not_tuple(arc_process.clone()),
strategy::term(arc_process),
)
},
|(arc_process, tuple, index, element)| {
prop_assert_is_not_tuple!(result(&arc_process, index, tuple, element), tuple);
Ok(())
},
);
}
#[test]
fn with_tuple_without_valid_index_errors_badarg() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::tuple::without_index(arc_process.clone()),
strategy::term(arc_process.clone()),
)
},
|(arc_process, (tuple, index), element)| {
let boxed_tuple: Boxed<Tuple> = tuple.try_into().unwrap();
prop_assert_badarg!(
result(&arc_process, index, tuple, element),
format!(
"index ({}) is not a 1-based integer between 1-{}",
index,
boxed_tuple.len()
)
);
Ok(())
},
);
}
#[test]
fn with_tuple_with_valid_index_returns_tuple_with_index_replaced() {
run!(
|arc_process| {
(
Just(arc_process.clone()),
strategy::term::tuple::with_index(arc_process.clone()),
strategy::term(arc_process.clone()),
)
},
|(arc_process, (mut element_vec, element_vec_index, tuple, index), element)| {
element_vec[element_vec_index] = element;
let new_tuple = arc_process.tuple_from_slice(&element_vec);
prop_assert_eq!(result(&arc_process, index, tuple, element), Ok(new_tuple));
Ok(())
},
);
}
|
//! `IndexMap` is a hash table where the iteration order of the key-value
//! pairs is independent of the hash values of the keys.
mod core;
mod iter;
mod slice;
#[cfg(feature = "serde")]
#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
pub mod serde_seq;
#[cfg(test)]
mod tests;
pub use self::core::{Entry, OccupiedEntry, VacantEntry};
pub use self::iter::{
Drain, IntoIter, IntoKeys, IntoValues, Iter, IterMut, Keys, Values, ValuesMut,
};
pub use self::slice::Slice;
pub use crate::mutable_keys::MutableKeys;
#[cfg(feature = "rayon")]
pub use crate::rayon::map as rayon;
use ::core::cmp::Ordering;
use ::core::fmt;
use ::core::hash::{BuildHasher, Hash, Hasher};
use ::core::ops::{Index, IndexMut, RangeBounds};
use alloc::boxed::Box;
use alloc::vec::Vec;
#[cfg(feature = "std")]
use std::collections::hash_map::RandomState;
use self::core::IndexMapCore;
use crate::util::{third, try_simplify_range};
use crate::{Bucket, Entries, Equivalent, HashValue, TryReserveError};
/// A hash table where the iteration order of the key-value pairs is independent
/// of the hash values of the keys.
///
/// The interface is closely compatible with the standard `HashMap`, but also
/// has additional features.
///
/// # Order
///
/// The key-value pairs have a consistent order that is determined by
/// the sequence of insertion and removal calls on the map. The order does
/// not depend on the keys or the hash function at all.
///
/// All iterators traverse the map in *the order*.
///
/// The insertion order is preserved, with **notable exceptions** like the
/// `.remove()` or `.swap_remove()` methods. Methods such as `.sort_by()` of
/// course result in a new order, depending on the sorting order.
///
/// # Indices
///
/// The key-value pairs are indexed in a compact range without holes in the
/// range `0..self.len()`. For example, the method `.get_full` looks up the
/// index for a key, and the method `.get_index` looks up the key-value pair by
/// index.
///
/// # Examples
///
/// ```
/// use indexmap::IndexMap;
///
/// // count the frequency of each letter in a sentence.
/// let mut letters = IndexMap::new();
/// for ch in "a short treatise on fungi".chars() {
/// *letters.entry(ch).or_insert(0) += 1;
/// }
///
/// assert_eq!(letters[&'s'], 2);
/// assert_eq!(letters[&'t'], 3);
/// assert_eq!(letters[&'u'], 1);
/// assert_eq!(letters.get(&'y'), None);
/// ```
#[cfg(feature = "std")]
pub struct IndexMap<K, V, S = RandomState> {
pub(crate) core: IndexMapCore<K, V>,
hash_builder: S,
}
#[cfg(not(feature = "std"))]
pub struct IndexMap<K, V, S> {
pub(crate) core: IndexMapCore<K, V>,
hash_builder: S,
}
impl<K, V, S> Clone for IndexMap<K, V, S>
where
K: Clone,
V: Clone,
S: Clone,
{
fn clone(&self) -> Self {
IndexMap {
core: self.core.clone(),
hash_builder: self.hash_builder.clone(),
}
}
fn clone_from(&mut self, other: &Self) {
self.core.clone_from(&other.core);
self.hash_builder.clone_from(&other.hash_builder);
}
}
impl<K, V, S> Entries for IndexMap<K, V, S> {
type Entry = Bucket<K, V>;
#[inline]
fn into_entries(self) -> Vec<Self::Entry> {
self.core.into_entries()
}
#[inline]
fn as_entries(&self) -> &[Self::Entry] {
self.core.as_entries()
}
#[inline]
fn as_entries_mut(&mut self) -> &mut [Self::Entry] {
self.core.as_entries_mut()
}
fn with_entries<F>(&mut self, f: F)
where
F: FnOnce(&mut [Self::Entry]),
{
self.core.with_entries(f);
}
}
impl<K, V, S> fmt::Debug for IndexMap<K, V, S>
where
K: fmt::Debug,
V: fmt::Debug,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if cfg!(not(feature = "test_debug")) {
f.debug_map().entries(self.iter()).finish()
} else {
// Let the inner `IndexMapCore` print all of its details
f.debug_struct("IndexMap")
.field("core", &self.core)
.finish()
}
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<K, V> IndexMap<K, V> {
/// Create a new map. (Does not allocate.)
#[inline]
pub fn new() -> Self {
Self::with_capacity(0)
}
/// Create a new map with capacity for `n` key-value pairs. (Does not
/// allocate if `n` is zero.)
///
/// Computes in **O(n)** time.
#[inline]
pub fn with_capacity(n: usize) -> Self {
Self::with_capacity_and_hasher(n, <_>::default())
}
}
impl<K, V, S> IndexMap<K, V, S> {
/// Create a new map with capacity for `n` key-value pairs. (Does not
/// allocate if `n` is zero.)
///
/// Computes in **O(n)** time.
#[inline]
pub fn with_capacity_and_hasher(n: usize, hash_builder: S) -> Self {
if n == 0 {
Self::with_hasher(hash_builder)
} else {
IndexMap {
core: IndexMapCore::with_capacity(n),
hash_builder,
}
}
}
/// Create a new map with `hash_builder`.
///
/// This function is `const`, so it
/// can be called in `static` contexts.
pub const fn with_hasher(hash_builder: S) -> Self {
IndexMap {
core: IndexMapCore::new(),
hash_builder,
}
}
/// Return the number of elements the map can hold without reallocating.
///
/// This number is a lower bound; the map might be able to hold more,
/// but is guaranteed to be able to hold at least this many.
///
/// Computes in **O(1)** time.
pub fn capacity(&self) -> usize {
self.core.capacity()
}
/// Return a reference to the map's `BuildHasher`.
pub fn hasher(&self) -> &S {
&self.hash_builder
}
/// Return the number of key-value pairs in the map.
///
/// Computes in **O(1)** time.
#[inline]
pub fn len(&self) -> usize {
self.core.len()
}
/// Returns true if the map contains no elements.
///
/// Computes in **O(1)** time.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Return an iterator over the key-value pairs of the map, in their order
pub fn iter(&self) -> Iter<'_, K, V> {
Iter::new(self.as_entries())
}
/// Return an iterator over the key-value pairs of the map, in their order
pub fn iter_mut(&mut self) -> IterMut<'_, K, V> {
IterMut::new(self.as_entries_mut())
}
/// Return an iterator over the keys of the map, in their order
pub fn keys(&self) -> Keys<'_, K, V> {
Keys::new(self.as_entries())
}
/// Return an owning iterator over the keys of the map, in their order
pub fn into_keys(self) -> IntoKeys<K, V> {
IntoKeys::new(self.into_entries())
}
/// Return an iterator over the values of the map, in their order
pub fn values(&self) -> Values<'_, K, V> {
Values::new(self.as_entries())
}
/// Return an iterator over mutable references to the values of the map,
/// in their order
pub fn values_mut(&mut self) -> ValuesMut<'_, K, V> {
ValuesMut::new(self.as_entries_mut())
}
/// Return an owning iterator over the values of the map, in their order
pub fn into_values(self) -> IntoValues<K, V> {
IntoValues::new(self.into_entries())
}
/// Remove all key-value pairs in the map, while preserving its capacity.
///
/// Computes in **O(n)** time.
pub fn clear(&mut self) {
self.core.clear();
}
/// Shortens the map, keeping the first `len` elements and dropping the rest.
///
/// If `len` is greater than the map's current length, this has no effect.
pub fn truncate(&mut self, len: usize) {
self.core.truncate(len);
}
/// Clears the `IndexMap` in the given index range, returning those
/// key-value pairs as a drain iterator.
///
/// The range may be any type that implements `RangeBounds<usize>`,
/// including all of the `std::ops::Range*` types, or even a tuple pair of
/// `Bound` start and end values. To drain the map entirely, use `RangeFull`
/// like `map.drain(..)`.
///
/// This shifts down all entries following the drained range to fill the
/// gap, and keeps the allocated memory for reuse.
///
/// ***Panics*** if the starting point is greater than the end point or if
/// the end point is greater than the length of the map.
pub fn drain<R>(&mut self, range: R) -> Drain<'_, K, V>
where
R: RangeBounds<usize>,
{
Drain::new(self.core.drain(range))
}
/// Splits the collection into two at the given index.
///
/// Returns a newly allocated map containing the elements in the range
/// `[at, len)`. After the call, the original map will be left containing
/// the elements `[0, at)` with its previous capacity unchanged.
///
/// ***Panics*** if `at > len`.
pub fn split_off(&mut self, at: usize) -> Self
where
S: Clone,
{
Self {
core: self.core.split_off(at),
hash_builder: self.hash_builder.clone(),
}
}
}
impl<K, V, S> IndexMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
/// Reserve capacity for `additional` more key-value pairs.
///
/// Computes in **O(n)** time.
pub fn reserve(&mut self, additional: usize) {
self.core.reserve(additional);
}
/// Reserve capacity for `additional` more key-value pairs, without over-allocating.
///
/// Unlike `reserve`, this does not deliberately over-allocate the entry capacity to avoid
/// frequent re-allocations. However, the underlying data structures may still have internal
/// capacity requirements, and the allocator itself may give more space than requested, so this
/// cannot be relied upon to be precisely minimal.
///
/// Computes in **O(n)** time.
pub fn reserve_exact(&mut self, additional: usize) {
self.core.reserve_exact(additional);
}
/// Try to reserve capacity for `additional` more key-value pairs.
///
/// Computes in **O(n)** time.
pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.core.try_reserve(additional)
}
/// Try to reserve capacity for `additional` more key-value pairs, without over-allocating.
///
/// Unlike `try_reserve`, this does not deliberately over-allocate the entry capacity to avoid
/// frequent re-allocations. However, the underlying data structures may still have internal
/// capacity requirements, and the allocator itself may give more space than requested, so this
/// cannot be relied upon to be precisely minimal.
///
/// Computes in **O(n)** time.
pub fn try_reserve_exact(&mut self, additional: usize) -> Result<(), TryReserveError> {
self.core.try_reserve_exact(additional)
}
/// Shrink the capacity of the map as much as possible.
///
/// Computes in **O(n)** time.
pub fn shrink_to_fit(&mut self) {
self.core.shrink_to(0);
}
/// Shrink the capacity of the map with a lower limit.
///
/// Computes in **O(n)** time.
pub fn shrink_to(&mut self, min_capacity: usize) {
self.core.shrink_to(min_capacity);
}
fn hash<Q: ?Sized + Hash>(&self, key: &Q) -> HashValue {
let mut h = self.hash_builder.build_hasher();
key.hash(&mut h);
HashValue(h.finish() as usize)
}
/// Insert a key-value pair in the map.
///
/// If an equivalent key already exists in the map: the key remains and
/// retains in its place in the order, its corresponding value is updated
/// with `value` and the older value is returned inside `Some(_)`.
///
/// If no equivalent key existed in the map: the new key-value pair is
/// inserted, last in order, and `None` is returned.
///
/// Computes in **O(1)** time (amortized average).
///
/// See also [`entry`](#method.entry) if you you want to insert *or* modify
/// or if you need to get the index of the corresponding key-value pair.
pub fn insert(&mut self, key: K, value: V) -> Option<V> {
self.insert_full(key, value).1
}
/// Insert a key-value pair in the map, and get their index.
///
/// If an equivalent key already exists in the map: the key remains and
/// retains in its place in the order, its corresponding value is updated
/// with `value` and the older value is returned inside `(index, Some(_))`.
///
/// If no equivalent key existed in the map: the new key-value pair is
/// inserted, last in order, and `(index, None)` is returned.
///
/// Computes in **O(1)** time (amortized average).
///
/// See also [`entry`](#method.entry) if you you want to insert *or* modify
/// or if you need to get the index of the corresponding key-value pair.
pub fn insert_full(&mut self, key: K, value: V) -> (usize, Option<V>) {
let hash = self.hash(&key);
self.core.insert_full(hash, key, value)
}
/// Get the given key’s corresponding entry in the map for insertion and/or
/// in-place manipulation.
///
/// Computes in **O(1)** time (amortized average).
pub fn entry(&mut self, key: K) -> Entry<'_, K, V> {
let hash = self.hash(&key);
self.core.entry(hash, key)
}
/// Return `true` if an equivalent to `key` exists in the map.
///
/// Computes in **O(1)** time (average).
pub fn contains_key<Q: ?Sized>(&self, key: &Q) -> bool
where
Q: Hash + Equivalent<K>,
{
self.get_index_of(key).is_some()
}
/// Return a reference to the value stored for `key`, if it is present,
/// else `None`.
///
/// Computes in **O(1)** time (average).
pub fn get<Q: ?Sized>(&self, key: &Q) -> Option<&V>
where
Q: Hash + Equivalent<K>,
{
if let Some(i) = self.get_index_of(key) {
let entry = &self.as_entries()[i];
Some(&entry.value)
} else {
None
}
}
/// Return references to the key-value pair stored for `key`,
/// if it is present, else `None`.
///
/// Computes in **O(1)** time (average).
pub fn get_key_value<Q: ?Sized>(&self, key: &Q) -> Option<(&K, &V)>
where
Q: Hash + Equivalent<K>,
{
if let Some(i) = self.get_index_of(key) {
let entry = &self.as_entries()[i];
Some((&entry.key, &entry.value))
} else {
None
}
}
/// Return item index, key and value
pub fn get_full<Q: ?Sized>(&self, key: &Q) -> Option<(usize, &K, &V)>
where
Q: Hash + Equivalent<K>,
{
if let Some(i) = self.get_index_of(key) {
let entry = &self.as_entries()[i];
Some((i, &entry.key, &entry.value))
} else {
None
}
}
/// Return item index, if it exists in the map
///
/// Computes in **O(1)** time (average).
pub fn get_index_of<Q: ?Sized>(&self, key: &Q) -> Option<usize>
where
Q: Hash + Equivalent<K>,
{
if self.is_empty() {
None
} else {
let hash = self.hash(key);
self.core.get_index_of(hash, key)
}
}
pub fn get_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<&mut V>
where
Q: Hash + Equivalent<K>,
{
if let Some(i) = self.get_index_of(key) {
let entry = &mut self.as_entries_mut()[i];
Some(&mut entry.value)
} else {
None
}
}
pub fn get_full_mut<Q: ?Sized>(&mut self, key: &Q) -> Option<(usize, &K, &mut V)>
where
Q: Hash + Equivalent<K>,
{
if let Some(i) = self.get_index_of(key) {
let entry = &mut self.as_entries_mut()[i];
Some((i, &entry.key, &mut entry.value))
} else {
None
}
}
/// Remove the key-value pair equivalent to `key` and return
/// its value.
///
/// **NOTE:** This is equivalent to `.swap_remove(key)`, if you need to
/// preserve the order of the keys in the map, use `.shift_remove(key)`
/// instead.
///
/// Computes in **O(1)** time (average).
pub fn remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
Q: Hash + Equivalent<K>,
{
self.swap_remove(key)
}
/// Remove and return the key-value pair equivalent to `key`.
///
/// **NOTE:** This is equivalent to `.swap_remove_entry(key)`, if you need to
/// preserve the order of the keys in the map, use `.shift_remove_entry(key)`
/// instead.
///
/// Computes in **O(1)** time (average).
pub fn remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
where
Q: Hash + Equivalent<K>,
{
self.swap_remove_entry(key)
}
/// Remove the key-value pair equivalent to `key` and return
/// its value.
///
/// Like `Vec::swap_remove`, the pair is removed by swapping it with the
/// last element of the map and popping it off. **This perturbs
/// the position of what used to be the last element!**
///
/// Return `None` if `key` is not in map.
///
/// Computes in **O(1)** time (average).
pub fn swap_remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
Q: Hash + Equivalent<K>,
{
self.swap_remove_full(key).map(third)
}
/// Remove and return the key-value pair equivalent to `key`.
///
/// Like `Vec::swap_remove`, the pair is removed by swapping it with the
/// last element of the map and popping it off. **This perturbs
/// the position of what used to be the last element!**
///
/// Return `None` if `key` is not in map.
///
/// Computes in **O(1)** time (average).
pub fn swap_remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
where
Q: Hash + Equivalent<K>,
{
match self.swap_remove_full(key) {
Some((_, key, value)) => Some((key, value)),
None => None,
}
}
/// Remove the key-value pair equivalent to `key` and return it and
/// the index it had.
///
/// Like `Vec::swap_remove`, the pair is removed by swapping it with the
/// last element of the map and popping it off. **This perturbs
/// the position of what used to be the last element!**
///
/// Return `None` if `key` is not in map.
///
/// Computes in **O(1)** time (average).
pub fn swap_remove_full<Q: ?Sized>(&mut self, key: &Q) -> Option<(usize, K, V)>
where
Q: Hash + Equivalent<K>,
{
if self.is_empty() {
return None;
}
let hash = self.hash(key);
self.core.swap_remove_full(hash, key)
}
/// Remove the key-value pair equivalent to `key` and return
/// its value.
///
/// Like `Vec::remove`, the pair is removed by shifting all of the
/// elements that follow it, preserving their relative order.
/// **This perturbs the index of all of those elements!**
///
/// Return `None` if `key` is not in map.
///
/// Computes in **O(n)** time (average).
pub fn shift_remove<Q: ?Sized>(&mut self, key: &Q) -> Option<V>
where
Q: Hash + Equivalent<K>,
{
self.shift_remove_full(key).map(third)
}
/// Remove and return the key-value pair equivalent to `key`.
///
/// Like `Vec::remove`, the pair is removed by shifting all of the
/// elements that follow it, preserving their relative order.
/// **This perturbs the index of all of those elements!**
///
/// Return `None` if `key` is not in map.
///
/// Computes in **O(n)** time (average).
pub fn shift_remove_entry<Q: ?Sized>(&mut self, key: &Q) -> Option<(K, V)>
where
Q: Hash + Equivalent<K>,
{
match self.shift_remove_full(key) {
Some((_, key, value)) => Some((key, value)),
None => None,
}
}
/// Remove the key-value pair equivalent to `key` and return it and
/// the index it had.
///
/// Like `Vec::remove`, the pair is removed by shifting all of the
/// elements that follow it, preserving their relative order.
/// **This perturbs the index of all of those elements!**
///
/// Return `None` if `key` is not in map.
///
/// Computes in **O(n)** time (average).
pub fn shift_remove_full<Q: ?Sized>(&mut self, key: &Q) -> Option<(usize, K, V)>
where
Q: Hash + Equivalent<K>,
{
if self.is_empty() {
return None;
}
let hash = self.hash(key);
self.core.shift_remove_full(hash, key)
}
/// Remove the last key-value pair
///
/// This preserves the order of the remaining elements.
///
/// Computes in **O(1)** time (average).
pub fn pop(&mut self) -> Option<(K, V)> {
self.core.pop()
}
/// Scan through each key-value pair in the map and keep those where the
/// closure `keep` returns `true`.
///
/// The elements are visited in order, and remaining elements keep their
/// order.
///
/// Computes in **O(n)** time (average).
pub fn retain<F>(&mut self, mut keep: F)
where
F: FnMut(&K, &mut V) -> bool,
{
self.core.retain_in_order(move |k, v| keep(k, v));
}
pub(crate) fn retain_mut<F>(&mut self, keep: F)
where
F: FnMut(&mut K, &mut V) -> bool,
{
self.core.retain_in_order(keep);
}
/// Sort the map’s key-value pairs by the default ordering of the keys.
///
/// See [`sort_by`](Self::sort_by) for details.
pub fn sort_keys(&mut self)
where
K: Ord,
{
self.with_entries(move |entries| {
entries.sort_by(move |a, b| K::cmp(&a.key, &b.key));
});
}
/// Sort the map’s key-value pairs in place using the comparison
/// function `cmp`.
///
/// The comparison function receives two key and value pairs to compare (you
/// can sort by keys or values or their combination as needed).
///
/// Computes in **O(n log n + c)** time and **O(n)** space where *n* is
/// the length of the map and *c* the capacity. The sort is stable.
pub fn sort_by<F>(&mut self, mut cmp: F)
where
F: FnMut(&K, &V, &K, &V) -> Ordering,
{
self.with_entries(move |entries| {
entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
});
}
/// Sort the key-value pairs of the map and return a by-value iterator of
/// the key-value pairs with the result.
///
/// The sort is stable.
pub fn sorted_by<F>(self, mut cmp: F) -> IntoIter<K, V>
where
F: FnMut(&K, &V, &K, &V) -> Ordering,
{
let mut entries = self.into_entries();
entries.sort_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
IntoIter::new(entries)
}
/// Sort the map's key-value pairs by the default ordering of the keys, but
/// may not preserve the order of equal elements.
///
/// See [`sort_unstable_by`](Self::sort_unstable_by) for details.
pub fn sort_unstable_keys(&mut self)
where
K: Ord,
{
self.with_entries(move |entries| {
entries.sort_unstable_by(move |a, b| K::cmp(&a.key, &b.key));
});
}
/// Sort the map's key-value pairs in place using the comparison function `cmp`, but
/// may not preserve the order of equal elements.
///
/// The comparison function receives two key and value pairs to compare (you
/// can sort by keys or values or their combination as needed).
///
/// Computes in **O(n log n + c)** time where *n* is
/// the length of the map and *c* is the capacity. The sort is unstable.
pub fn sort_unstable_by<F>(&mut self, mut cmp: F)
where
F: FnMut(&K, &V, &K, &V) -> Ordering,
{
self.with_entries(move |entries| {
entries.sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
});
}
/// Sort the key-value pairs of the map and return a by-value iterator of
/// the key-value pairs with the result.
///
/// The sort is unstable.
#[inline]
pub fn sorted_unstable_by<F>(self, mut cmp: F) -> IntoIter<K, V>
where
F: FnMut(&K, &V, &K, &V) -> Ordering,
{
let mut entries = self.into_entries();
entries.sort_unstable_by(move |a, b| cmp(&a.key, &a.value, &b.key, &b.value));
IntoIter::new(entries)
}
/// Sort the map’s key-value pairs in place using a sort-key extraction function.
///
/// During sorting, the function is called at most once per entry, by using temporary storage
/// to remember the results of its evaluation. The order of calls to the function is
/// unspecified and may change between versions of `indexmap` or the standard library.
///
/// Computes in **O(m n + n log n + c)** time () and **O(n)** space, where the function is
/// **O(m)**, *n* is the length of the map, and *c* the capacity. The sort is stable.
pub fn sort_by_cached_key<T, F>(&mut self, mut sort_key: F)
where
T: Ord,
F: FnMut(&K, &V) -> T,
{
self.with_entries(move |entries| {
entries.sort_by_cached_key(move |a| sort_key(&a.key, &a.value));
});
}
/// Reverses the order of the map’s key-value pairs in place.
///
/// Computes in **O(n)** time and **O(1)** space.
pub fn reverse(&mut self) {
self.core.reverse()
}
}
impl<K, V, S> IndexMap<K, V, S> {
/// Returns a slice of all the key-value pairs in the map.
///
/// Computes in **O(1)** time.
pub fn as_slice(&self) -> &Slice<K, V> {
Slice::from_slice(self.as_entries())
}
/// Returns a mutable slice of all the key-value pairs in the map.
///
/// Computes in **O(1)** time.
pub fn as_mut_slice(&mut self) -> &mut Slice<K, V> {
Slice::from_mut_slice(self.as_entries_mut())
}
/// Converts into a boxed slice of all the key-value pairs in the map.
///
/// Note that this will drop the inner hash table and any excess capacity.
pub fn into_boxed_slice(self) -> Box<Slice<K, V>> {
Slice::from_boxed(self.into_entries().into_boxed_slice())
}
/// Get a key-value pair by index
///
/// Valid indices are *0 <= index < self.len()*
///
/// Computes in **O(1)** time.
pub fn get_index(&self, index: usize) -> Option<(&K, &V)> {
self.as_entries().get(index).map(Bucket::refs)
}
/// Get a key-value pair by index
///
/// Valid indices are *0 <= index < self.len()*
///
/// Computes in **O(1)** time.
pub fn get_index_mut(&mut self, index: usize) -> Option<(&K, &mut V)> {
self.as_entries_mut().get_mut(index).map(Bucket::ref_mut)
}
/// Returns a slice of key-value pairs in the given range of indices.
///
/// Valid indices are *0 <= index < self.len()*
///
/// Computes in **O(1)** time.
pub fn get_range<R: RangeBounds<usize>>(&self, range: R) -> Option<&Slice<K, V>> {
let entries = self.as_entries();
let range = try_simplify_range(range, entries.len())?;
entries.get(range).map(Slice::from_slice)
}
/// Returns a mutable slice of key-value pairs in the given range of indices.
///
/// Valid indices are *0 <= index < self.len()*
///
/// Computes in **O(1)** time.
pub fn get_range_mut<R: RangeBounds<usize>>(&mut self, range: R) -> Option<&mut Slice<K, V>> {
let entries = self.as_entries_mut();
let range = try_simplify_range(range, entries.len())?;
entries.get_mut(range).map(Slice::from_mut_slice)
}
/// Get the first key-value pair
///
/// Computes in **O(1)** time.
pub fn first(&self) -> Option<(&K, &V)> {
self.as_entries().first().map(Bucket::refs)
}
/// Get the first key-value pair, with mutable access to the value
///
/// Computes in **O(1)** time.
pub fn first_mut(&mut self) -> Option<(&K, &mut V)> {
self.as_entries_mut().first_mut().map(Bucket::ref_mut)
}
/// Get the last key-value pair
///
/// Computes in **O(1)** time.
pub fn last(&self) -> Option<(&K, &V)> {
self.as_entries().last().map(Bucket::refs)
}
/// Get the last key-value pair, with mutable access to the value
///
/// Computes in **O(1)** time.
pub fn last_mut(&mut self) -> Option<(&K, &mut V)> {
self.as_entries_mut().last_mut().map(Bucket::ref_mut)
}
/// Remove the key-value pair by index
///
/// Valid indices are *0 <= index < self.len()*
///
/// Like `Vec::swap_remove`, the pair is removed by swapping it with the
/// last element of the map and popping it off. **This perturbs
/// the position of what used to be the last element!**
///
/// Computes in **O(1)** time (average).
pub fn swap_remove_index(&mut self, index: usize) -> Option<(K, V)> {
self.core.swap_remove_index(index)
}
/// Remove the key-value pair by index
///
/// Valid indices are *0 <= index < self.len()*
///
/// Like `Vec::remove`, the pair is removed by shifting all of the
/// elements that follow it, preserving their relative order.
/// **This perturbs the index of all of those elements!**
///
/// Computes in **O(n)** time (average).
pub fn shift_remove_index(&mut self, index: usize) -> Option<(K, V)> {
self.core.shift_remove_index(index)
}
/// Moves the position of a key-value pair from one index to another
/// by shifting all other pairs in-between.
///
/// * If `from < to`, the other pairs will shift down while the targeted pair moves up.
/// * If `from > to`, the other pairs will shift up while the targeted pair moves down.
///
/// ***Panics*** if `from` or `to` are out of bounds.
///
/// Computes in **O(n)** time (average).
pub fn move_index(&mut self, from: usize, to: usize) {
self.core.move_index(from, to)
}
/// Swaps the position of two key-value pairs in the map.
///
/// ***Panics*** if `a` or `b` are out of bounds.
pub fn swap_indices(&mut self, a: usize, b: usize) {
self.core.swap_indices(a, b)
}
}
/// Access `IndexMap` values corresponding to a key.
///
/// # Examples
///
/// ```
/// use indexmap::IndexMap;
///
/// let mut map = IndexMap::new();
/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
/// map.insert(word.to_lowercase(), word.to_uppercase());
/// }
/// assert_eq!(map["lorem"], "LOREM");
/// assert_eq!(map["ipsum"], "IPSUM");
/// ```
///
/// ```should_panic
/// use indexmap::IndexMap;
///
/// let mut map = IndexMap::new();
/// map.insert("foo", 1);
/// println!("{:?}", map["bar"]); // panics!
/// ```
impl<K, V, Q: ?Sized, S> Index<&Q> for IndexMap<K, V, S>
where
Q: Hash + Equivalent<K>,
K: Hash + Eq,
S: BuildHasher,
{
type Output = V;
/// Returns a reference to the value corresponding to the supplied `key`.
///
/// ***Panics*** if `key` is not present in the map.
fn index(&self, key: &Q) -> &V {
self.get(key).expect("IndexMap: key not found")
}
}
/// Access `IndexMap` values corresponding to a key.
///
/// Mutable indexing allows changing / updating values of key-value
/// pairs that are already present.
///
/// You can **not** insert new pairs with index syntax, use `.insert()`.
///
/// # Examples
///
/// ```
/// use indexmap::IndexMap;
///
/// let mut map = IndexMap::new();
/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
/// map.insert(word.to_lowercase(), word.to_string());
/// }
/// let lorem = &mut map["lorem"];
/// assert_eq!(lorem, "Lorem");
/// lorem.retain(char::is_lowercase);
/// assert_eq!(map["lorem"], "orem");
/// ```
///
/// ```should_panic
/// use indexmap::IndexMap;
///
/// let mut map = IndexMap::new();
/// map.insert("foo", 1);
/// map["bar"] = 1; // panics!
/// ```
impl<K, V, Q: ?Sized, S> IndexMut<&Q> for IndexMap<K, V, S>
where
Q: Hash + Equivalent<K>,
K: Hash + Eq,
S: BuildHasher,
{
/// Returns a mutable reference to the value corresponding to the supplied `key`.
///
/// ***Panics*** if `key` is not present in the map.
fn index_mut(&mut self, key: &Q) -> &mut V {
self.get_mut(key).expect("IndexMap: key not found")
}
}
/// Access `IndexMap` values at indexed positions.
///
/// # Examples
///
/// ```
/// use indexmap::IndexMap;
///
/// let mut map = IndexMap::new();
/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
/// map.insert(word.to_lowercase(), word.to_uppercase());
/// }
/// assert_eq!(map[0], "LOREM");
/// assert_eq!(map[1], "IPSUM");
/// map.reverse();
/// assert_eq!(map[0], "AMET");
/// assert_eq!(map[1], "SIT");
/// map.sort_keys();
/// assert_eq!(map[0], "AMET");
/// assert_eq!(map[1], "DOLOR");
/// ```
///
/// ```should_panic
/// use indexmap::IndexMap;
///
/// let mut map = IndexMap::new();
/// map.insert("foo", 1);
/// println!("{:?}", map[10]); // panics!
/// ```
impl<K, V, S> Index<usize> for IndexMap<K, V, S> {
type Output = V;
/// Returns a reference to the value at the supplied `index`.
///
/// ***Panics*** if `index` is out of bounds.
fn index(&self, index: usize) -> &V {
self.get_index(index)
.expect("IndexMap: index out of bounds")
.1
}
}
/// Access `IndexMap` values at indexed positions.
///
/// Mutable indexing allows changing / updating indexed values
/// that are already present.
///
/// You can **not** insert new values with index syntax, use `.insert()`.
///
/// # Examples
///
/// ```
/// use indexmap::IndexMap;
///
/// let mut map = IndexMap::new();
/// for word in "Lorem ipsum dolor sit amet".split_whitespace() {
/// map.insert(word.to_lowercase(), word.to_string());
/// }
/// let lorem = &mut map[0];
/// assert_eq!(lorem, "Lorem");
/// lorem.retain(char::is_lowercase);
/// assert_eq!(map["lorem"], "orem");
/// ```
///
/// ```should_panic
/// use indexmap::IndexMap;
///
/// let mut map = IndexMap::new();
/// map.insert("foo", 1);
/// map[10] = 1; // panics!
/// ```
impl<K, V, S> IndexMut<usize> for IndexMap<K, V, S> {
/// Returns a mutable reference to the value at the supplied `index`.
///
/// ***Panics*** if `index` is out of bounds.
fn index_mut(&mut self, index: usize) -> &mut V {
self.get_index_mut(index)
.expect("IndexMap: index out of bounds")
.1
}
}
impl<K, V, S> FromIterator<(K, V)> for IndexMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher + Default,
{
/// Create an `IndexMap` from the sequence of key-value pairs in the
/// iterable.
///
/// `from_iter` uses the same logic as `extend`. See
/// [`extend`](#method.extend) for more details.
fn from_iter<I: IntoIterator<Item = (K, V)>>(iterable: I) -> Self {
let iter = iterable.into_iter();
let (low, _) = iter.size_hint();
let mut map = Self::with_capacity_and_hasher(low, <_>::default());
map.extend(iter);
map
}
}
#[cfg(feature = "std")]
#[cfg_attr(docsrs, doc(cfg(feature = "std")))]
impl<K, V, const N: usize> From<[(K, V); N]> for IndexMap<K, V, RandomState>
where
K: Hash + Eq,
{
/// # Examples
///
/// ```
/// use indexmap::IndexMap;
///
/// let map1 = IndexMap::from([(1, 2), (3, 4)]);
/// let map2: IndexMap<_, _> = [(1, 2), (3, 4)].into();
/// assert_eq!(map1, map2);
/// ```
fn from(arr: [(K, V); N]) -> Self {
Self::from_iter(arr)
}
}
impl<K, V, S> Extend<(K, V)> for IndexMap<K, V, S>
where
K: Hash + Eq,
S: BuildHasher,
{
/// Extend the map with all key-value pairs in the iterable.
///
/// This is equivalent to calling [`insert`](#method.insert) for each of
/// them in order, which means that for keys that already existed
/// in the map, their value is updated but it keeps the existing order.
///
/// New keys are inserted in the order they appear in the sequence. If
/// equivalents of a key occur more than once, the last corresponding value
/// prevails.
fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iterable: I) {
// (Note: this is a copy of `std`/`hashbrown`'s reservation logic.)
// Keys may be already present or show multiple times in the iterator.
// Reserve the entire hint lower bound if the map is empty.
// Otherwise reserve half the hint (rounded up), so the map
// will only resize twice in the worst case.
let iter = iterable.into_iter();
let reserve = if self.is_empty() {
iter.size_hint().0
} else {
(iter.size_hint().0 + 1) / 2
};
self.reserve(reserve);
iter.for_each(move |(k, v)| {
self.insert(k, v);
});
}
}
impl<'a, K, V, S> Extend<(&'a K, &'a V)> for IndexMap<K, V, S>
where
K: Hash + Eq + Copy,
V: Copy,
S: BuildHasher,
{
/// Extend the map with all key-value pairs in the iterable.
///
/// See the first extend method for more details.
fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iterable: I) {
self.extend(iterable.into_iter().map(|(&key, &value)| (key, value)));
}
}
impl<K, V, S> Default for IndexMap<K, V, S>
where
S: Default,
{
/// Return an empty `IndexMap`
fn default() -> Self {
Self::with_capacity_and_hasher(0, S::default())
}
}
impl<K, V1, S1, V2, S2> PartialEq<IndexMap<K, V2, S2>> for IndexMap<K, V1, S1>
where
K: Hash + Eq,
V1: PartialEq<V2>,
S1: BuildHasher,
S2: BuildHasher,
{
fn eq(&self, other: &IndexMap<K, V2, S2>) -> bool {
if self.len() != other.len() {
return false;
}
self.iter()
.all(|(key, value)| other.get(key).map_or(false, |v| *value == *v))
}
}
impl<K, V, S> Eq for IndexMap<K, V, S>
where
K: Eq + Hash,
V: Eq,
S: BuildHasher,
{
}
|
#[derive(Serialize, Deserialize, Debug)]
pub struct Task {
content: String,
id: u32
}
impl Task {
pub fn new(content: String, id: u32) -> Task {
Task {
content,
id,
}
}
}
|
extern crate gitlab;
extern crate github_rs;
extern crate toml;
#[macro_use] extern crate serde_derive;
extern crate failure;
#[macro_use]
extern crate failure_derive;
extern crate rayon;
extern crate serde_json;
extern crate clap;
mod action;
mod actions;
mod config;
mod gitlab_impl;
mod github_impl;
use self::action::Action;
use self::actions::GitAction;
use self::config::*;
use self::github_impl::GitHub;
use std::process::exit;
use gitlab::Gitlab;
use clap::{App, Arg, SubCommand};
fn main() {
let matches = App::new("gitrepoman")
.version("0.1")
.about("Manages git repositories across GitHub organizations or GitLab instances")
.author("Michael Aaron Murphy")
.arg(Arg::with_name("ssh")
.long("--ssh")
.short("s"))
.arg(Arg::with_name("force")
.long("force")
.short("f"))
.arg(Arg::with_name("config")
.long("config")
.short("c")
.takes_value(true))
.subcommand(SubCommand::with_name("gitlab")
.arg(Arg::with_name("DOMAIN").required(true))
.arg(Arg::with_name("NAMESPACE").required(true))
.arg(Arg::with_name("ACTION").required(true)))
.subcommand(SubCommand::with_name("github")
.arg(Arg::with_name("DOMAIN").required(true))
.arg(Arg::with_name("ACTION").required(true)))
.get_matches();
let config_path: &str = matches.value_of("config").unwrap_or("secret.toml");
let config = match Config::new(config_path) {
Ok(config) => config,
Err(why) => {
eprintln!("failed to get config: {}", why);
exit(1);
}
};
let flags = if matches.occurrences_of("ssh") > 0 { 0b01 } else { 0b00 }
+ if matches.occurrences_of("force") > 0 { 0b10 } else { 0b00 };
let (source, org, action, ns) = if let Some(matches) = matches.subcommand_matches("gitlab") {
(
GitService::GitLab,
matches.value_of("DOMAIN").unwrap(),
matches.value_of("ACTION").unwrap(),
matches.value_of("NAMESPACE").unwrap_or("")
)
} else if let Some(matches) = matches.subcommand_matches("github") {
(
GitService::GitHub,
matches.value_of("DOMAIN").unwrap(),
matches.value_of("ACTION").unwrap(),
""
)
} else {
eprintln!("no subcommand provided");
exit(1);
};
macro_rules! client {
($name:tt, $token:expr) => {{
let token = match $token {
Some(token) => token,
None => {
eprintln!("no {} token provided", stringify!($name));
exit(1);
}
};
match $name::new(org.to_owned(), token) {
Ok(client) => Box::new(client),
Err(why) => {
eprintln!("unable to authenticate client: {}", why);
exit(1);
}
}
}};
}
let authenticated: Box<dyn GitAction> = match source {
GitService::GitHub => client!(GitHub, config.github),
GitService::GitLab => client!(Gitlab, config.gitlab),
};
match Action::from(action) {
Ok(Action::List) => authenticated.list(ns),
Ok(Action::Clone) => authenticated.clone(flags, ns),
Ok(Action::Pull) => authenticated.pull(flags, ns),
Ok(Action::Checkout) => authenticated.checkout(flags, ns),
Ok(Action::MirrorPull) => authenticated.mirror_pull(flags, ns),
Ok(Action::MirrorPush) => authenticated.mirror_push(flags, ns),
Err(cmd) => {
eprintln!("{} is not a valid command", cmd);
exit(1);
}
}
}
|
use crate::{
analysis::Analysis,
app::{AppContext, AppContextPointer},
errors::SondeError,
};
use gtk::{
glib::translate::IntoGlib, prelude::*, EventControllerKey, Inhibit, TextBuffer, TextTag,
TextView,
};
use metfor::{Fahrenheit, Inches, Quantity};
use std::{fmt::Write, rc::Rc};
const TEXT_AREA_ID: &str = "indexes_text_area";
const HEADER_LINE: &str = "----------------------------------------------------\n";
pub fn set_up_indexes_area(acp: &AppContextPointer) -> Result<(), SondeError> {
use gtk::gdk::Key;
let text_area: TextView = acp.fetch_widget(TEXT_AREA_ID)?;
let key_press = EventControllerKey::new();
let ac = Rc::clone(acp);
key_press.connect_key_pressed(move |_key_press, key, _code, _key_modifier| {
if key == Key::KP_Right || key == Key::Right {
ac.display_next();
} else if key == Key::KP_Left || key == Key::Left {
ac.display_previous();
}
Inhibit(true)
});
text_area.add_controller(key_press);
let text_buffer = text_area.buffer();
set_up_tags(&text_buffer, acp);
set_text(&text_buffer, "No data, loaded");
text_buffer.create_mark(Some("scroll_mark"), &text_buffer.start_iter(), true);
Ok(())
}
pub fn update_indexes_area(ac: &AppContext) {
let text_area: TextView = match ac.fetch_widget::<TextView>(TEXT_AREA_ID) {
Ok(ta) => ta,
Err(_) => return,
};
let text_buffer = text_area.buffer();
let anal = match ac.get_sounding_for_display() {
Some(anal) => anal,
None => return,
};
let anal = &anal.borrow();
let text = &mut String::with_capacity(4096);
push_profile_indexes(text, anal);
push_parcel_indexes(text, anal);
push_fire_indexes(text, anal);
// Get the scroll position before setting the text
let old_adj = text_area.vadjustment().map(|adj| adj.value());
set_text(&text_buffer, text);
highlight_parcel(&text_buffer, ac);
// I don't totally understand this, but after quite a lot of experimentation this works
// well at keeping the scroll of the text view in the same area as you step through
// time.
if let Some(adj) = text_area.vadjustment() {
if let Some(val) = old_adj {
let val = if val.round() < (adj.upper() - adj.page_size()).round() {
val.round()
} else {
(adj.upper() - adj.page_size() - 1.0).round()
};
adj.set_value(val);
}
}
}
fn set_up_tags(tb: &TextBuffer, ac: &AppContext) {
let tag_table = tb.tag_table();
let config = ac.config.borrow();
let default_tag = TextTag::builder()
.name("default")
.family(&config.font_name)
.size_points(config.text_area_font_size_points)
.weight(gtk::pango::Weight::Bold.into_glib())
.build();
let success = tag_table.add(&default_tag);
debug_assert!(success, "Failed to add tag to text tag table");
let rgba = config.parcel_indexes_highlight;
let parcel_tag = TextTag::builder()
.name("parcel")
.background_rgba(>k::gdk::RGBA::new(
rgba.0 as f32,
rgba.1 as f32,
rgba.2 as f32,
rgba.3 as f32,
))
.build();
let success = tag_table.add(&parcel_tag);
debug_assert!(success, "Failed to add tag to text tag table");
}
fn set_text(tb: &TextBuffer, txt: &str) {
tb.set_text(txt);
let start = tb.start_iter();
let end = tb.end_iter();
tb.apply_tag_by_name("default", &start, &end);
}
macro_rules! push_prof {
($anal: expr, $buf:ident, $name:expr, $selector:tt, $format:expr, $empty_val:expr) => {
$buf.push_str($name);
$anal
.$selector()
.into_option()
.and_then(|val| {
write!($buf, $format, val.unpack()).unwrap();
Some(())
})
.or_else(|| {
$buf.push_str($empty_val);
Some(())
});
$buf.push('\n');
};
($anal: expr, $buf:ident, $name:expr, $selector:tt, $format:expr, temp, $empty_val:expr) => {
$buf.push_str($name);
$anal
.$selector()
.into_option()
.and_then(|val| {
write!(
$buf,
$format,
val.unpack(),
Fahrenheit::from(val).unpack().round()
)
.unwrap();
Some(())
})
.or_else(|| {
$buf.push_str($empty_val);
Some(())
});
$buf.push('\n');
};
($anal: expr, $buf:ident, $name:expr, $selector:tt, $format:expr, mm, $empty_val:expr) => {
$buf.push_str($name);
$anal
.$selector()
.into_option()
.and_then(|val| {
let val_inches = Inches::from(val);
if val_inches < Inches(0.01) && val_inches > Inches(0.0) {
write!($buf, " T").unwrap();
} else {
write!(
$buf,
$format,
(val.unpack() * 10.0).round() / 10.0,
(val_inches.unpack() * 100.0).round() / 100.0,
)
.unwrap();
}
Some(())
})
.or_else(|| {
$buf.push_str($empty_val);
Some(())
});
$buf.push('\n');
};
($anal: expr, $buf:ident, $name:expr, $selector:tt, $format:expr, cape, $empty_val:expr) => {
$buf.push_str($name);
$anal
.$selector()
.into_option()
.and_then(|val| {
let mps = (val.unpack() * 2.0).sqrt();
let mph = mps * 2.23694;
write!($buf, $format, val.unpack(), mps.round(), mph.round()).unwrap();
Some(())
})
.or_else(|| {
$buf.push_str($empty_val);
Some(())
});
$buf.push('\n');
};
}
#[inline]
#[rustfmt::skip]
fn push_profile_indexes(buffer: &mut String, anal: &Analysis){
let empty_val = " - ";
buffer.push('\n');
buffer.push_str("Index Value\n");
buffer.push_str(HEADER_LINE);
push_prof!(anal, buffer, "1-hour Precip ", provider_1hr_precip, "{:>7.1} mm ({:>4.2} in)", mm, empty_val);
push_prof!(anal, buffer, "DCAPE ", dcape, "{:>5.0} J/kg ({:>3.0} m/s {:>3.0} m/h)", cape, empty_val);
push_prof!(anal, buffer, "PWAT ", pwat, "{:>7.0} mm ({:>4.2} in)", mm, empty_val);
push_prof!(anal, buffer, "Downrush T ", downrush_t, "{:>8.0}\u{00b0}C ({:>3.0}\u{00b0}F)", temp, empty_val);
push_prof!(anal, buffer, "Convective T ", convective_t, "{:>8.0}\u{00b0}C ({:>3.0}\u{00b0}F) ", temp, empty_val);
push_prof!(anal, buffer, "3km SR Helicity (RM)", sr_helicity_3k_rm, "{:>4.0} m\u{00b2}/s\u{00b2}", empty_val);
push_prof!(anal, buffer, "3km SR Helicity (LM)", sr_helicity_3k_lm, "{:>4.0} m\u{00b2}/s\u{00b2}", empty_val);
push_prof!(anal, buffer, "Eff SR Helicity (RM)", sr_helicity_eff_rm, "{:>4.0} m\u{00b2}/s\u{00b2}", empty_val);
push_prof!(anal, buffer, "Eff SR Helicity (LM)", sr_helicity_eff_lm, "{:>4.0} m\u{00b2}/s\u{00b2}", empty_val);
}
#[inline]
#[rustfmt::skip]
fn push_parcel_indexes(buffer: &mut String, anal: &Analysis) {
buffer.push('\n');
macro_rules! push_var {
($buf:ident, $anal:ident, $selector:tt, $fmt:expr,$empty:expr) => {
$anal.$selector().into_option().and_then(|val|{
$buf.push_str(&format!($fmt, val.unpack()));
Some(())
}).or_else(||{
$buf.push_str($empty);
Some(())
});
}
}
macro_rules! parcel_index_row {
($buf:ident, $pcl_name:expr, $opt_pcl_anal:ident, $empty:expr) => {
$buf.push_str($pcl_name);
if let Some(anal) = $opt_pcl_anal {
push_var!($buf, anal, cape, " {:>5.0}", $empty);
push_var!($buf, anal, cin, " {:>5.0}", $empty);
push_var!($buf, anal, ncape, " {:>5.2}", $empty);
push_var!($buf, anal, hail_cape, " {:>5.0}", $empty);
$buf.push_str(" ");
} else {
$buf.push_str(" -- No Parcel -- ");
}
$buf.push('\n');
}
}
macro_rules! parcel_level_row {
($buf:ident, $pcl_name:expr, $opt_pcl_anal:tt, $empty:expr) => {
$buf.push_str($pcl_name);
if let Some(anal) = $opt_pcl_anal {
push_var!($buf, anal, lcl_pressure, " {:>5.0}", $empty);
push_var!($buf, anal, lcl_height_agl, " {:>6.0}", $empty);
push_var!($buf, anal, lfc_pressure, " {:>5.0}", $empty);
push_var!($buf, anal, el_pressure, " {:>5.0}", $empty);
push_var!($buf, anal, el_height_asl, " {:>6.0}", $empty);
push_var!($buf, anal, el_temperature, " {:>5.0}", $empty);
} else {
$buf.push_str(" -- No Parcel -- ");
}
$buf.push('\n');
}
}
let sfc = anal.surface_parcel_analysis();
let ml = anal.mixed_layer_parcel_analysis();
let mu = anal.most_unstable_parcel_analysis();
let con = anal.convective_parcel_analysis();
let eff = anal.effective_parcel_analysis();
let empty = " -";
buffer.push_str("Parcel CAPE CIN NCAPE Hail\n");
buffer.push_str(" J/Kg J/Kg CAPE\n");
buffer.push_str(HEADER_LINE);
parcel_index_row!(buffer, "Surface ", sfc, empty);
parcel_index_row!(buffer, "Mixed Layer ", ml, empty);
parcel_index_row!(buffer, "Most Unstable ", mu, empty);
parcel_index_row!(buffer, "Convective ", con, empty);
parcel_index_row!(buffer, "Effective ", eff, empty);
buffer.push('\n');
buffer.push_str("Parcel LCL LCL LFC EL EL EL\n");
buffer.push_str(" hPa m AGL hPa hPa m ASL C\n");
buffer.push_str(HEADER_LINE);
parcel_level_row!(buffer, "Surface ", sfc, empty);
parcel_level_row!(buffer, "Mixed Layer ", ml, empty);
parcel_level_row!(buffer, "Most Unstable ", mu, empty);
parcel_level_row!(buffer, "Convective ", con, empty);
parcel_level_row!(buffer, "Effective ", eff, empty);
}
#[inline]
#[rustfmt::skip]
fn push_fire_indexes(buffer: &mut String, anal: &Analysis) {
macro_rules! push_fire_index {
($buf:ident, $label:expr, $anal:ident, $selector:tt, $fmt:expr, $empty:expr) => {
$buf.push_str($label);
if let Some(val) = $anal.$selector().into_option() {
$buf.push_str(&format!($fmt, val.unpack()));
} else {
$buf.push_str($empty);
}
};
($buf:ident, $label:expr, $anal:ident, $selector_low:tt, $selector_high:tt, $fmt:expr, $empty:expr) => {
$buf.push_str($label);
if let (Some(val_low), Some(val_high)) =
($anal.$selector_low().into_option(),$anal.$selector_high().into_option()) {
$buf.push_str(&format!($fmt, val_low.unpack(), val_high.unpack()));
} else {
$buf.push_str($empty);
}
};
}
buffer.push('\n');
buffer.push_str("Fire Weather\n");
buffer.push_str(HEADER_LINE);
buffer.push_str("Haines Low Mid High\n");
buffer.push_str(" ");
let empty = " - ";
for &hns in [anal.haines_low(), anal.haines_mid(), anal.haines_high()].iter() {
if let Some(val) = hns.into_option() {
buffer.push_str(&format!("{:>5.0} ", val));
} else {
buffer.push_str(empty);
}
}
buffer.push('\n');
let empty = " - \n";
push_fire_index!(buffer, "HDW ", anal, hdw, "{:>12.0}\n", empty);
buffer.push_str("PFT ");
if let Some(pft_anal) = anal.pft(){
buffer.push_str(&format!("{:>10.0}GW\n", pft_anal.pft.unpack()));
} else {
buffer.push_str(empty);
}
let empty = " - \n";
buffer.push_str("\nExperimental\n");
buffer.push_str(HEADER_LINE);
push_fire_index!(buffer, "Cloud ∆T ", anal, lcl_dt_low, "{:>5.1}\u{00b0}C\n\n", empty);
push_fire_index!(buffer, "Blow Up ∆T (LMIB) ", anal, el_blow_up_dt_low, el_blow_up_dt_high, "{:>5.1}\u{00b0}C - {:>4.1}\u{00b0}C\n", empty);
push_fire_index!(buffer, "Blow Up Hgt (LMIB) ", anal, el_blow_up_height_change_low, el_blow_up_height_change_high, "{:>6.0}m - {:>4.0}m\n", empty);
}
fn highlight_parcel(tb: &TextBuffer, ac: &AppContext) {
use crate::app::config::ParcelType;
let config = ac.config.borrow();
if !config.show_parcel_profile {
return;
}
let tag = match tb.tag_table().lookup("parcel") {
Some(tag) => tag,
None => return,
};
let rgba = config.parcel_indexes_highlight;
tag.set_background_rgba(Some(>k::gdk::RGBA::new(
rgba.0 as f32,
rgba.1 as f32,
rgba.2 as f32,
rgba.3 as f32,
)));
let pcl_label: &'static str = match config.parcel_type {
ParcelType::Surface => "Surface",
ParcelType::MixedLayer => "Mixed",
ParcelType::MostUnstable => "Most",
ParcelType::Effective => "Effective",
ParcelType::Convective => "Convective",
};
let lines = tb.line_count();
for i in 0..lines {
if let Some(start) = tb.iter_at_line(i) {
let mut end = start;
end.forward_line();
if tb.text(&start, &end, false).as_str().starts_with(pcl_label) {
tb.apply_tag(&tag, &start, &end);
}
}
}
}
|
pub mod constructors;
pub mod tycons;
use super::*;
use crate::elaborate::*;
fn define_constructor<'arena>(
ctx: &mut elaborate::Context<'arena>,
con: Constructor,
sch: Scheme<'arena>,
) {
ctx.define_value(con.name, Span::dummy(), sch, IdStatus::Con(con));
}
/// This is not pretty, but we have to handle builtins for elaboration somehow
pub fn populate_context<'arena>(ctx: &mut elaborate::Context<'arena>) {
// Build the initial type environment
for tc in &tycons::T_BUILTINS {
ctx.define_type(tc.name, TypeStructure::Tycon(*tc));
}
let nil = ctx.arena.types.fresh_var(0);
define_constructor(
ctx,
constructors::C_NIL,
Scheme::Poly(vec![nil.as_tyvar().id], ctx.arena.types.list(nil)),
);
let cons = ctx.arena.types.fresh_var(0);
// The inner types of cons: 'a * 'a list
let crec = ctx
.arena
.types
.tuple(vec![cons, ctx.arena.types.list(cons)]);
define_constructor(
ctx,
constructors::C_CONS,
Scheme::Poly(
vec![cons.as_tyvar().id],
ctx.arena.types.arrow(crec, ctx.arena.types.list(cons)),
),
);
define_constructor(
ctx,
constructors::C_TRUE,
Scheme::Mono(ctx.arena.types.bool()),
);
define_constructor(
ctx,
constructors::C_FALSE,
Scheme::Mono(ctx.arena.types.bool()),
);
let reff = ctx.arena.types.fresh_var(0);
define_constructor(
ctx,
constructors::C_REF,
Scheme::Poly(
vec![reff.as_tyvar().id],
ctx.arena.types.arrow(reff, ctx.arena.types.reff(reff)),
),
);
}
|
extern crate cc;
#[cfg(target_os="macos")]
fn main() {
cc::Build::new()
.cpp(true)
.warnings(true)
.flag("-std=c++11")
.file("src/webcam/cpp/src/webcam.cpp")
.include("src/webcam/cpp/include")
.include("/usr/local/opt/opencv/include/opencv4")
.compile("libwebcam.a");
println!("cargo:rustc-link-search=native=/usr/local/opt/opencv/lib");
}
#[cfg(not(target_os="macos"))]
fn main() {
cc::Build::new()
.cpp(true)
.warnings(true)
.file("src\\webcam\\cpp\\src\\webcam.cpp")
.include("src\\webcam\\cpp\\include")
.include("C:\\tools\\opencv\\build\\include")
.compile("libwebcam.a");
}
|
pub use VkCommandBufferResetFlags::*;
#[repr(u32)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VkCommandBufferResetFlags {
VK_COMMAND_BUFFER_RESET_RELEASE_RESOURCES_BIT = 0x00000001,
}
use crate::SetupVkFlags;
#[repr(C)]
#[derive(Clone, Copy, Eq, PartialEq, Hash)]
pub struct VkCommandBufferResetFlagBits(u32);
SetupVkFlags!(VkCommandBufferResetFlags, VkCommandBufferResetFlagBits);
|
use ic_cdk::export::candid::{CandidType, Deserialize, Principal};
use std::fmt::{Display, Formatter};
#[derive(CandidType, Deserialize)]
pub enum Error {
AlreadyIsAMember,
IsNotAMember,
AccessDenied,
ForbiddenOperation,
}
impl Display for Error {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
let str = match self {
Error::AlreadyIsAMember => "AlreadyIsAMember",
Error::IsNotAMember => "IsNotAMember",
Error::AccessDenied => "AccessDenied",
Error::ForbiddenOperation => "ForbiddenOperation",
};
f.write_str(str)
}
}
pub type Controllers = Vec<Principal>;
#[derive(Clone, CandidType, Deserialize)]
pub struct ControllerList {
pub issue_controllers: Controllers,
pub revoke_controllers: Controllers,
pub event_listeners_controllers: Controllers,
}
impl ControllerList {
pub fn single(controller: Option<Principal>) -> ControllerList {
let controllers = if controller.is_some() {
vec![controller.unwrap()]
} else {
Vec::new()
};
ControllerList {
issue_controllers: controllers.clone(),
revoke_controllers: controllers.clone(),
event_listeners_controllers: controllers,
}
}
}
#[derive(CandidType, Deserialize)]
pub struct IsMemberRequest {
pub prin: Principal,
}
#[derive(CandidType, Deserialize)]
pub struct IsMemberResponse {
pub is_member: bool,
}
#[derive(CandidType, Deserialize)]
pub struct GetTotalMembersResponse {
pub total_members: u64,
}
#[derive(CandidType, Deserialize)]
pub struct IssueRevokeMembershipsRequest {
pub principals: Vec<Principal>,
}
#[derive(CandidType, Deserialize)]
pub struct GetControllersResponse {
pub controllers: ControllerList,
}
#[derive(CandidType, Deserialize)]
pub struct UpdateControllerRequest {
pub new_controllers: Controllers,
}
#[derive(CandidType, Deserialize)]
pub struct UpdateControllerResponse {
pub old_controllers: Controllers,
}
#[derive(CandidType, Deserialize)]
pub struct InitRequest {
pub default_controllers: Option<Controllers>,
} |
#[doc = "Reader of register _1_CTL"]
pub type R = crate::R<u32, super::_1_CTL>;
#[doc = "Writer for register _1_CTL"]
pub type W = crate::W<u32, super::_1_CTL>;
#[doc = "Register _1_CTL `reset()`'s with value 0"]
impl crate::ResetValue for super::_1_CTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `ENABLE`"]
pub type ENABLE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ENABLE`"]
pub struct ENABLE_W<'a> {
w: &'a mut W,
}
impl<'a> ENABLE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !0x01) | ((value as u32) & 0x01);
self.w
}
}
#[doc = "Reader of field `MODE`"]
pub type MODE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MODE`"]
pub struct MODE_W<'a> {
w: &'a mut W,
}
impl<'a> MODE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "Reader of field `DEBUG`"]
pub type DEBUG_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DEBUG`"]
pub struct DEBUG_W<'a> {
w: &'a mut W,
}
impl<'a> DEBUG_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 << 2)) | (((value as u32) & 0x01) << 2);
self.w
}
}
#[doc = "Reader of field `LOADUPD`"]
pub type LOADUPD_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LOADUPD`"]
pub struct LOADUPD_W<'a> {
w: &'a mut W,
}
impl<'a> LOADUPD_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 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "Reader of field `CMPAUPD`"]
pub type CMPAUPD_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CMPAUPD`"]
pub struct CMPAUPD_W<'a> {
w: &'a mut W,
}
impl<'a> CMPAUPD_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 << 4)) | (((value as u32) & 0x01) << 4);
self.w
}
}
#[doc = "Reader of field `CMPBUPD`"]
pub type CMPBUPD_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CMPBUPD`"]
pub struct CMPBUPD_W<'a> {
w: &'a mut W,
}
impl<'a> CMPBUPD_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 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "PWMnGENA Update Mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum GENAUPD_A {
#[doc = "0: Immediate"]
I = 0,
#[doc = "2: Locally Synchronized"]
LS = 2,
#[doc = "3: Globally Synchronized"]
GS = 3,
}
impl From<GENAUPD_A> for u8 {
#[inline(always)]
fn from(variant: GENAUPD_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `GENAUPD`"]
pub type GENAUPD_R = crate::R<u8, GENAUPD_A>;
impl GENAUPD_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, GENAUPD_A> {
use crate::Variant::*;
match self.bits {
0 => Val(GENAUPD_A::I),
2 => Val(GENAUPD_A::LS),
3 => Val(GENAUPD_A::GS),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `I`"]
#[inline(always)]
pub fn is_i(&self) -> bool {
*self == GENAUPD_A::I
}
#[doc = "Checks if the value of the field is `LS`"]
#[inline(always)]
pub fn is_ls(&self) -> bool {
*self == GENAUPD_A::LS
}
#[doc = "Checks if the value of the field is `GS`"]
#[inline(always)]
pub fn is_gs(&self) -> bool {
*self == GENAUPD_A::GS
}
}
#[doc = "Write proxy for field `GENAUPD`"]
pub struct GENAUPD_W<'a> {
w: &'a mut W,
}
impl<'a> GENAUPD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: GENAUPD_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn i(self) -> &'a mut W {
self.variant(GENAUPD_A::I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn ls(self) -> &'a mut W {
self.variant(GENAUPD_A::LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn gs(self) -> &'a mut W {
self.variant(GENAUPD_A::GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 6)) | (((value as u32) & 0x03) << 6);
self.w
}
}
#[doc = "PWMnGENB Update Mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum GENBUPD_A {
#[doc = "0: Immediate"]
I = 0,
#[doc = "2: Locally Synchronized"]
LS = 2,
#[doc = "3: Globally Synchronized"]
GS = 3,
}
impl From<GENBUPD_A> for u8 {
#[inline(always)]
fn from(variant: GENBUPD_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `GENBUPD`"]
pub type GENBUPD_R = crate::R<u8, GENBUPD_A>;
impl GENBUPD_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, GENBUPD_A> {
use crate::Variant::*;
match self.bits {
0 => Val(GENBUPD_A::I),
2 => Val(GENBUPD_A::LS),
3 => Val(GENBUPD_A::GS),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `I`"]
#[inline(always)]
pub fn is_i(&self) -> bool {
*self == GENBUPD_A::I
}
#[doc = "Checks if the value of the field is `LS`"]
#[inline(always)]
pub fn is_ls(&self) -> bool {
*self == GENBUPD_A::LS
}
#[doc = "Checks if the value of the field is `GS`"]
#[inline(always)]
pub fn is_gs(&self) -> bool {
*self == GENBUPD_A::GS
}
}
#[doc = "Write proxy for field `GENBUPD`"]
pub struct GENBUPD_W<'a> {
w: &'a mut W,
}
impl<'a> GENBUPD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: GENBUPD_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn i(self) -> &'a mut W {
self.variant(GENBUPD_A::I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn ls(self) -> &'a mut W {
self.variant(GENBUPD_A::LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn gs(self) -> &'a mut W {
self.variant(GENBUPD_A::GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 8)) | (((value as u32) & 0x03) << 8);
self.w
}
}
#[doc = "PWMnDBCTL Update Mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum DBCTLUPD_A {
#[doc = "0: Immediate"]
I = 0,
#[doc = "2: Locally Synchronized"]
LS = 2,
#[doc = "3: Globally Synchronized"]
GS = 3,
}
impl From<DBCTLUPD_A> for u8 {
#[inline(always)]
fn from(variant: DBCTLUPD_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `DBCTLUPD`"]
pub type DBCTLUPD_R = crate::R<u8, DBCTLUPD_A>;
impl DBCTLUPD_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, DBCTLUPD_A> {
use crate::Variant::*;
match self.bits {
0 => Val(DBCTLUPD_A::I),
2 => Val(DBCTLUPD_A::LS),
3 => Val(DBCTLUPD_A::GS),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `I`"]
#[inline(always)]
pub fn is_i(&self) -> bool {
*self == DBCTLUPD_A::I
}
#[doc = "Checks if the value of the field is `LS`"]
#[inline(always)]
pub fn is_ls(&self) -> bool {
*self == DBCTLUPD_A::LS
}
#[doc = "Checks if the value of the field is `GS`"]
#[inline(always)]
pub fn is_gs(&self) -> bool {
*self == DBCTLUPD_A::GS
}
}
#[doc = "Write proxy for field `DBCTLUPD`"]
pub struct DBCTLUPD_W<'a> {
w: &'a mut W,
}
impl<'a> DBCTLUPD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DBCTLUPD_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn i(self) -> &'a mut W {
self.variant(DBCTLUPD_A::I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn ls(self) -> &'a mut W {
self.variant(DBCTLUPD_A::LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn gs(self) -> &'a mut W {
self.variant(DBCTLUPD_A::GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 10)) | (((value as u32) & 0x03) << 10);
self.w
}
}
#[doc = "PWMnDBRISE Update Mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum DBRISEUPD_A {
#[doc = "0: Immediate"]
I = 0,
#[doc = "2: Locally Synchronized"]
LS = 2,
#[doc = "3: Globally Synchronized"]
GS = 3,
}
impl From<DBRISEUPD_A> for u8 {
#[inline(always)]
fn from(variant: DBRISEUPD_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `DBRISEUPD`"]
pub type DBRISEUPD_R = crate::R<u8, DBRISEUPD_A>;
impl DBRISEUPD_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, DBRISEUPD_A> {
use crate::Variant::*;
match self.bits {
0 => Val(DBRISEUPD_A::I),
2 => Val(DBRISEUPD_A::LS),
3 => Val(DBRISEUPD_A::GS),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `I`"]
#[inline(always)]
pub fn is_i(&self) -> bool {
*self == DBRISEUPD_A::I
}
#[doc = "Checks if the value of the field is `LS`"]
#[inline(always)]
pub fn is_ls(&self) -> bool {
*self == DBRISEUPD_A::LS
}
#[doc = "Checks if the value of the field is `GS`"]
#[inline(always)]
pub fn is_gs(&self) -> bool {
*self == DBRISEUPD_A::GS
}
}
#[doc = "Write proxy for field `DBRISEUPD`"]
pub struct DBRISEUPD_W<'a> {
w: &'a mut W,
}
impl<'a> DBRISEUPD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DBRISEUPD_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn i(self) -> &'a mut W {
self.variant(DBRISEUPD_A::I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn ls(self) -> &'a mut W {
self.variant(DBRISEUPD_A::LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn gs(self) -> &'a mut W {
self.variant(DBRISEUPD_A::GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12);
self.w
}
}
#[doc = "PWMnDBFALL Update Mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum DBFALLUPD_A {
#[doc = "0: Immediate"]
I = 0,
#[doc = "2: Locally Synchronized"]
LS = 2,
#[doc = "3: Globally Synchronized"]
GS = 3,
}
impl From<DBFALLUPD_A> for u8 {
#[inline(always)]
fn from(variant: DBFALLUPD_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `DBFALLUPD`"]
pub type DBFALLUPD_R = crate::R<u8, DBFALLUPD_A>;
impl DBFALLUPD_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, DBFALLUPD_A> {
use crate::Variant::*;
match self.bits {
0 => Val(DBFALLUPD_A::I),
2 => Val(DBFALLUPD_A::LS),
3 => Val(DBFALLUPD_A::GS),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `I`"]
#[inline(always)]
pub fn is_i(&self) -> bool {
*self == DBFALLUPD_A::I
}
#[doc = "Checks if the value of the field is `LS`"]
#[inline(always)]
pub fn is_ls(&self) -> bool {
*self == DBFALLUPD_A::LS
}
#[doc = "Checks if the value of the field is `GS`"]
#[inline(always)]
pub fn is_gs(&self) -> bool {
*self == DBFALLUPD_A::GS
}
}
#[doc = "Write proxy for field `DBFALLUPD`"]
pub struct DBFALLUPD_W<'a> {
w: &'a mut W,
}
impl<'a> DBFALLUPD_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: DBFALLUPD_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Immediate"]
#[inline(always)]
pub fn i(self) -> &'a mut W {
self.variant(DBFALLUPD_A::I)
}
#[doc = "Locally Synchronized"]
#[inline(always)]
pub fn ls(self) -> &'a mut W {
self.variant(DBFALLUPD_A::LS)
}
#[doc = "Globally Synchronized"]
#[inline(always)]
pub fn gs(self) -> &'a mut W {
self.variant(DBFALLUPD_A::GS)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x03 << 14)) | (((value as u32) & 0x03) << 14);
self.w
}
}
#[doc = "Reader of field `FLTSRC`"]
pub type FLTSRC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FLTSRC`"]
pub struct FLTSRC_W<'a> {
w: &'a mut W,
}
impl<'a> FLTSRC_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `MINFLTPER`"]
pub type MINFLTPER_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MINFLTPER`"]
pub struct MINFLTPER_W<'a> {
w: &'a mut W,
}
impl<'a> MINFLTPER_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 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `LATCH`"]
pub type LATCH_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LATCH`"]
pub struct LATCH_W<'a> {
w: &'a mut W,
}
impl<'a> LATCH_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
impl R {
#[doc = "Bit 0 - PWM Block Enable"]
#[inline(always)]
pub fn enable(&self) -> ENABLE_R {
ENABLE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Counter Mode"]
#[inline(always)]
pub fn mode(&self) -> MODE_R {
MODE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Debug Mode"]
#[inline(always)]
pub fn debug(&self) -> DEBUG_R {
DEBUG_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Load Register Update Mode"]
#[inline(always)]
pub fn loadupd(&self) -> LOADUPD_R {
LOADUPD_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Comparator A Update Mode"]
#[inline(always)]
pub fn cmpaupd(&self) -> CMPAUPD_R {
CMPAUPD_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Comparator B Update Mode"]
#[inline(always)]
pub fn cmpbupd(&self) -> CMPBUPD_R {
CMPBUPD_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bits 6:7 - PWMnGENA Update Mode"]
#[inline(always)]
pub fn genaupd(&self) -> GENAUPD_R {
GENAUPD_R::new(((self.bits >> 6) & 0x03) as u8)
}
#[doc = "Bits 8:9 - PWMnGENB Update Mode"]
#[inline(always)]
pub fn genbupd(&self) -> GENBUPD_R {
GENBUPD_R::new(((self.bits >> 8) & 0x03) as u8)
}
#[doc = "Bits 10:11 - PWMnDBCTL Update Mode"]
#[inline(always)]
pub fn dbctlupd(&self) -> DBCTLUPD_R {
DBCTLUPD_R::new(((self.bits >> 10) & 0x03) as u8)
}
#[doc = "Bits 12:13 - PWMnDBRISE Update Mode"]
#[inline(always)]
pub fn dbriseupd(&self) -> DBRISEUPD_R {
DBRISEUPD_R::new(((self.bits >> 12) & 0x03) as u8)
}
#[doc = "Bits 14:15 - PWMnDBFALL Update Mode"]
#[inline(always)]
pub fn dbfallupd(&self) -> DBFALLUPD_R {
DBFALLUPD_R::new(((self.bits >> 14) & 0x03) as u8)
}
#[doc = "Bit 16 - Fault Condition Source"]
#[inline(always)]
pub fn fltsrc(&self) -> FLTSRC_R {
FLTSRC_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - Minimum Fault Period"]
#[inline(always)]
pub fn minfltper(&self) -> MINFLTPER_R {
MINFLTPER_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - Latch Fault Input"]
#[inline(always)]
pub fn latch(&self) -> LATCH_R {
LATCH_R::new(((self.bits >> 18) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - PWM Block Enable"]
#[inline(always)]
pub fn enable(&mut self) -> ENABLE_W {
ENABLE_W { w: self }
}
#[doc = "Bit 1 - Counter Mode"]
#[inline(always)]
pub fn mode(&mut self) -> MODE_W {
MODE_W { w: self }
}
#[doc = "Bit 2 - Debug Mode"]
#[inline(always)]
pub fn debug(&mut self) -> DEBUG_W {
DEBUG_W { w: self }
}
#[doc = "Bit 3 - Load Register Update Mode"]
#[inline(always)]
pub fn loadupd(&mut self) -> LOADUPD_W {
LOADUPD_W { w: self }
}
#[doc = "Bit 4 - Comparator A Update Mode"]
#[inline(always)]
pub fn cmpaupd(&mut self) -> CMPAUPD_W {
CMPAUPD_W { w: self }
}
#[doc = "Bit 5 - Comparator B Update Mode"]
#[inline(always)]
pub fn cmpbupd(&mut self) -> CMPBUPD_W {
CMPBUPD_W { w: self }
}
#[doc = "Bits 6:7 - PWMnGENA Update Mode"]
#[inline(always)]
pub fn genaupd(&mut self) -> GENAUPD_W {
GENAUPD_W { w: self }
}
#[doc = "Bits 8:9 - PWMnGENB Update Mode"]
#[inline(always)]
pub fn genbupd(&mut self) -> GENBUPD_W {
GENBUPD_W { w: self }
}
#[doc = "Bits 10:11 - PWMnDBCTL Update Mode"]
#[inline(always)]
pub fn dbctlupd(&mut self) -> DBCTLUPD_W {
DBCTLUPD_W { w: self }
}
#[doc = "Bits 12:13 - PWMnDBRISE Update Mode"]
#[inline(always)]
pub fn dbriseupd(&mut self) -> DBRISEUPD_W {
DBRISEUPD_W { w: self }
}
#[doc = "Bits 14:15 - PWMnDBFALL Update Mode"]
#[inline(always)]
pub fn dbfallupd(&mut self) -> DBFALLUPD_W {
DBFALLUPD_W { w: self }
}
#[doc = "Bit 16 - Fault Condition Source"]
#[inline(always)]
pub fn fltsrc(&mut self) -> FLTSRC_W {
FLTSRC_W { w: self }
}
#[doc = "Bit 17 - Minimum Fault Period"]
#[inline(always)]
pub fn minfltper(&mut self) -> MINFLTPER_W {
MINFLTPER_W { w: self }
}
#[doc = "Bit 18 - Latch Fault Input"]
#[inline(always)]
pub fn latch(&mut self) -> LATCH_W {
LATCH_W { w: self }
}
}
|
use std::error;
use std::fmt;
use std::io;
use hyper;
use serde_json;
#[derive(Debug)]
pub enum DropBoxError {
APIError(String),
HyperError(hyper::error::Error),
IOError(io::Error),
SerdeError(serde_json::error::Error),
}
impl fmt::Display for DropBoxError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
DropBoxError::HyperError(ref err) => err.fmt(f),
DropBoxError::IOError(ref err) => err.fmt(f),
DropBoxError::SerdeError(ref err) => err.fmt(f),
DropBoxError::APIError(ref res) => write!(f, "JSON Response: {}", res),
}
}
}
impl error::Error for DropBoxError {
fn description(&self) -> &str {
match *self {
DropBoxError::HyperError(ref err) => err.description(),
DropBoxError::IOError(ref err) => err.description(),
DropBoxError::SerdeError(ref err) => err.description(),
DropBoxError::APIError(ref res) => "Dropbox could not process request",
}
}
}
impl From<io::Error> for DropBoxError {
fn from(error: io::Error) -> DropBoxError {
DropBoxError::IOError(error)
}
}
impl From<hyper::error::Error> for DropBoxError {
fn from(error: hyper::error::Error) -> DropBoxError {
DropBoxError::HyperError(error)
}
}
impl From<serde_json::error::Error> for DropBoxError {
fn from(error: serde_json::error::Error) -> DropBoxError {
DropBoxError::SerdeError(error)
}
}
|
pub mod instruction;
pub mod parsing;
pub type Word = u16;
|
use std::pin::Pin;
use futures::{future, stream};
use juniper::{graphql_subscription, GraphQLObject};
type Stream<'a, I> = Pin<Box<dyn futures::Stream<Item = I> + Send + 'a>>;
#[derive(GraphQLObject)]
struct ObjA {
test: String,
}
struct ObjB;
#[graphql_subscription]
impl ObjB {
async fn id(&self, obj: ObjA) -> Stream<'static, &'static str> {
Box::pin(stream::once(future::ready("funA")))
}
}
fn main() {}
|
// Example is taken from
// http://matt2xu.github.io/async-http-client
extern crate async_http_client;
use async_http_client::prelude::*;
use async_http_client::{HttpRequest, HttpCodec};
fn main() {
let req = HttpRequest::get("http://www.google.com").unwrap();
let mut core = Core::new().unwrap();
let addr = req.addr().unwrap();
let handle = core.handle();
let (res, _) = core.run(TcpStream::connect(&addr, &handle).and_then(|connection| {
req.send(connection)
})).unwrap();
println!("got response {}", res.unwrap());
}
|
use crate::vec3::Vec3;
use crate::ray::Ray;
use rand::prelude::*;
use std::f64::consts::PI;
pub struct ScatterInfo(pub Ray,pub Vec3);
pub trait Material : Sync + Send {
fn scatter(&self, ray_in : Ray, point : Vec3, normal: Vec3) -> Option<ScatterInfo>;
}
fn random_unit_vector() -> Vec3 {
let mut rng=rand::thread_rng();
let a = rng.gen_range(0.0, 2.0*PI);
let z = rng.gen_range(-1.0,1.0);
let r = ((1.0-z*z) as f64).sqrt();
Vec3(r*a.cos(), r*a.sin(),z)
}
fn random_in_unit_sphere() -> Vec3 {
loop {
let p = Vec3::random_vector(-1.0,1.0);
if p.length_squared() < 1.0 {
return p
}
}
}
#[derive(Copy,Clone,Debug)]
pub struct Lambertian {
pub albedo: Vec3
}
impl Lambertian {
pub fn new(albedo :Vec3) -> Lambertian {
Lambertian { albedo }
}
}
impl Material for Lambertian {
fn scatter(&self, ray_in : Ray, point: Vec3, normal: Vec3) -> Option<ScatterInfo> {
let scatter_direction = normal + random_unit_vector();
let scattered = Ray::new(point, scatter_direction);
let attenuation = self.albedo;
Some(ScatterInfo(scattered,attenuation))
}
}
#[derive(Copy,Clone,Debug)]
pub struct Metallic {
pub albedo: Vec3,
pub fuzz: f64,
}
impl Metallic {
pub fn new(albedo: Vec3, fuzz: f64) -> Metallic {
Metallic { albedo, fuzz }
}
pub fn reflect(v: Vec3, n: Vec3) -> Vec3 {
v-n*Vec3::dot(v,n)*2.0
}
}
impl Material for Metallic {
fn scatter(&self, ray_in: Ray, point: Vec3, normal: Vec3) -> Option<ScatterInfo> {
let reflected = Self::reflect(ray_in.direction.unit_vector(), normal);
let scattered = Ray::new(point, reflected+random_in_unit_sphere()*self.fuzz);
let attenuation = self.albedo;
match Vec3::dot(scattered.direction, normal) > 0.0 {
true => Some(ScatterInfo(scattered, attenuation)),
false => None
}
}
}
|
use std::default::Default;
#[derive(PartialEq)]
pub enum Type {
A,
NS,
MD,
MF,
CNAME,
SOA,
MB,
MG,
MR,
NULL,
WKS,
PTR,
HINFO,
MINFO,
MX,
TXT,
RP,
AFSDB,
X25,
ISDN,
RT,
NSAP,
NSAPPTR,
SIG,
KEY,
PX,
GPOS,
AAAA,
LOC,
NXT,
EID,
NIMLOC,
SRV,
ATMA,
NAPTR,
KX,
CERT,
DNAME,
SINK,
OPT,
APL,
DS,
SSHFP,
IPSECKEY,
RRSIG,
NSEC,
DNSKEY,
DHCID,
NSEC3,
NSEC3PARAM,
TLSA,
HIP,
NINFO,
RKEY,
TALINK,
CDS,
CDNSKEY,
OPENPGPKEY,
SPF,
UINFO,
UID,
GID,
UNSPEC,
NID,
L32,
L64,
LP,
EUI48,
EUI64,
TKEY,
TSIG,
IXFR,
AXFR,
MAILB,
MAILA,
URI,
CAA,
TA,
DLV,
Wildcard,
Private(u16),
Unassigned(u16),
Reserved,
}
impl Default for Type {
fn default() -> Type {
Type::Wildcard
}
}
pub fn unpack(value: u16) -> Type {
return match value {
0x0001 => Type::A,
0x0002 => Type::NS,
0x0003 => Type::MD,
0x0004 => Type::MF,
0x0005 => Type::CNAME,
0x0006 => Type::SOA,
0x0007 => Type::MB,
0x0008 => Type::MG,
0x0009 => Type::MR,
0x000A => Type::NULL,
0x000B => Type::WKS,
0x000C => Type::PTR,
0x000D => Type::HINFO,
0x000E => Type::MINFO,
0x000F => Type::MX,
0x0010 => Type::TXT,
0x0011 => Type::RP,
0x0012 => Type::AFSDB,
0x0013 => Type::X25,
0x0014 => Type::ISDN,
0x0015 => Type::RT,
0x0016 => Type::NSAP,
0x0017 => Type::NSAPPTR,
0x0018 => Type::SIG,
0x0019 => Type::KEY,
0x001A => Type::PX,
0x001B => Type::GPOS,
0x001C => Type::AAAA,
0x001D => Type::LOC,
0x001E => Type::NXT,
0x001F => Type::EID,
0x0020 => Type::NIMLOC,
0x0021 => Type::SRV,
0x0022 => Type::ATMA,
0x0023 => Type::NAPTR,
0x0024 => Type::KX,
0x0025 => Type::CERT,
0x0026 => Type::DNAME,
0x0027 => Type::SINK,
0x0028 => Type::OPT,
0x0029 => Type::APL,
0x002A => Type::DS,
0x002B => Type::SSHFP,
0x002C => Type::IPSECKEY,
0x002D => Type::RRSIG,
0x002E => Type::NSEC,
0x002F => Type::DNSKEY,
0x0030 => Type::DHCID,
0x0031 => Type::NSEC3,
0x0032 => Type::NSEC3PARAM,
0x0033 => Type::TLSA,
0x0036 => Type::HIP,
0x0037 => Type::NINFO,
0x0038 => Type::RKEY,
0x0039 => Type::TALINK,
0x003A => Type::CDS,
0x003B => Type::CDNSKEY,
0x003C => Type::OPENPGPKEY,
0x0063 => Type::SPF,
0x0064 => Type::UINFO,
0x0065 => Type::UID,
0x0066 => Type::GID,
0x0067 => Type::UNSPEC,
0x0068 => Type::NID,
0x0069 => Type::L32,
0x006A => Type::L64,
0x006B => Type::LP,
0x006C => Type::EUI48,
0x006D => Type::EUI64,
0x00F9 => Type::TKEY,
0x00FA => Type::TSIG,
0x00FB => Type::IXFR,
0x00FC => Type::AXFR,
0x00FD => Type::MAILB,
0x00FE => Type::MAILA,
0x00FF => Type::Wildcard,
0x0100 => Type::URI,
0x0101 => Type::CAA,
0x8000 => Type::TA,
0x8001 => Type::DLV,
0xFFFF => Type::Reserved,
n => {
if n < 0xFF00 {
Type::Unassigned(n)
} else {
Type::Private(n)
}
}
};
}
impl std::fmt::Display for Type {
fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
Type::A => write!(fmt, "A"),
Type::NS => write!(fmt, "NS"),
Type::MD => write!(fmt, "MD"),
Type::MF => write!(fmt, "MF"),
Type::CNAME => write!(fmt, "CNAME"),
Type::SOA => write!(fmt, "SOA"),
Type::MB => write!(fmt, "MB"),
Type::MG => write!(fmt, "MG"),
Type::MR => write!(fmt, "MR"),
Type::NULL => write!(fmt, "NULL"),
Type::WKS => write!(fmt, "WKS"),
Type::PTR => write!(fmt, "PTR"),
Type::HINFO => write!(fmt, "HINFO"),
Type::MINFO => write!(fmt, "MINFO"),
Type::MX => write!(fmt, "MX"),
Type::TXT => write!(fmt, "TXT"),
Type::RP => write!(fmt, "RP"),
Type::AFSDB => write!(fmt, "AFSDB"),
Type::X25 => write!(fmt, "X25"),
Type::ISDN => write!(fmt, "ISDN"),
Type::RT => write!(fmt, "RT"),
Type::NSAP => write!(fmt, "NSAP"),
Type::NSAPPTR => write!(fmt, "NSAPPTR"),
Type::SIG => write!(fmt, "SIG"),
Type::KEY => write!(fmt, "KEY"),
Type::PX => write!(fmt, "PX"),
Type::GPOS => write!(fmt, "GPOS"),
Type::AAAA => write!(fmt, "AAAA"),
Type::LOC => write!(fmt, "LOC"),
Type::NXT => write!(fmt, "NXT"),
Type::EID => write!(fmt, "EID"),
Type::NIMLOC => write!(fmt, "NIMLOC"),
Type::SRV => write!(fmt, "SRV"),
Type::ATMA => write!(fmt, "ATMA"),
Type::NAPTR => write!(fmt, "NAPTR"),
Type::KX => write!(fmt, "KX"),
Type::CERT => write!(fmt, "CERT"),
Type::DNAME => write!(fmt, "DNAME"),
Type::SINK => write!(fmt, "SINK"),
Type::OPT => write!(fmt, "OPT"),
Type::APL => write!(fmt, "APL"),
Type::DS => write!(fmt, "DS"),
Type::SSHFP => write!(fmt, "SSHFP"),
Type::IPSECKEY => write!(fmt, "IPSECKEY"),
Type::RRSIG => write!(fmt, "RRSIG"),
Type::NSEC => write!(fmt, "NSEC"),
Type::DNSKEY => write!(fmt, "DNSKEY"),
Type::DHCID => write!(fmt, "DHCID"),
Type::NSEC3 => write!(fmt, "NSEC3"),
Type::NSEC3PARAM => write!(fmt, "NSEC3PARAM"),
Type::TLSA => write!(fmt, "TLSA"),
Type::HIP => write!(fmt, "HIP"),
Type::NINFO => write!(fmt, "NINFO"),
Type::RKEY => write!(fmt, "RKEY"),
Type::TALINK => write!(fmt, "TALINK"),
Type::CDS => write!(fmt, "CDS"),
Type::CDNSKEY => write!(fmt, "CDNSKEY"),
Type::OPENPGPKEY => write!(fmt, "OPENPGPKEY"),
Type::SPF => write!(fmt, "SPF"),
Type::UINFO => write!(fmt, "UINFO"),
Type::UID => write!(fmt, "UID"),
Type::GID => write!(fmt, "GID"),
Type::UNSPEC => write!(fmt, "UNSPEC"),
Type::NID => write!(fmt, "NID"),
Type::L32 => write!(fmt, "L32"),
Type::L64 => write!(fmt, "L64"),
Type::LP => write!(fmt, "LP"),
Type::EUI48 => write!(fmt, "EUI48"),
Type::EUI64 => write!(fmt, "EUI64"),
Type::TKEY => write!(fmt, "TKEY"),
Type::TSIG => write!(fmt, "TSIG"),
Type::IXFR => write!(fmt, "IXFR"),
Type::AXFR => write!(fmt, "AXFR"),
Type::MAILB => write!(fmt, "MAILB"),
Type::MAILA => write!(fmt, "MAILA"),
Type::Wildcard => write!(fmt, "Wildcard"),
Type::URI => write!(fmt, "URI"),
Type::CAA => write!(fmt, "CAA"),
Type::TA => write!(fmt, "TA"),
Type::DLV => write!(fmt, "DLV"),
Type::Reserved => write!(fmt, "Reserved"),
Type::Unassigned(n) => write!(fmt, "Unassigned({})", n),
Type::Private(n) => write!(fmt, "Private({})", n),
}
}
}
|
use crate::buffer::StreamBuffer;
use crate::constants;
use crate::constraints::Constraints;
use crate::content_disposition::ContentDisposition;
use crate::helpers;
use crate::state::{MultipartState, StreamingStage};
use crate::Field;
use bytes::Bytes;
use futures::stream::{Stream, TryStreamExt};
use std::ops::DerefMut;
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::task::{Context, Poll};
#[cfg(feature = "reader")]
use tokio::io::AsyncRead;
#[cfg(feature = "reader")]
use tokio_util::codec::{BytesCodec, FramedRead};
/// Represents the implementation of `multipart/form-data` formatted data.
///
/// This will parse the source stream into [`Field`](./struct.Field.html) instances via its [`Stream`](https://docs.rs/futures/0.3.5/futures/stream/trait.Stream.html)
/// implementation.
///
/// To maintain consistency in the underlying stream, this will not yield more than one [`Field`](./struct.Field.html) at a time.
/// A [`Drop`](https://doc.rust-lang.org/nightly/std/ops/trait.Drop.html) implementation on [`Field`](./struct.Field.html) is used to signal
/// when it's time to move forward, so do avoid leaking that type or anything which contains it.
///
/// The Fields can be accessed via the [`Stream`](./struct.Multipart.html#impl-Stream) API or the methods defined in this type.
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let stream = once(async move { Result::<Bytes, Infallible>::Ok(Bytes::from(data)) });
/// let mut multipart = Multipart::new(stream, "X-BOUNDARY");
///
/// while let Some(field) = multipart.next_field().await.unwrap() {
/// println!("Field: {:?}", field.text().await)
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
pub struct Multipart {
state: Arc<Mutex<MultipartState>>,
constraints: Constraints,
fallback_boundary: Option<String>,
}
impl Multipart {
/// Construct a new `Multipart` instance with the given [`Bytes`](https://docs.rs/bytes/0.5.4/bytes/struct.Bytes.html) stream and the boundary.
pub fn new<S, O, E, B>(stream: S, boundary: B) -> Multipart
where
S: Stream<Item = Result<O, E>> + Send + 'static,
O: Into<Bytes> + 'static,
E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
B: Into<String>,
{
let constraints = Constraints::default();
let stream = stream
.map_ok(|b| b.into())
.map_err(|err| crate::Error::StreamReadFailed(err.into()));
let state = MultipartState {
buffer: StreamBuffer::new(stream, constraints.size_limit.whole_stream),
boundary: boundary.into(),
stage: StreamingStage::ReadingBoundary,
is_prev_field_consumed: true,
next_field_waker: None,
next_field_idx: 0,
curr_field_name: None,
curr_field_size_limit: constraints.size_limit.per_field,
curr_field_size_counter: 0,
};
Multipart {
state: Arc::new(Mutex::new(state)),
constraints,
fallback_boundary: None,
}
}
/// Set a raw fallback boundary to process.
///
/// This allows to process an arbitrary boundary if the boundary provided
/// in constructors fn fails to work, for instance, due to an
/// `IncompleteStream` error.
///
/// Please provide a full boundary, including double hyphen, example:
/// `--single-boundary \r`
///
/// The provided boundary is processed if default boundary fails.
///
/// This does not check if boundary is standard compliant, that is to say,
/// there is no check on if received boundary starts with double hyphen and
/// ends with CRLF.
///
/// **Note: This fn is meant to be used as a last resort when normal boundary
/// parse does not work.**
pub fn with_fallback_boundary(mut self, s: impl std::string::ToString) -> Multipart
{
self.fallback_boundary = Some(s.to_string());
self
}
/// Construct a new `Multipart` instance with the given [`Bytes`](https://docs.rs/bytes/0.5.4/bytes/struct.Bytes.html) stream and the boundary.
pub fn new_with_constraints<S, O, E, B>(stream: S, boundary: B, constraints: Constraints) -> Multipart
where
S: Stream<Item = Result<O, E>> + Send + 'static,
O: Into<Bytes> + 'static,
E: Into<Box<dyn std::error::Error + Send + Sync>> + 'static,
B: Into<String>,
{
let stream = stream
.map_ok(|b| b.into())
.map_err(|err| crate::Error::StreamReadFailed(err.into()));
let state = MultipartState {
buffer: StreamBuffer::new(stream, constraints.size_limit.whole_stream),
boundary: boundary.into(),
stage: StreamingStage::ReadingBoundary,
is_prev_field_consumed: true,
next_field_waker: None,
next_field_idx: 0,
curr_field_name: None,
curr_field_size_limit: constraints.size_limit.per_field,
curr_field_size_counter: 0,
};
Multipart {
state: Arc::new(Mutex::new(state)),
constraints,
fallback_boundary: None,
}
}
/// Construct a new `Multipart` instance with the given [`AsyncRead`](https://docs.rs/tokio/0.2.20/tokio/io/trait.AsyncRead.html) reader and the boundary.
///
/// # Optional
///
/// This requires the optional `reader` feature to be enabled.
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let reader = data.as_bytes();
/// let mut multipart = Multipart::with_reader(reader, "X-BOUNDARY");
///
/// while let Some(mut field) = multipart.next_field().await.unwrap() {
/// while let Some(chunk) = field.chunk().await.unwrap() {
/// println!("Chunk: {:?}", chunk);
/// }
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
#[cfg(feature = "reader")]
pub fn with_reader<R, B>(reader: R, boundary: B) -> Multipart
where
R: AsyncRead + Send + 'static,
B: Into<String>,
{
let stream = FramedRead::new(reader, BytesCodec::new());
Multipart::new(stream, boundary)
}
/// Construct a new `Multipart` instance with the given [`AsyncRead`](https://docs.rs/tokio/0.2.20/tokio/io/trait.AsyncRead.html) reader and the boundary.
///
/// # Optional
///
/// This requires the optional `reader` feature to be enabled.
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let reader = data.as_bytes();
/// let mut multipart = Multipart::with_reader(reader, "X-BOUNDARY");
///
/// while let Some(mut field) = multipart.next_field().await.unwrap() {
/// while let Some(chunk) = field.chunk().await.unwrap() {
/// println!("Chunk: {:?}", chunk);
/// }
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
#[cfg(feature = "reader")]
pub fn with_reader_with_constraints<R, B>(reader: R, boundary: B, constraints: Constraints) -> Multipart
where
R: AsyncRead + Send + 'static,
B: Into<String>,
{
let stream = FramedRead::new(reader, BytesCodec::new());
Multipart::new_with_constraints(stream, boundary, constraints)
}
/// Yields the next [`Field`](./struct.Field.html) if available.
///
/// For more info, go to [`Field`](./struct.Field.html#warning-about-leaks).
pub async fn next_field(&mut self) -> crate::Result<Option<Field>> {
self.try_next().await
}
/// Yields the next [`Field`](./struct.Field.html) with their positioning index as a tuple `(usize, Field)`.
///
/// For more info, go to [`Field`](./struct.Field.html#warning-about-leaks).
///
/// # Examples
///
/// ```
/// use multer::Multipart;
/// use bytes::Bytes;
/// use std::convert::Infallible;
/// use futures::stream::once;
///
/// # async fn run() {
/// let data = "--X-BOUNDARY\r\nContent-Disposition: form-data; name=\"my_text_field\"\r\n\r\nabcd\r\n--X-BOUNDARY--\r\n";
/// let reader = data.as_bytes();
/// let mut multipart = Multipart::with_reader(reader, "X-BOUNDARY");
///
/// while let Some((idx, field)) = multipart.next_field_with_idx().await.unwrap() {
/// println!("Index: {:?}, Content: {:?}", idx, field.text().await)
/// }
/// # }
/// # tokio::runtime::Runtime::new().unwrap().block_on(run());
/// ```
pub async fn next_field_with_idx(&mut self) -> crate::Result<Option<(usize, Field)>> {
self.try_next().await.map(|f| f.map(|field| (field.index(), field)))
}
}
impl Stream for Multipart {
type Item = Result<Field, crate::Error>;
fn poll_next(self: Pin<&mut Self>, cx: &mut Context) -> Poll<Option<Self::Item>> {
let mut mutex_guard = match self.state.lock() {
Ok(lock) => lock,
Err(err) => {
return Poll::Ready(Some(Err(crate::Error::LockFailure(err.to_string().into()))));
}
};
let state: &mut MultipartState = mutex_guard.deref_mut();
if state.stage == StreamingStage::Eof {
return Poll::Ready(None);
}
if !state.is_prev_field_consumed {
state.next_field_waker = Some(cx.waker().clone());
return Poll::Pending;
}
let stream_buffer = &mut state.buffer;
if let Err(err) = stream_buffer.poll_stream(cx) {
return Poll::Ready(Some(Err(crate::Error::StreamReadFailed(err.into()))));
}
if state.stage == StreamingStage::CleaningPrevFieldData {
match stream_buffer.read_field_data(state.boundary.as_str(), state.curr_field_name.as_deref()) {
Ok(Some((done, bytes))) => {
state.curr_field_size_counter += bytes.len() as u64;
if state.curr_field_size_counter > state.curr_field_size_limit {
return Poll::Ready(Some(Err(crate::Error::FieldSizeExceeded {
limit: state.curr_field_size_limit,
field_name: state.curr_field_name.clone(),
})));
}
if done {
state.stage = StreamingStage::ReadingBoundary;
} else {
return Poll::Pending;
}
}
Ok(None) => {
return Poll::Pending;
}
Err(err) => {
return Poll::Ready(Some(Err(err)));
}
}
}
if state.stage == StreamingStage::ReadingBoundary {
let boundary = &state.boundary;
let boundary_deriv_len = constants::BOUNDARY_EXT.len() + boundary.len() + 2;
let boundary_bytes = match stream_buffer.read_exact(boundary_deriv_len) {
Some(bytes) => {
bytes
},
None => {
return if stream_buffer.eof {
Poll::Ready(Some(Err(crate::Error::IncompleteStream)))
} else {
Poll::Pending
};
}
};
if &boundary_bytes[..]
== format!("{}{}{}", constants::BOUNDARY_EXT, boundary, constants::BOUNDARY_EXT).as_bytes()
{
state.stage = StreamingStage::Eof;
return Poll::Ready(None);
}
if &boundary_bytes[..] != format!("{}{}{}", constants::BOUNDARY_EXT, boundary, constants::CRLF).as_bytes() {
let mut fallback_failed = true;
if self.fallback_boundary.is_some() {
let raw_boundary = self.fallback_boundary.as_ref().unwrap();
if &boundary_bytes[..] == raw_boundary.as_bytes() {
fallback_failed = false;
state.stage = StreamingStage::ReadingFieldHeaders;
}
}
if fallback_failed {
return Poll::Ready(Some(Err(crate::Error::IncompleteStream)));
}
} else {
state.stage = StreamingStage::ReadingFieldHeaders;
}
}
if state.stage == StreamingStage::ReadingFieldHeaders {
let header_bytes = match stream_buffer.read_until(constants::CRLF_CRLF.as_bytes()) {
Some(bytes) => bytes,
None => {
return if stream_buffer.eof {
return Poll::Ready(Some(Err(crate::Error::IncompleteStream)));
} else {
Poll::Pending
};
}
};
let mut headers = [httparse::EMPTY_HEADER; constants::MAX_HEADERS];
let headers = match httparse::parse_headers(&header_bytes, &mut headers) {
Ok(httparse::Status::Complete((_, raw_headers))) => {
match helpers::convert_raw_headers_to_header_map(raw_headers) {
Ok(headers) => headers,
Err(err) => {
return Poll::Ready(Some(Err(err)));
}
}
}
Ok(httparse::Status::Partial) => {
return Poll::Ready(Some(Err(crate::Error::IncompleteHeaders)));
}
Err(err) => {
return Poll::Ready(Some(Err(crate::Error::ReadHeaderFailed(err.into()))));
}
};
state.stage = StreamingStage::ReadingFieldData;
state.is_prev_field_consumed = false;
let field_idx = state.next_field_idx;
state.next_field_idx += 1;
let content_disposition = ContentDisposition::parse(&headers);
let field_size_limit = self
.constraints
.size_limit
.extract_size_limit_for(content_disposition.field_name.as_deref());
state.curr_field_name = content_disposition.field_name.clone();
state.curr_field_size_limit = field_size_limit;
state.curr_field_size_counter = 0;
drop(mutex_guard);
let next_field = Field::new(Arc::clone(&self.state), headers, field_idx, content_disposition);
let field_name = next_field.name().map(|name| name.to_owned());
if !self.constraints.is_it_allowed(field_name.as_deref()) {
return Poll::Ready(Some(Err(crate::Error::UnknownField {
field_name: field_name.clone(),
})));
}
return Poll::Ready(Some(Ok(next_field)));
}
state.next_field_waker = Some(cx.waker().clone());
Poll::Pending
}
}
|
use thiserror::Error;
#[derive(Error, Debug)]
pub enum BinaryParsingError {
#[error("too small buffer, expected minimum {0} bytes")]
BufferSmall(usize),
#[error("invalid command given: 0x{0:X}")]
InvalidCommand(u8),
#[error("invalid transport protocol given: 0x{0:X}")]
InvalidTransportProtocol(u8),
#[error("invalid address family given: 0x{0:X}")]
InvalidAddressFamily(u8),
#[error("invalid version: {0}")]
InvalidVersion(u8),
}
#[derive(Error, Debug)]
pub enum Version1ParsingError {
#[error("unknown address family given")]
InvalidAddressFamily,
#[error("expected a space at {1} where 0x{0:X} was given")]
ExpectedSpace(u8, usize),
#[error("expected a CRLF")]
ExpectedCRLF,
#[error("the addresses were not of the same family")]
UnequalAddressFamilies,
}
#[derive(Error, Debug)]
pub enum EncodingError {
#[error("cannot have a destination port but no source port")]
DestinationPortButNoSource,
}
#[derive(Error, Debug)]
pub enum DecodingError {
#[error("the data given is not a PROXY protocol header")]
NotProxyHeader,
#[error("too small buffer, expected minimum {0} bytes")]
BufferSmall(usize),
#[error("cannot parse address: {0} - {1}")]
AddrParse(std::net::AddrParseError, String),
#[error("cannot parse string: {0}")]
Utf8Error(#[from] std::string::FromUtf8Error),
#[error("cannot parse integer: {0}")]
ParseIntError(#[from] std::num::ParseIntError),
#[error("error parsing binary header: {0}")]
BinaryParsing(#[from] BinaryParsingError),
#[error("error parsing human readable header: {0}")]
Version1Parsing(#[from] Version1ParsingError),
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - endpoint 0 register"]
pub ep0r: EP0R,
#[doc = "0x04 - endpoint 1 register"]
pub ep1r: EP1R,
#[doc = "0x08 - endpoint 2 register"]
pub ep2r: EP2R,
#[doc = "0x0c - endpoint 3 register"]
pub ep3r: EP3R,
#[doc = "0x10 - endpoint 4 register"]
pub ep4r: EP4R,
#[doc = "0x14 - endpoint 5 register"]
pub ep5r: EP5R,
#[doc = "0x18 - endpoint 6 register"]
pub ep6r: EP6R,
#[doc = "0x1c - endpoint 7 register"]
pub ep7r: EP7R,
_reserved8: [u8; 32usize],
#[doc = "0x40 - control register"]
pub cntr: CNTR,
#[doc = "0x44 - interrupt status register"]
pub istr: ISTR,
#[doc = "0x48 - frame number register"]
pub fnr: FNR,
#[doc = "0x4c - device address"]
pub daddr: DADDR,
#[doc = "0x50 - Buffer table address"]
pub btable: BTABLE,
}
#[doc = "endpoint 0 register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep0r](ep0r) module"]
pub type EP0R = crate::Reg<u32, _EP0R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EP0R;
#[doc = "`read()` method returns [ep0r::R](ep0r::R) reader structure"]
impl crate::Readable for EP0R {}
#[doc = "`write(|w| ..)` method takes [ep0r::W](ep0r::W) writer structure"]
impl crate::Writable for EP0R {}
#[doc = "endpoint 0 register"]
pub mod ep0r;
#[doc = "endpoint 1 register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep1r](ep1r) module"]
pub type EP1R = crate::Reg<u32, _EP1R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EP1R;
#[doc = "`read()` method returns [ep1r::R](ep1r::R) reader structure"]
impl crate::Readable for EP1R {}
#[doc = "`write(|w| ..)` method takes [ep1r::W](ep1r::W) writer structure"]
impl crate::Writable for EP1R {}
#[doc = "endpoint 1 register"]
pub mod ep1r;
#[doc = "endpoint 2 register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep2r](ep2r) module"]
pub type EP2R = crate::Reg<u32, _EP2R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EP2R;
#[doc = "`read()` method returns [ep2r::R](ep2r::R) reader structure"]
impl crate::Readable for EP2R {}
#[doc = "`write(|w| ..)` method takes [ep2r::W](ep2r::W) writer structure"]
impl crate::Writable for EP2R {}
#[doc = "endpoint 2 register"]
pub mod ep2r;
#[doc = "endpoint 3 register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep3r](ep3r) module"]
pub type EP3R = crate::Reg<u32, _EP3R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EP3R;
#[doc = "`read()` method returns [ep3r::R](ep3r::R) reader structure"]
impl crate::Readable for EP3R {}
#[doc = "`write(|w| ..)` method takes [ep3r::W](ep3r::W) writer structure"]
impl crate::Writable for EP3R {}
#[doc = "endpoint 3 register"]
pub mod ep3r;
#[doc = "endpoint 4 register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep4r](ep4r) module"]
pub type EP4R = crate::Reg<u32, _EP4R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EP4R;
#[doc = "`read()` method returns [ep4r::R](ep4r::R) reader structure"]
impl crate::Readable for EP4R {}
#[doc = "`write(|w| ..)` method takes [ep4r::W](ep4r::W) writer structure"]
impl crate::Writable for EP4R {}
#[doc = "endpoint 4 register"]
pub mod ep4r;
#[doc = "endpoint 5 register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep5r](ep5r) module"]
pub type EP5R = crate::Reg<u32, _EP5R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EP5R;
#[doc = "`read()` method returns [ep5r::R](ep5r::R) reader structure"]
impl crate::Readable for EP5R {}
#[doc = "`write(|w| ..)` method takes [ep5r::W](ep5r::W) writer structure"]
impl crate::Writable for EP5R {}
#[doc = "endpoint 5 register"]
pub mod ep5r;
#[doc = "endpoint 6 register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep6r](ep6r) module"]
pub type EP6R = crate::Reg<u32, _EP6R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EP6R;
#[doc = "`read()` method returns [ep6r::R](ep6r::R) reader structure"]
impl crate::Readable for EP6R {}
#[doc = "`write(|w| ..)` method takes [ep6r::W](ep6r::W) writer structure"]
impl crate::Writable for EP6R {}
#[doc = "endpoint 6 register"]
pub mod ep6r;
#[doc = "endpoint 7 register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep7r](ep7r) module"]
pub type EP7R = crate::Reg<u32, _EP7R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _EP7R;
#[doc = "`read()` method returns [ep7r::R](ep7r::R) reader structure"]
impl crate::Readable for EP7R {}
#[doc = "`write(|w| ..)` method takes [ep7r::W](ep7r::W) writer structure"]
impl crate::Writable for EP7R {}
#[doc = "endpoint 7 register"]
pub mod ep7r;
#[doc = "control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [cntr](cntr) module"]
pub type CNTR = crate::Reg<u32, _CNTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _CNTR;
#[doc = "`read()` method returns [cntr::R](cntr::R) reader structure"]
impl crate::Readable for CNTR {}
#[doc = "`write(|w| ..)` method takes [cntr::W](cntr::W) writer structure"]
impl crate::Writable for CNTR {}
#[doc = "control register"]
pub mod cntr;
#[doc = "interrupt status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [istr](istr) module"]
pub type ISTR = crate::Reg<u32, _ISTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _ISTR;
#[doc = "`read()` method returns [istr::R](istr::R) reader structure"]
impl crate::Readable for ISTR {}
#[doc = "`write(|w| ..)` method takes [istr::W](istr::W) writer structure"]
impl crate::Writable for ISTR {}
#[doc = "interrupt status register"]
pub mod istr;
#[doc = "frame number register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [fnr](fnr) module"]
pub type FNR = crate::Reg<u32, _FNR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _FNR;
#[doc = "`read()` method returns [fnr::R](fnr::R) reader structure"]
impl crate::Readable for FNR {}
#[doc = "frame number register"]
pub mod fnr;
#[doc = "device address\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [daddr](daddr) module"]
pub type DADDR = crate::Reg<u32, _DADDR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _DADDR;
#[doc = "`read()` method returns [daddr::R](daddr::R) reader structure"]
impl crate::Readable for DADDR {}
#[doc = "`write(|w| ..)` method takes [daddr::W](daddr::W) writer structure"]
impl crate::Writable for DADDR {}
#[doc = "device address"]
pub mod daddr;
#[doc = "Buffer table address\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [btable](btable) module"]
pub type BTABLE = crate::Reg<u32, _BTABLE>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _BTABLE;
#[doc = "`read()` method returns [btable::R](btable::R) reader structure"]
impl crate::Readable for BTABLE {}
#[doc = "`write(|w| ..)` method takes [btable::W](btable::W) writer structure"]
impl crate::Writable for BTABLE {}
#[doc = "Buffer table address"]
pub mod btable;
|
#[doc = r" Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r" Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::DLY {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct PRE_DELAYR {
bits: u8,
}
impl PRE_DELAYR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct POST_DELAYR {
bits: u8,
}
impl POST_DELAYR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct FRAME_DELAYR {
bits: u8,
}
impl FRAME_DELAYR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct TRANSFER_DELAYR {
bits: u8,
}
impl TRANSFER_DELAYR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Proxy"]
pub struct _PRE_DELAYW<'a> {
w: &'a mut W,
}
impl<'a> _PRE_DELAYW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _POST_DELAYW<'a> {
w: &'a mut W,
}
impl<'a> _POST_DELAYW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _FRAME_DELAYW<'a> {
w: &'a mut W,
}
impl<'a> _FRAME_DELAYW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 8;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _TRANSFER_DELAYW<'a> {
w: &'a mut W,
}
impl<'a> _TRANSFER_DELAYW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:3 - Controls the amount of time between SSEL assertion and the beginning of a data frame. There is always one SPI clock time between SSEL assertion and the first clock edge. This is not considered part of the pre-delay. 0x0 = No additional time is inserted. 0x1 = 1 SPI clock time is inserted. 0x2 = 2 SPI clock times are inserted. ... 0xF = 15 SPI clock times are inserted."]
#[inline]
pub fn pre_delay(&self) -> PRE_DELAYR {
let bits = {
const MASK: u8 = 15;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
PRE_DELAYR { bits }
}
#[doc = "Bits 4:7 - Controls the amount of time between the end of a data frame and SSEL deassertion. 0x0 = No additional time is inserted. 0x1 = 1 SPI clock time is inserted. 0x2 = 2 SPI clock times are inserted. ... 0xF = 15 SPI clock times are inserted."]
#[inline]
pub fn post_delay(&self) -> POST_DELAYR {
let bits = {
const MASK: u8 = 15;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) as u8
};
POST_DELAYR { bits }
}
#[doc = "Bits 8:11 - Controls the minimum amount of time between adjacent data frames. 0x0 = No additional time is inserted. 0x1 = 1 SPI clock time is inserted. 0x2 = 2 SPI clock times are inserted. ... 0xF = 15 SPI clock times are inserted."]
#[inline]
pub fn frame_delay(&self) -> FRAME_DELAYR {
let bits = {
const MASK: u8 = 15;
const OFFSET: u8 = 8;
((self.bits >> OFFSET) & MASK as u32) as u8
};
FRAME_DELAYR { bits }
}
#[doc = "Bits 12:15 - Controls the minimum amount of time that the SSELs are deasserted between transfers. 0x0 = The minimum time that SSEL is deasserted is 1 SPI clock time. (Zero added time.) 0x1 = The minimum time that SSEL is deasserted is 2 SPI clock times. 0x2 = The minimum time that SSEL is deasserted is 3 SPI clock times. ... 0xF = The minimum time that SSEL is deasserted is 16 SPI clock times."]
#[inline]
pub fn transfer_delay(&self) -> TRANSFER_DELAYR {
let bits = {
const MASK: u8 = 15;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) as u8
};
TRANSFER_DELAYR { bits }
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:3 - Controls the amount of time between SSEL assertion and the beginning of a data frame. There is always one SPI clock time between SSEL assertion and the first clock edge. This is not considered part of the pre-delay. 0x0 = No additional time is inserted. 0x1 = 1 SPI clock time is inserted. 0x2 = 2 SPI clock times are inserted. ... 0xF = 15 SPI clock times are inserted."]
#[inline]
pub fn pre_delay(&mut self) -> _PRE_DELAYW {
_PRE_DELAYW { w: self }
}
#[doc = "Bits 4:7 - Controls the amount of time between the end of a data frame and SSEL deassertion. 0x0 = No additional time is inserted. 0x1 = 1 SPI clock time is inserted. 0x2 = 2 SPI clock times are inserted. ... 0xF = 15 SPI clock times are inserted."]
#[inline]
pub fn post_delay(&mut self) -> _POST_DELAYW {
_POST_DELAYW { w: self }
}
#[doc = "Bits 8:11 - Controls the minimum amount of time between adjacent data frames. 0x0 = No additional time is inserted. 0x1 = 1 SPI clock time is inserted. 0x2 = 2 SPI clock times are inserted. ... 0xF = 15 SPI clock times are inserted."]
#[inline]
pub fn frame_delay(&mut self) -> _FRAME_DELAYW {
_FRAME_DELAYW { w: self }
}
#[doc = "Bits 12:15 - Controls the minimum amount of time that the SSELs are deasserted between transfers. 0x0 = The minimum time that SSEL is deasserted is 1 SPI clock time. (Zero added time.) 0x1 = The minimum time that SSEL is deasserted is 2 SPI clock times. 0x2 = The minimum time that SSEL is deasserted is 3 SPI clock times. ... 0xF = The minimum time that SSEL is deasserted is 16 SPI clock times."]
#[inline]
pub fn transfer_delay(&mut self) -> _TRANSFER_DELAYW {
_TRANSFER_DELAYW { w: self }
}
}
|
use super::{Dispatch, NodeId, ShardId, State};
use crate::{
NodeQueue, NodeQueueEntry, NodeThreadPool, ProbabilisticDispatcher, Query, QueryEstimate,
QueryId,
};
use std::collections::HashSet;
use std::rc::Rc;
use simrs::{Key, QueueId};
pub struct OptPlusDispatch {
node_queues: Vec<QueueId<NodeQueue<NodeQueueEntry>>>,
shards: Vec<Vec<NodeId>>,
disabled_nodes: HashSet<NodeId>,
estimates: Rc<Vec<QueryEstimate>>,
queries: Rc<Vec<Query>>,
thread_pools: Vec<Key<NodeThreadPool>>,
probabilistic: ProbabilisticDispatcher,
threshold: f32,
}
impl OptPlusDispatch {
/// Constructs a new dispatcher.
#[must_use]
pub fn new(
nodes: &[Vec<usize>],
node_queues: Vec<QueueId<NodeQueue<NodeQueueEntry>>>,
estimates: Rc<Vec<QueryEstimate>>,
queries: Rc<Vec<Query>>,
thread_pools: Vec<Key<NodeThreadPool>>,
probabilistic: ProbabilisticDispatcher,
threshold: f32,
) -> Self {
Self {
shards: super::invert_nodes_to_shards(nodes),
disabled_nodes: HashSet::new(),
node_queues,
estimates,
queries,
thread_pools,
probabilistic,
threshold,
}
}
fn query_time(&self, query_id: QueryId, shard_id: ShardId) -> u64 {
self.estimates
.get(query_id.0 - 1)
.expect("query out of bounds")
.shard_estimate(shard_id)
}
#[allow(clippy::cast_possible_wrap, clippy::cast_possible_truncation)]
fn select_node(&self, shard_id: ShardId, state: &State) -> NodeId {
*self.shards[shard_id.0]
.iter()
.filter(|n| !self.disabled_nodes.contains(n))
.min_by_key(|n| {
let running = state
.get(self.thread_pools[n.0])
.expect("unknown thread pool ID")
.running_threads()
.iter()
.map(|t| t.estimated.as_micros())
.sum::<u128>();
let waiting = state
.queue(self.node_queues[n.0])
.iter()
.map(|msg| self.query_time(msg.request.query_id(), shard_id))
.sum::<u64>();
//waiting
running as u64 + waiting
})
.unwrap()
}
fn any_over_threshold(&self, shard_id: ShardId, state: &State) -> bool {
use simrs::Queue;
let nodes = &self.shards[shard_id.0];
let all_queues_empty = !nodes
.iter()
.all(|n| state.queue(self.node_queues[n.0]).is_empty());
if !all_queues_empty {
return true;
}
nodes.iter().any(|n| {
let pool = state
.get(self.thread_pools[n.0])
.expect("unknown thread pool ID");
pool.num_active() as f32 / (pool.num_idle() + pool.num_active()) as f32 > self.threshold
})
}
}
impl Dispatch for OptPlusDispatch {
fn dispatch(&self, _: QueryId, shards: &[ShardId], state: &State) -> Vec<(ShardId, NodeId)> {
shards
.iter()
.map(|&shard_id| {
if self.any_over_threshold(shard_id, &state) {
(shard_id, self.select_node(shard_id, &state))
} else {
(shard_id, self.probabilistic.select_node(shard_id))
}
})
.collect()
}
fn num_shards(&self) -> usize {
self.shards.len()
}
fn num_nodes(&self) -> usize {
self.node_queues.len()
}
fn disable_node(&mut self, node_id: NodeId) -> eyre::Result<bool> {
Ok(self.disabled_nodes.insert(node_id))
}
fn enable_node(&mut self, node_id: NodeId) -> bool {
self.disabled_nodes.remove(&node_id)
}
}
|
use std::fs::File;
use std::io::prelude::*;
fn main() {
println!("Hello!");
// Read a file
let mut fp = File::open("ip.txt").expect("File not found!");
let mut contents = String::new();
fp.read_to_string(&mut contents)
.expect("something went wrong reading the file");
println!("{}", contents);
}
|
use crate::util::{self, color};
use crate::{config, git};
use anyhow::Result;
use std::cmp::max;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
use std::{env, fs};
use walkdir::WalkDir;
/// Represents which direction to sync dotfiles.
#[derive(PartialEq)]
enum SyncDirection {
FromRemote,
ToRemote,
NoDiff,
}
/// Synchronizes the remote and local dotfiles.
///
/// If two files are the same, then no copying occurs. Otherwise, the newer file
/// remains and is copied onto the other. The timestamp of a file depends on whether
/// it is a local file or a remote file. Remote files have their timestamps determined
/// by the time of the most recent commit which modifies them. Local files' timestamps
/// are determined by the filesystem.
pub fn sync() -> Result<()> {
use SyncDirection::*;
for (remote, local) in config::get_config()?.dests().iter() {
let files = remote_and_local_files(&remote, &local)?;
let direction = sync_direction(&files);
if direction == NoDiff {
continue;
}
for (remote_file, local_file) in files.iter() {
let arrow_str = if direction == FromRemote {
if !local_file
.parent()
.expect(&format!("Local path has no parent {:?}", local_file))
.is_dir()
{
fs::create_dir_all(local_file.parent().unwrap())?
}
fs::copy(remote_file, local_file)?;
"->"
} else {
fs::copy(local_file, remote_file)?;
"<-"
};
util::info(format!(
"sync {} {} {}",
color::path(remote_file),
arrow_str,
color::path(local_file)
));
}
}
git::commit(&env::args().collect::<Vec<String>>()[1..].join(" "))?;
Ok(())
}
/// Returns the pairs of corresponding files under a tracked file or directory.
///
/// # Arguments
///
/// * `remote` - A key from `Config::dest`.
/// * `local` - The corresponding value to the key `remote`.
pub fn remote_and_local_files<P: AsRef<Path>, Q: AsRef<Path>>(
remote: P,
local: Q,
) -> Result<Vec<(PathBuf, PathBuf)>> {
let remote = remote.as_ref();
let local = local.as_ref();
let tittle_config_dir = config::tittle_config_dir();
let remote = &tittle_config_dir.join(remote);
if remote.is_file() {
return Ok(vec![(remote.to_path_buf(), local.to_path_buf())]);
}
let mut vec = Vec::new();
for remote_file in WalkDir::new(remote).into_iter() {
let remote_file = remote_file?;
let remote_file = remote_file.path();
if remote_file.is_dir() {
continue;
}
let local_file = local.join(remote_file.strip_prefix(&remote)?);
vec.push((remote_file.to_path_buf(), local_file.to_path_buf()));
}
return Ok(vec);
}
/// Returns a file's timestamp in seconds. If the file does not exist then return 0.
fn file_timestamp<P: AsRef<Path>>(path: P) -> u64 {
if !path.as_ref().exists() {
return 0;
}
fs::metadata(path)
.unwrap()
.modified()
.unwrap()
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap()
.as_secs()
}
/// Returns which direction to sync this sequence of `(remote, local)` files.
///
/// This function assumes that this is an return value of `remote_and_local_files`.
/// If no diffs occur between the pairs of files in `files`, then `NoDiff` will be
/// returned. If the remote files contain the newest file, then `FromRemote`
/// is returned. Otherwise, `ToRemote` is returned.
fn sync_direction<P: AsRef<Path>, Q: AsRef<Path>>(files: &[(P, Q)]) -> SyncDirection {
use SyncDirection::*;
let (remote_time, local_time, diff) = files
.iter()
.map(|(remote_f, local_f)| {
(
git::timestamp(remote_f).unwrap(),
file_timestamp(local_f),
util::diff(remote_f, local_f).unwrap(),
)
})
.fold(
(0, 0, false),
|(r_acc, l_acc, d_acc), (r_time, l_time, diff)| {
(
max(r_acc, r_time),
max(l_acc, l_time),
d_acc | (None != diff),
)
},
);
if !diff {
NoDiff
} else if remote_time > local_time {
FromRemote
} else {
ToRemote
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::FIFOLVL {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = "Possible values of the field `EPI_FIFOLVL_RDFIFO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_FIFOLVL_RDFIFOR {
#[doc = "Trigger when there are 1 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_1,
#[doc = "Trigger when there are 2 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_2,
#[doc = "Trigger when there are 4 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_4,
#[doc = "Trigger when there are 6 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_6,
#[doc = "Trigger when there are 7 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_7,
#[doc = "Trigger when there are 8 entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_8,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl EPI_FIFOLVL_RDFIFOR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_1 => 1,
EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_2 => 2,
EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_4 => 3,
EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_6 => 4,
EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_7 => 5,
EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_8 => 6,
EPI_FIFOLVL_RDFIFOR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> EPI_FIFOLVL_RDFIFOR {
match value {
1 => EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_1,
2 => EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_2,
3 => EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_4,
4 => EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_6,
5 => EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_7,
6 => EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_8,
i => EPI_FIFOLVL_RDFIFOR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_RDFIFO_1`"]
#[inline(always)]
pub fn is_epi_fifolvl_rdfifo_1(&self) -> bool {
*self == EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_1
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_RDFIFO_2`"]
#[inline(always)]
pub fn is_epi_fifolvl_rdfifo_2(&self) -> bool {
*self == EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_2
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_RDFIFO_4`"]
#[inline(always)]
pub fn is_epi_fifolvl_rdfifo_4(&self) -> bool {
*self == EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_4
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_RDFIFO_6`"]
#[inline(always)]
pub fn is_epi_fifolvl_rdfifo_6(&self) -> bool {
*self == EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_6
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_RDFIFO_7`"]
#[inline(always)]
pub fn is_epi_fifolvl_rdfifo_7(&self) -> bool {
*self == EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_7
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_RDFIFO_8`"]
#[inline(always)]
pub fn is_epi_fifolvl_rdfifo_8(&self) -> bool {
*self == EPI_FIFOLVL_RDFIFOR::EPI_FIFOLVL_RDFIFO_8
}
}
#[doc = "Values that can be written to the field `EPI_FIFOLVL_RDFIFO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_FIFOLVL_RDFIFOW {
#[doc = "Trigger when there are 1 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_1,
#[doc = "Trigger when there are 2 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_2,
#[doc = "Trigger when there are 4 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_4,
#[doc = "Trigger when there are 6 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_6,
#[doc = "Trigger when there are 7 or more entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_7,
#[doc = "Trigger when there are 8 entries in the NBRFIFO"]
EPI_FIFOLVL_RDFIFO_8,
}
impl EPI_FIFOLVL_RDFIFOW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_1 => 1,
EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_2 => 2,
EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_4 => 3,
EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_6 => 4,
EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_7 => 5,
EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_8 => 6,
}
}
}
#[doc = r"Proxy"]
pub struct _EPI_FIFOLVL_RDFIFOW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_FIFOLVL_RDFIFOW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EPI_FIFOLVL_RDFIFOW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Trigger when there are 1 or more entries in the NBRFIFO"]
#[inline(always)]
pub fn epi_fifolvl_rdfifo_1(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_1)
}
#[doc = "Trigger when there are 2 or more entries in the NBRFIFO"]
#[inline(always)]
pub fn epi_fifolvl_rdfifo_2(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_2)
}
#[doc = "Trigger when there are 4 or more entries in the NBRFIFO"]
#[inline(always)]
pub fn epi_fifolvl_rdfifo_4(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_4)
}
#[doc = "Trigger when there are 6 or more entries in the NBRFIFO"]
#[inline(always)]
pub fn epi_fifolvl_rdfifo_6(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_6)
}
#[doc = "Trigger when there are 7 or more entries in the NBRFIFO"]
#[inline(always)]
pub fn epi_fifolvl_rdfifo_7(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_7)
}
#[doc = "Trigger when there are 8 entries in the NBRFIFO"]
#[inline(always)]
pub fn epi_fifolvl_rdfifo_8(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_RDFIFOW::EPI_FIFOLVL_RDFIFO_8)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(7 << 0);
self.w.bits |= ((value as u32) & 7) << 0;
self.w
}
}
#[doc = "Possible values of the field `EPI_FIFOLVL_WRFIFO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_FIFOLVL_WRFIFOR {
#[doc = "Interrupt is triggered while WRFIFO is empty."]
EPI_FIFOLVL_WRFIFO_EMPT,
#[doc = "Interrupt is triggered until there are only two slots available. Thus, trigger is deasserted when there are two WRFIFO entries present. This configuration is optimized for bursts of 2"]
EPI_FIFOLVL_WRFIFO_2,
#[doc = "Interrupt is triggered until there is one WRFIFO entry available. This configuration expects only single writes"]
EPI_FIFOLVL_WRFIFO_1,
#[doc = "Trigger interrupt when WRFIFO is not full, meaning trigger will continue to assert until there are four entries in the WRFIFO"]
EPI_FIFOLVL_WRFIFO_NFULL,
#[doc = r"Reserved"]
_Reserved(u8),
}
impl EPI_FIFOLVL_WRFIFOR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_EMPT => 0,
EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_2 => 2,
EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_1 => 3,
EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_NFULL => 4,
EPI_FIFOLVL_WRFIFOR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> EPI_FIFOLVL_WRFIFOR {
match value {
0 => EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_EMPT,
2 => EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_2,
3 => EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_1,
4 => EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_NFULL,
i => EPI_FIFOLVL_WRFIFOR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_WRFIFO_EMPT`"]
#[inline(always)]
pub fn is_epi_fifolvl_wrfifo_empt(&self) -> bool {
*self == EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_EMPT
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_WRFIFO_2`"]
#[inline(always)]
pub fn is_epi_fifolvl_wrfifo_2(&self) -> bool {
*self == EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_2
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_WRFIFO_1`"]
#[inline(always)]
pub fn is_epi_fifolvl_wrfifo_1(&self) -> bool {
*self == EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_1
}
#[doc = "Checks if the value of the field is `EPI_FIFOLVL_WRFIFO_NFULL`"]
#[inline(always)]
pub fn is_epi_fifolvl_wrfifo_nfull(&self) -> bool {
*self == EPI_FIFOLVL_WRFIFOR::EPI_FIFOLVL_WRFIFO_NFULL
}
}
#[doc = "Values that can be written to the field `EPI_FIFOLVL_WRFIFO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum EPI_FIFOLVL_WRFIFOW {
#[doc = "Interrupt is triggered while WRFIFO is empty."]
EPI_FIFOLVL_WRFIFO_EMPT,
#[doc = "Interrupt is triggered until there are only two slots available. Thus, trigger is deasserted when there are two WRFIFO entries present. This configuration is optimized for bursts of 2"]
EPI_FIFOLVL_WRFIFO_2,
#[doc = "Interrupt is triggered until there is one WRFIFO entry available. This configuration expects only single writes"]
EPI_FIFOLVL_WRFIFO_1,
#[doc = "Trigger interrupt when WRFIFO is not full, meaning trigger will continue to assert until there are four entries in the WRFIFO"]
EPI_FIFOLVL_WRFIFO_NFULL,
}
impl EPI_FIFOLVL_WRFIFOW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
EPI_FIFOLVL_WRFIFOW::EPI_FIFOLVL_WRFIFO_EMPT => 0,
EPI_FIFOLVL_WRFIFOW::EPI_FIFOLVL_WRFIFO_2 => 2,
EPI_FIFOLVL_WRFIFOW::EPI_FIFOLVL_WRFIFO_1 => 3,
EPI_FIFOLVL_WRFIFOW::EPI_FIFOLVL_WRFIFO_NFULL => 4,
}
}
}
#[doc = r"Proxy"]
pub struct _EPI_FIFOLVL_WRFIFOW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_FIFOLVL_WRFIFOW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: EPI_FIFOLVL_WRFIFOW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Interrupt is triggered while WRFIFO is empty."]
#[inline(always)]
pub fn epi_fifolvl_wrfifo_empt(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_WRFIFOW::EPI_FIFOLVL_WRFIFO_EMPT)
}
#[doc = "Interrupt is triggered until there are only two slots available. Thus, trigger is deasserted when there are two WRFIFO entries present. This configuration is optimized for bursts of 2"]
#[inline(always)]
pub fn epi_fifolvl_wrfifo_2(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_WRFIFOW::EPI_FIFOLVL_WRFIFO_2)
}
#[doc = "Interrupt is triggered until there is one WRFIFO entry available. This configuration expects only single writes"]
#[inline(always)]
pub fn epi_fifolvl_wrfifo_1(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_WRFIFOW::EPI_FIFOLVL_WRFIFO_1)
}
#[doc = "Trigger interrupt when WRFIFO is not full, meaning trigger will continue to assert until there are four entries in the WRFIFO"]
#[inline(always)]
pub fn epi_fifolvl_wrfifo_nfull(self) -> &'a mut W {
self.variant(EPI_FIFOLVL_WRFIFOW::EPI_FIFOLVL_WRFIFO_NFULL)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(7 << 4);
self.w.bits |= ((value as u32) & 7) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_FIFOLVL_RSERRR {
bits: bool,
}
impl EPI_FIFOLVL_RSERRR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_FIFOLVL_RSERRW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_FIFOLVL_RSERRW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 16);
self.w.bits |= ((value as u32) & 1) << 16;
self.w
}
}
#[doc = r"Value of the field"]
pub struct EPI_FIFOLVL_WFERRR {
bits: bool,
}
impl EPI_FIFOLVL_WFERRR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _EPI_FIFOLVL_WFERRW<'a> {
w: &'a mut W,
}
impl<'a> _EPI_FIFOLVL_WFERRW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 17);
self.w.bits |= ((value as u32) & 1) << 17;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:2 - Read FIFO"]
#[inline(always)]
pub fn epi_fifolvl_rdfifo(&self) -> EPI_FIFOLVL_RDFIFOR {
EPI_FIFOLVL_RDFIFOR::_from(((self.bits >> 0) & 7) as u8)
}
#[doc = "Bits 4:6 - Write FIFO"]
#[inline(always)]
pub fn epi_fifolvl_wrfifo(&self) -> EPI_FIFOLVL_WRFIFOR {
EPI_FIFOLVL_WRFIFOR::_from(((self.bits >> 4) & 7) as u8)
}
#[doc = "Bit 16 - Read Stall Error"]
#[inline(always)]
pub fn epi_fifolvl_rserr(&self) -> EPI_FIFOLVL_RSERRR {
let bits = ((self.bits >> 16) & 1) != 0;
EPI_FIFOLVL_RSERRR { bits }
}
#[doc = "Bit 17 - Write Full Error"]
#[inline(always)]
pub fn epi_fifolvl_wferr(&self) -> EPI_FIFOLVL_WFERRR {
let bits = ((self.bits >> 17) & 1) != 0;
EPI_FIFOLVL_WFERRR { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:2 - Read FIFO"]
#[inline(always)]
pub fn epi_fifolvl_rdfifo(&mut self) -> _EPI_FIFOLVL_RDFIFOW {
_EPI_FIFOLVL_RDFIFOW { w: self }
}
#[doc = "Bits 4:6 - Write FIFO"]
#[inline(always)]
pub fn epi_fifolvl_wrfifo(&mut self) -> _EPI_FIFOLVL_WRFIFOW {
_EPI_FIFOLVL_WRFIFOW { w: self }
}
#[doc = "Bit 16 - Read Stall Error"]
#[inline(always)]
pub fn epi_fifolvl_rserr(&mut self) -> _EPI_FIFOLVL_RSERRW {
_EPI_FIFOLVL_RSERRW { w: self }
}
#[doc = "Bit 17 - Write Full Error"]
#[inline(always)]
pub fn epi_fifolvl_wferr(&mut self) -> _EPI_FIFOLVL_WFERRW {
_EPI_FIFOLVL_WFERRW { w: self }
}
}
|
const width:usize = 25;
const height:usize = 6;
fn main() {
let input: &str = include_str!("./input.txt").lines().next().unwrap();
let data: Vec<isize> = input.chars().map(|x| x.to_digit(10).unwrap() as isize).collect();
let mut layer = 0;
let total_layers = data.len() / width / height;
let mut layers: Vec<&[isize]> = vec![];
let mut least_zeros = 99999999;
let mut zero_layer = 0;
let mut final_layer: Vec<isize> = vec![2; width * height];
for layer in 0..total_layers {
let start = layer * height * width;
let end = start + (height * width);
let slice = &data[start..end];
layers.push(slice);
let zero_count: usize = slice.iter().filter(|&x| *x == 0).collect::<Vec<&isize>>().len();
if zero_count <= least_zeros {
least_zeros = zero_count;
zero_layer = layer;
}
}
for (c, layer) in layers.iter().rev().enumerate() {
for (i, &pixel) in layer.iter().enumerate() {
if pixel < 2 {
final_layer[i] = pixel;
}
}
}
let total_ones = layers[zero_layer].iter().filter(|&x| *x == 1).collect::<Vec<&isize>>().len();
let total_twos = layers[zero_layer].iter().filter(|&x| *x == 2).collect::<Vec<&isize>>().len();
println!("1: {} 2: {} Total: {}", total_ones, total_twos, total_twos * total_ones);
}
fn print_layer(final_layer: &Vec<isize>) {
let items: Vec<char> = final_layer.iter().map(|&x| {
return match x {
0 => ' ',
1 => 'X',
_ => ' '
}
}).collect();
for i in 0..height {
let start = width * i;
let end = start + width;
println!("{}", &items[start..end].iter().collect::<String>());
}
}
|
//! libc syscalls supporting `rustix::io`.
use crate::backend::c;
#[cfg(not(target_os = "wasi"))]
use crate::backend::conv::ret_discarded_fd;
use crate::backend::conv::{borrowed_fd, ret, ret_c_int, ret_owned_fd, ret_usize};
use crate::fd::{AsFd, BorrowedFd, OwnedFd, RawFd};
#[cfg(not(any(
target_os = "aix",
target_os = "espidf",
target_os = "nto",
target_os = "wasi"
)))]
use crate::io::DupFlags;
#[cfg(linux_kernel)]
use crate::io::ReadWriteFlags;
use crate::io::{self, FdFlags};
use core::cmp::min;
#[cfg(all(feature = "fs", feature = "net"))]
use libc_errno::errno;
#[cfg(not(target_os = "espidf"))]
use {
crate::backend::MAX_IOV,
crate::io::{IoSlice, IoSliceMut},
};
pub(crate) fn read(fd: BorrowedFd<'_>, buf: &mut [u8]) -> io::Result<usize> {
unsafe {
ret_usize(c::read(
borrowed_fd(fd),
buf.as_mut_ptr().cast(),
min(buf.len(), READ_LIMIT),
))
}
}
pub(crate) fn write(fd: BorrowedFd<'_>, buf: &[u8]) -> io::Result<usize> {
unsafe {
ret_usize(c::write(
borrowed_fd(fd),
buf.as_ptr().cast(),
min(buf.len(), READ_LIMIT),
))
}
}
pub(crate) fn pread(fd: BorrowedFd<'_>, buf: &mut [u8], offset: u64) -> io::Result<usize> {
let len = min(buf.len(), READ_LIMIT);
// Silently cast; we'll get `EINVAL` if the value is negative.
let offset = offset as i64;
// ESP-IDF doesn't support 64-bit offsets.
#[cfg(target_os = "espidf")]
let offset: i32 = offset.try_into().map_err(|_| io::Errno::OVERFLOW)?;
unsafe {
ret_usize(c::pread(
borrowed_fd(fd),
buf.as_mut_ptr().cast(),
len,
offset,
))
}
}
pub(crate) fn pwrite(fd: BorrowedFd<'_>, buf: &[u8], offset: u64) -> io::Result<usize> {
let len = min(buf.len(), READ_LIMIT);
// Silently cast; we'll get `EINVAL` if the value is negative.
let offset = offset as i64;
// ESP-IDF doesn't support 64-bit offsets.
#[cfg(target_os = "espidf")]
let offset: i32 = offset.try_into().map_err(|_| io::Errno::OVERFLOW)?;
unsafe { ret_usize(c::pwrite(borrowed_fd(fd), buf.as_ptr().cast(), len, offset)) }
}
#[cfg(not(target_os = "espidf"))]
pub(crate) fn readv(fd: BorrowedFd<'_>, bufs: &mut [IoSliceMut]) -> io::Result<usize> {
unsafe {
ret_usize(c::readv(
borrowed_fd(fd),
bufs.as_ptr().cast::<c::iovec>(),
min(bufs.len(), MAX_IOV) as c::c_int,
))
}
}
#[cfg(not(target_os = "espidf"))]
pub(crate) fn writev(fd: BorrowedFd<'_>, bufs: &[IoSlice]) -> io::Result<usize> {
unsafe {
ret_usize(c::writev(
borrowed_fd(fd),
bufs.as_ptr().cast::<c::iovec>(),
min(bufs.len(), MAX_IOV) as c::c_int,
))
}
}
#[cfg(not(any(
target_os = "espidf",
target_os = "haiku",
target_os = "nto",
target_os = "redox",
target_os = "solaris"
)))]
pub(crate) fn preadv(
fd: BorrowedFd<'_>,
bufs: &mut [IoSliceMut],
offset: u64,
) -> io::Result<usize> {
// Silently cast; we'll get `EINVAL` if the value is negative.
let offset = offset as i64;
unsafe {
ret_usize(c::preadv(
borrowed_fd(fd),
bufs.as_ptr().cast::<c::iovec>(),
min(bufs.len(), MAX_IOV) as c::c_int,
offset,
))
}
}
#[cfg(not(any(
target_os = "espidf",
target_os = "haiku",
target_os = "nto",
target_os = "redox",
target_os = "solaris"
)))]
pub(crate) fn pwritev(fd: BorrowedFd<'_>, bufs: &[IoSlice], offset: u64) -> io::Result<usize> {
// Silently cast; we'll get `EINVAL` if the value is negative.
let offset = offset as i64;
unsafe {
ret_usize(c::pwritev(
borrowed_fd(fd),
bufs.as_ptr().cast::<c::iovec>(),
min(bufs.len(), MAX_IOV) as c::c_int,
offset,
))
}
}
#[cfg(linux_kernel)]
pub(crate) fn preadv2(
fd: BorrowedFd<'_>,
bufs: &mut [IoSliceMut],
offset: u64,
flags: ReadWriteFlags,
) -> io::Result<usize> {
// Silently cast; we'll get `EINVAL` if the value is negative.
let offset = offset as i64;
unsafe {
ret_usize(c::preadv2(
borrowed_fd(fd),
bufs.as_ptr().cast::<c::iovec>(),
min(bufs.len(), MAX_IOV) as c::c_int,
offset,
bitflags_bits!(flags),
))
}
}
#[cfg(linux_kernel)]
pub(crate) fn pwritev2(
fd: BorrowedFd<'_>,
bufs: &[IoSlice],
offset: u64,
flags: ReadWriteFlags,
) -> io::Result<usize> {
// Silently cast; we'll get `EINVAL` if the value is negative.
let offset = offset as i64;
unsafe {
ret_usize(c::pwritev2(
borrowed_fd(fd),
bufs.as_ptr().cast::<c::iovec>(),
min(bufs.len(), MAX_IOV) as c::c_int,
offset,
bitflags_bits!(flags),
))
}
}
// These functions are derived from Rust's library/std/src/sys/unix/fd.rs at
// revision 326ef470a8b379a180d6dc4bbef08990698a737a.
// The maximum read limit on most POSIX-like systems is `SSIZE_MAX`, with the
// manual page quoting that if the count of bytes to read is greater than
// `SSIZE_MAX` the result is “unspecified”.
//
// On macOS, however, apparently the 64-bit libc is either buggy or
// intentionally showing odd behavior by rejecting any read with a size larger
// than or equal to `INT_MAX`. To handle both of these the read size is capped
// on both platforms.
#[cfg(target_os = "macos")]
const READ_LIMIT: usize = c::c_int::MAX as usize - 1;
#[cfg(not(target_os = "macos"))]
const READ_LIMIT: usize = c::ssize_t::MAX as usize;
pub(crate) unsafe fn close(raw_fd: RawFd) {
let _ = c::close(raw_fd as c::c_int);
}
#[cfg(not(target_os = "espidf"))]
pub(crate) fn ioctl_fionread(fd: BorrowedFd<'_>) -> io::Result<u64> {
use core::mem::MaybeUninit;
let mut nread = MaybeUninit::<c::c_int>::uninit();
unsafe {
ret(c::ioctl(borrowed_fd(fd), c::FIONREAD, nread.as_mut_ptr()))?;
// `FIONREAD` returns the number of bytes silently casted to a `c_int`,
// even when this is lossy. The best we can do is convert it back to a
// `u64` without sign-extending it back first.
Ok(u64::from(nread.assume_init() as c::c_uint))
}
}
pub(crate) fn ioctl_fionbio(fd: BorrowedFd<'_>, value: bool) -> io::Result<()> {
unsafe {
let data = value as c::c_int;
ret(c::ioctl(borrowed_fd(fd), c::FIONBIO, &data))
}
}
#[cfg(not(any(target_os = "redox", target_os = "wasi")))]
#[cfg(all(feature = "fs", feature = "net"))]
pub(crate) fn is_read_write(fd: BorrowedFd<'_>) -> io::Result<(bool, bool)> {
use core::mem::MaybeUninit;
let (mut read, mut write) = crate::fs::fd::_is_file_read_write(fd)?;
let mut not_socket = false;
if read {
// Do a `recv` with `PEEK` and `DONTWAIT` for 1 byte. A 0 indicates
// the read side is shut down; an `EWOULDBLOCK` indicates the read
// side is still open.
match unsafe {
c::recv(
borrowed_fd(fd),
MaybeUninit::<[u8; 1]>::uninit()
.as_mut_ptr()
.cast::<c::c_void>(),
1,
c::MSG_PEEK | c::MSG_DONTWAIT,
)
} {
0 => read = false,
-1 => {
#[allow(unreachable_patterns)] // `EAGAIN` may equal `EWOULDBLOCK`
match errno().0 {
c::EAGAIN | c::EWOULDBLOCK => (),
c::ENOTSOCK => not_socket = true,
err => return Err(io::Errno(err)),
}
}
_ => (),
}
}
if write && !not_socket {
// Do a `send` with `DONTWAIT` for 0 bytes. An `EPIPE` indicates
// the write side is shut down.
if unsafe { c::send(borrowed_fd(fd), [].as_ptr(), 0, c::MSG_DONTWAIT) } == -1 {
#[allow(unreachable_patterns)] // `EAGAIN` may equal `EWOULDBLOCK`
match errno().0 {
c::EAGAIN | c::EWOULDBLOCK | c::ENOTSOCK => (),
c::EPIPE => write = false,
err => return Err(io::Errno(err)),
}
}
}
Ok((read, write))
}
#[cfg(target_os = "wasi")]
#[cfg(all(feature = "fs", feature = "net"))]
pub(crate) fn is_read_write(_fd: BorrowedFd<'_>) -> io::Result<(bool, bool)> {
todo!("Implement is_read_write for WASI in terms of fd_fdstat_get");
}
pub(crate) fn fcntl_getfd(fd: BorrowedFd<'_>) -> io::Result<FdFlags> {
let flags = unsafe { ret_c_int(c::fcntl(borrowed_fd(fd), c::F_GETFD))? };
Ok(FdFlags::from_bits_retain(bitcast!(flags)))
}
pub(crate) fn fcntl_setfd(fd: BorrowedFd<'_>, flags: FdFlags) -> io::Result<()> {
unsafe { ret(c::fcntl(borrowed_fd(fd), c::F_SETFD, flags.bits())) }
}
#[cfg(not(any(target_os = "espidf", target_os = "wasi")))]
pub(crate) fn fcntl_dupfd_cloexec(fd: BorrowedFd<'_>, min: RawFd) -> io::Result<OwnedFd> {
unsafe { ret_owned_fd(c::fcntl(borrowed_fd(fd), c::F_DUPFD_CLOEXEC, min)) }
}
#[cfg(target_os = "espidf")]
pub(crate) fn fcntl_dupfd(fd: BorrowedFd<'_>, min: RawFd) -> io::Result<OwnedFd> {
unsafe { ret_owned_fd(c::fcntl(borrowed_fd(fd), c::F_DUPFD, min)) }
}
#[cfg(not(target_os = "wasi"))]
pub(crate) fn dup(fd: BorrowedFd<'_>) -> io::Result<OwnedFd> {
unsafe { ret_owned_fd(c::dup(borrowed_fd(fd))) }
}
#[cfg(not(target_os = "wasi"))]
pub(crate) fn dup2(fd: BorrowedFd<'_>, new: &mut OwnedFd) -> io::Result<()> {
unsafe { ret_discarded_fd(c::dup2(borrowed_fd(fd), borrowed_fd(new.as_fd()))) }
}
#[cfg(not(any(
apple,
target_os = "aix",
target_os = "android",
target_os = "dragonfly",
target_os = "espidf",
target_os = "haiku",
target_os = "nto",
target_os = "redox",
target_os = "wasi",
)))]
pub(crate) fn dup3(fd: BorrowedFd<'_>, new: &mut OwnedFd, flags: DupFlags) -> io::Result<()> {
unsafe {
ret_discarded_fd(c::dup3(
borrowed_fd(fd),
borrowed_fd(new.as_fd()),
bitflags_bits!(flags),
))
}
}
#[cfg(any(
apple,
target_os = "android",
target_os = "dragonfly",
target_os = "haiku",
target_os = "redox",
))]
pub(crate) fn dup3(fd: BorrowedFd<'_>, new: &mut OwnedFd, _flags: DupFlags) -> io::Result<()> {
// Android 5.0 has `dup3`, but libc doesn't have bindings. Emulate it
// using `dup2`. We don't need to worry about the difference between
// `dup2` and `dup3` when the file descriptors are equal because we
// have an `&mut OwnedFd` which means `fd` doesn't alias it.
dup2(fd, new)
}
#[cfg(apple)]
pub(crate) fn ioctl_fioclex(fd: BorrowedFd<'_>) -> io::Result<()> {
unsafe {
ret(c::ioctl(
borrowed_fd(fd),
c::FIOCLEX,
core::ptr::null_mut::<u8>(),
))
}
}
|
use crate::{DocBase, VarType};
const TR_ARGU: &'static str = r#"
**handle_na (bool)** How NaN values are handled. if true, and previous day's close is NaN then tr would be calculated as current day high-low. Otherwise (if false) tr would return NaN in such cases. Also note, that atr uses tr(true).
"#;
pub fn gen_doc() -> Vec<DocBase> {
vec![
DocBase {
var_type: VarType::Variable,
name: "tr",
signatures: vec![],
description: "True range. Same as `tr(false)`. It is `max(high - low, abs(high - close[1]), abs(low - close[1]))`",
example: "",
returns: "",
arguments: "",
remarks: "",
links: "[tr](#fun-tr) [atr](#var-atr)",
},
DocBase {
var_type: VarType::Function,
name: "tr",
signatures: vec![],
description: "",
example: "",
returns: "True range. It is `max(high - low, abs(high - close[1]), abs(low - close[1]))`",
arguments: TR_ARGU,
remarks: "tr(false) is exactly the same as [tr](#var-tr).",
links: "[tr](#var-tr) [atr](#var-atr)",
},
]
}
|
use serde::{Serialize, Deserialize};
use tokio_pg_mapper_derive::PostgresMapper;
use crate::common::errors::CustomError;
use deadpool_postgres::Pool;
use deadpool_postgres::Client;
use actix_web::{web};
use tokio_pg_mapper::FromTokioPostgresRow;
#[derive(Serialize, Deserialize, PostgresMapper)]
#[pg_mapper(table="eshop_product")]
pub struct Product {
pub id: i32,
pub title: String,
pub message: String,
pub stock: i32,
}
#[derive(Serialize, Deserialize)]
pub struct NewProduct {
pub title: String,
pub message: String,
pub stock: i32,
}
pub async fn find(pool: &web::Data<Pool>) -> Result<Vec<Product>, CustomError> {
let client: Client = pool.get().await.map_err(CustomError::PoolError)?;
let statement = client.prepare("select * from eshop_product").await.unwrap();
let products = client.query(&statement, &[])
.await
.expect("Error getting product list")
.iter()
.map(|row| Product::from_row_ref(row).unwrap())
.collect::<Vec<Product>>();
return Ok(products);
}
/// add product.
/// if successful, it return product have added.
pub async fn add(product_data: Product, pool: &web::Data<Pool>) -> Result<Product, CustomError> {
let client: Client = pool.get().await.map_err(CustomError::PoolError)?;
let statement = client.prepare("
INSERT INTO eshop_product(title, message, stock)
VALUES ($1, $2, $3)
RETURNING *;
").await.unwrap();
client.query(
&statement,
&[
&product_data.title,
&product_data.message,
&product_data.stock,
])
.await?
.iter()
.map(|row| Product::from_row_ref(row).unwrap())
.collect::<Vec<Product>>()
.pop()
.ok_or(CustomError::NotFound)
}
pub async fn update(product_data: Product, pool: &web::Data<Pool>) -> Result<Product, CustomError> {
let client: Client = pool.get().await.map_err(CustomError::PoolError)?;
let statement = client.prepare("\
UPDATE eshop_product
SET title = $2,
message = $3,
stock = $4
WHERE id = $1;
").await.unwrap();
let pro = client.query(
&statement,
&[
&product_data.id,
&product_data.title,
&product_data.message,
&product_data.stock,
])
.await?
.iter()
.map(|row| Product::from_row_ref(row).unwrap())
.collect::<Vec<Product>>()
.pop()
.ok_or(CustomError::NotFound)?;
Ok(pro)
}
/// delete product.
/// it delete product and return successful.
/// if product_id not found is still return successful.
pub async fn delete(product_id: u32, pool: &web::Data<Pool>) -> Result<(), CustomError> {
let client: Client = pool.get().await.map_err(CustomError::PoolError)?;
let statement = client.prepare("
DELETE FROM eshop_product
WHERE id = $1
").await.unwrap();
client.query(&statement, &[&product_id]).await?;
Ok(())
} |
use std::collections::{HashMap, HashSet};
use std::env;
use std::fs;
use std::io;
use std::io::{BufRead, Read, Write};
use std::path;
use std::path::PathBuf;
use std::process;
use std::sync::mpsc;
use std::thread;
use reqwest;
use tempfile;
use regex;
use tokio;
use crate::bc::pubapi::{JavaClass, JavaField, JavaMethod};
use crate::sconst::StringConstants;
use lazy_static::lazy_static;
use std::process::Stdio;
const JAVA_CLASS_LIST_URL: &'static str = "https://docs.oracle.com/en/java/javase/11/docs/api/allclasses.html";
lazy_static! {
static ref JAVA_CLASS_LIST: HashSet<String> = load_java_class_name_set();
}
fn load_java_class_name_set() -> HashSet<String> {
let mut runtime = tokio::runtime::Runtime::new()
.expect("Could not initialize tokio runtime.");
let result = runtime.block_on(load_java_classes(JAVA_CLASS_LIST_URL));
let hash_set: HashSet<String>;
match result {
Ok(result) => {
hash_set = result;
}
Err(e) => {
panic!("Error: {:#?}", e);
}
}
hash_set
}
async fn load_java_classes(url: &str) -> Result<HashSet<String>, Box<dyn std::error::Error>> {
println!("Loading java class list from {}", url);
let package_pattern = "(?P<package>([a-zA-Z_0-9]+)([.][a-zA-Z_0-9]+)+)";
let class_name_pattern = "(?P<class>([a-zA-Z_0-9]+)([/]([a-zA-Z_0-9]+))+)";
let re = regex::Regex::new(&format!(
"href=\"{}/{}[.]html\"",
package_pattern,
class_name_pattern))?;
let body = reqwest::get(url)
.await?
.text()
.await?;
let mut set = HashSet::new();
for cap in re.captures_iter(&body) {
let package = cap.name("package");
if package.is_none() {
continue;
}
let class = cap.name("class");
if class.is_none() {
continue;
}
let class = class.unwrap();
let class = class.as_str();
set.insert(class.to_string());
}
if set.len() == 0 {
return Err(Box::new(io::Error::new(io::ErrorKind::Other, "Found no classes.")));
}
println!("Loaded {} classes names for java standard library.", &set.len());
Ok(set)
}
pub struct JavaStdLib {
loaded_classes: HashMap<String, JavaClass>,
request_sender: mpsc::Sender<String>,
response_receiver: mpsc::Receiver<Option<ClassData>>,
java_class_list: &'static HashSet<String>,
}
impl JavaStdLib {
pub fn new() -> io::Result<Self> {
let workdir = tempfile::tempdir()?;
Self::write_java_code(&workdir.path())?;
Self::compile_java_code(&workdir.path())?;
let (send, receive) = Self::run_java_inspector(&workdir.path())?;
Ok(Self {
loaded_classes: HashMap::new(),
request_sender: send,
response_receiver: receive,
java_class_list: &JAVA_CLASS_LIST,
})
}
pub fn is_standard_library_class(class_name: &str) -> bool {
return JAVA_CLASS_LIST.contains(class_name);
}
pub fn get_all_java_class_names(&self) -> Vec<String> {
self.java_class_list.iter().map(|s| s.to_string()).collect()
}
pub fn get_classes(&self) -> Vec<JavaClass> {
let mut results = vec![];
for value in self.loaded_classes.values() {
results.push(value.clone());
}
return results;
}
pub fn get(&mut self, class_name: &str, constants: &mut StringConstants) -> Option<&JavaClass> {
if self.loaded_classes.contains_key(class_name) {
return self.loaded_classes.get(class_name);
}
if let Some(java_class) = self.load(class_name, constants) {
self.loaded_classes
.insert(class_name.to_string(), java_class);
return self.loaded_classes.get(class_name);
}
None
}
fn load(&mut self, class_name: &str, constants: &mut StringConstants) -> Option<JavaClass> {
self.request_sender.send(class_name.to_string()).unwrap();
let response = self.response_receiver.recv();
if let Ok(class_data) = response {
if class_data.is_none() {
return None;
}
let class_data = class_data.unwrap();
let class_name = constants.put(&class_data.name);
let fields = class_data
.fields
.iter()
.map(|f| {
let field_name = constants.put(&f.name);
let field_type = constants.put(&f.type_name);
JavaField {
field_name,
field_type,
}
})
.collect();
let methods = class_data
.methods
.iter()
.map(|m| {
let method_name = constants.put(&m.name);
let return_type = constants.put(&m.return_type);
JavaMethod {
method_name,
param_types: vec![],
return_type: Some(return_type),
}
})
.collect();
let superclass = constants.put(&class_data.superclass);
let interfaces = class_data
.interfaces
.iter()
.map(|i| constants.put(i))
.collect();
return Some(JavaClass {
class_name,
interfaces,
superclass,
fields,
methods,
});
}
None
}
fn run_java_inspector(
workdir: &path::Path,
) -> io::Result<(mpsc::Sender<String>, mpsc::Receiver<Option<ClassData>>)> {
let java = java_home_file("bin/java")?;
let (req_sender, req_receiver) = mpsc::channel::<String>();
let (resp_sender, resp_receiver) = mpsc::channel::<Option<ClassData>>();
let workdir = workdir.to_str().unwrap().to_string();
thread::spawn(move || {
let proc = process::Command::new(java)
.arg("JavaStdLib")
.current_dir(&workdir)
.stdout(Stdio::piped())
.stdin(Stdio::piped())
.stderr(Stdio::inherit())
.spawn();
if let Err(e) = proc {
println!("Running java code: {:#?}", e);
return;
}
let proc = proc.unwrap();
if proc.stdout.is_none() {
println!("Process has no stdout pipe.");
println!("Workdir exists? {}", path::Path::new(&workdir).is_dir());
return;
}
let mut stdout = io::BufReader::new(proc.stdout.unwrap());
if proc.stdin.is_none() {
println!("Process has no stdin pipe.");
return;
}
let mut stdin = proc.stdin.unwrap();
for class_name in req_receiver {
let request_string = format!("{}\n", class_name.replace("/", "."));
if let Err(_) = stdin.write_all(request_string.as_bytes()) {
break;
}
let mut current_class = ClassData {
name: "".to_string(),
superclass: "".to_string(),
interfaces: vec![],
methods: vec![],
fields: vec![],
};
let mut current_method = MethodData {
name: "".to_string(),
return_type: "".to_string(),
};
let mut current_field = FieldData {
name: "".to_string(),
type_name: "".to_string(),
};
loop {
let mut line = String::new();
let read = stdout.read_line(&mut line);
if let Err(_) = read {
break;
}
if let Ok(0) = read {
break;
}
let line = line.trim();
if let Some(class_name) = remove_prefix(&line, "ClassName: ") {
current_class = ClassData {
name: class_name.replace(".", "/").to_string(),
superclass: "java/lang/Object".to_string(),
interfaces: vec![],
methods: vec![],
fields: vec![],
};
} else if let Some(superclass) = remove_prefix(&line, "SuperClass: ") {
current_class.superclass = superclass.replace(".", "/").to_string();
} else if let Some(interface) = remove_prefix(&line, "Implements: ") {
current_class
.interfaces
.push(interface.replace(".", "/").to_string());
} else if let Some(method_name) = remove_prefix(&line, "MethodName: ") {
current_method = MethodData {
name: method_name.to_string(),
return_type: "".to_string(),
}
} else if let Some(method_type) = remove_prefix(&line, "MethodReturnType: ") {
current_method.return_type = method_type.replace(".", "/").to_string();
} else if line == "EndMethod" {
current_class.methods.push(current_method.clone());
} else if let Some(field_name) = remove_prefix(&line, "FieldName: ") {
current_field = FieldData {
name: field_name.to_string(),
type_name: "".to_string(),
};
} else if let Some(field_type) = remove_prefix(&line, "FieldType: ") {
current_field.type_name = field_type.replace(".", "/").to_string();
} else if line == "EndField" {
current_class.fields.push(current_field.clone());
} else if line == "EndClass" {
resp_sender.send(Some(current_class.clone())).unwrap();
break;
} else if line == "NoClass" {
resp_sender.send(None).unwrap();
break;
}
}
}
println!("Done listening for classes.");
stdin.write_all("END\n".as_bytes()).unwrap();
});
Ok((req_sender, resp_receiver))
}
fn compile_java_code(workdir: &path::Path) -> io::Result<()> {
let javac = java_home_file("bin/javac")?;
let mut proc = process::Command::new(javac)
.arg("JavaStdLib.java")
.current_dir(workdir)
.spawn()?;
let exit = proc.wait()?;
if exit.success() {
Ok(())
} else {
let mut stdout = String::new();
let mut stderr = String::new();
if proc.stdout.is_some() {
proc.stdout.unwrap().read_to_string(&mut stdout).unwrap();
}
if proc.stderr.is_some() {
proc.stderr.unwrap().read_to_string(&mut stderr).unwrap();
}
Err(io::Error::new(
io::ErrorKind::Other,
format!("{}\n\n{}", stdout, stderr),
))
}
}
fn write_java_code(workdir: &path::Path) -> io::Result<()> {
let java_file_path = workdir.join("JavaStdLib.java");
let mut java_file = fs::File::create(java_file_path)?;
java_file.write_all(include_str!("JavaStdLib.java").as_bytes()).unwrap();
Ok(())
}
}
#[derive(Clone)]
struct ClassData {
name: String,
superclass: String,
interfaces: Vec<String>,
methods: Vec<MethodData>,
fields: Vec<FieldData>,
}
#[derive(Clone)]
struct MethodData {
name: String,
return_type: String,
}
#[derive(Clone)]
struct FieldData {
name: String,
type_name: String,
}
fn remove_prefix<'a>(text: &'a str, prefix: &str) -> Option<&'a str> {
if text.starts_with(prefix) {
return Some(&text[prefix.len()..]);
}
None
}
fn java_home_file(subpath: &str) -> Result<PathBuf, io::Error> {
env::var("JAVA_HOME")
.map(|home| path::Path::new(&home).join(subpath))
.map_err(|_e| io::Error::new(io::ErrorKind::Other, "Unable to read JAVA_HOME."))
}
|
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Deserialize, Serialize, Debug)]
pub struct OrderBookResult {
pub bids: Vec<(String, String, u32)>,
pub asks: Vec<(String, String, u32)>,
}
#[derive(Deserialize, Serialize, Debug)]
pub struct RawOrderBook {
pub error: Vec<String>,
pub result: HashMap<String, OrderBookResult>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct OfferData {
pub price: f32,
pub size: f32,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct OrderBookDTO {
pub bids: Vec<OfferData>,
pub asks: Vec<OfferData>,
}
|
#[macro_use]
extern crate rental;
#[derive(Debug)]
pub struct Foo {
i: i32,
}
rental! {
mod rentals {
use super::*;
#[rental(debug, deref_suffix)]
pub struct SimpleRef {
foo: Box<Foo>,
iref: &'foo i32,
}
#[rental_mut(debug, deref_suffix)]
pub struct SimpleMut {
foo: Box<Foo>,
iref: &'foo mut i32,
}
}
}
#[test]
fn print() {
let foo = Foo { i: 5 };
let sr = rentals::SimpleRef::new(Box::new(foo), |foo| &foo.i);
println!("{:?}", sr);
let foo = Foo { i: 5 };
let sm = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i);
println!("{:?}", sm);
}
|
/// Represents original source file location information present in Erlang Abstract Format
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub struct Loc {
line: u32,
column: u32,
}
impl Loc {
pub fn new(line: u32, column: u32) -> Self {
Self { line, column }
}
}
|
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use core::sync::atomic::Ordering;
use core::sync::atomic::AtomicU64;
#[derive(Clone, Debug, PartialEq, Copy)]
#[repr(u64)]
pub enum VcpuState {
Waiting,
Searching, // wait in kernel to look for new jobs
Running,
}
#[derive(Debug, Default)]
#[repr(C)]
#[repr(align(128))]
pub struct CPULocal {
pub kernelStack: AtomicU64, //offset 0
pub userStack: AtomicU64, //offset 8
pub vcpuId: usize, //offset 16
pub waitTask: AtomicU64, //offset 24
pub currentTask: AtomicU64, //offset 32
pub pendingFreeStack: AtomicU64, //offset 40
pub state: AtomicU64, //offset 48
pub data: u64, // for eventfd data writing and reading
pub eventfd: i32,
}
impl CPULocal {
pub fn SwapState(&self, state: VcpuState) -> VcpuState {
let old = self.state.swap(state as u64, Ordering::SeqCst);
return unsafe { core::mem::transmute(old) };
}
pub fn SetState(&self, state: VcpuState) {
self.state.store(state as u64, Ordering::Release);
}
pub fn State(&self) -> VcpuState {
let state = self.state.load(Ordering::Acquire);
return unsafe { core::mem::transmute(state) };
}
pub fn SetWaiting(&self) {
self.SetState(VcpuState::Waiting)
}
pub fn SetRunning(&self) {
self.SetState(VcpuState::Running)
}
pub fn SetSearching(&self) {
self.SetState(VcpuState::Searching)
}
} |
#![cfg(path_api)]
use tauri_api::path;
use tauri_api::path::BaseDirectory;
use webview_official::Webview;
pub fn resolve_path(
webview: &mut Webview<'_>,
path: String,
directory: Option<BaseDirectory>,
callback: String,
error: String,
) {
crate::execute_promise(
webview,
move || path::resolve_path(path, directory),
callback,
error,
)
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type Buffer = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct ByteOrder(pub i32);
impl ByteOrder {
pub const LittleEndian: Self = Self(0i32);
pub const BigEndian: Self = Self(1i32);
}
impl ::core::marker::Copy for ByteOrder {}
impl ::core::clone::Clone for ByteOrder {
fn clone(&self) -> Self {
*self
}
}
pub type DataReader = *mut ::core::ffi::c_void;
pub type DataReaderLoadOperation = *mut ::core::ffi::c_void;
pub type DataWriter = *mut ::core::ffi::c_void;
pub type DataWriterStoreOperation = *mut ::core::ffi::c_void;
pub type FileInputStream = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct FileOpenDisposition(pub i32);
impl FileOpenDisposition {
pub const OpenExisting: Self = Self(0i32);
pub const OpenAlways: Self = Self(1i32);
pub const CreateNew: Self = Self(2i32);
pub const CreateAlways: Self = Self(3i32);
pub const TruncateExisting: Self = Self(4i32);
}
impl ::core::marker::Copy for FileOpenDisposition {}
impl ::core::clone::Clone for FileOpenDisposition {
fn clone(&self) -> Self {
*self
}
}
pub type FileOutputStream = *mut ::core::ffi::c_void;
pub type FileRandomAccessStream = *mut ::core::ffi::c_void;
pub type IBuffer = *mut ::core::ffi::c_void;
pub type IContentTypeProvider = *mut ::core::ffi::c_void;
pub type IDataReader = *mut ::core::ffi::c_void;
pub type IDataWriter = *mut ::core::ffi::c_void;
pub type IInputStream = *mut ::core::ffi::c_void;
pub type IInputStreamReference = *mut ::core::ffi::c_void;
pub type IOutputStream = *mut ::core::ffi::c_void;
pub type IPropertySetSerializer = *mut ::core::ffi::c_void;
pub type IRandomAccessStream = *mut ::core::ffi::c_void;
pub type IRandomAccessStreamReference = *mut ::core::ffi::c_void;
pub type IRandomAccessStreamWithContentType = *mut ::core::ffi::c_void;
pub type InMemoryRandomAccessStream = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct InputStreamOptions(pub u32);
impl InputStreamOptions {
pub const None: Self = Self(0u32);
pub const Partial: Self = Self(1u32);
pub const ReadAhead: Self = Self(2u32);
}
impl ::core::marker::Copy for InputStreamOptions {}
impl ::core::clone::Clone for InputStreamOptions {
fn clone(&self) -> Self {
*self
}
}
pub type InputStreamOverStream = *mut ::core::ffi::c_void;
pub type OutputStreamOverStream = *mut ::core::ffi::c_void;
pub type RandomAccessStreamOverStream = *mut ::core::ffi::c_void;
pub type RandomAccessStreamReference = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct UnicodeEncoding(pub i32);
impl UnicodeEncoding {
pub const Utf8: Self = Self(0i32);
pub const Utf16LE: Self = Self(1i32);
pub const Utf16BE: Self = Self(2i32);
}
impl ::core::marker::Copy for UnicodeEncoding {}
impl ::core::clone::Clone for UnicodeEncoding {
fn clone(&self) -> Self {
*self
}
}
|
use snafu::Snafu;
#[derive(Debug, Snafu)]
pub enum Error {
#[snafu(
visibility = "pub",
display("Could not open file '{}': {}", "filename.display()", "source")
)]
OpenFile {
path: std::path::PathBuf,
source: std::io::Error,
},
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
|
use serde::Deserialize;
use crate::apis::flight_provider::raw_models::airline_code_raw::AirlineCodeRaw;
#[derive(Deserialize, Debug)]
pub struct AirlineRaw {
pub name: Option<String>,
pub short: Option<String>,
pub code: Option<AirlineCodeRaw>,
pub url: Option<String>,
}
|
use std::collections::HashMap;
use crate::ast::node::bind_node::BindNode;
use crate::ast::node::choose_node::ChooseNode;
use crate::ast::node::delete_node::DeleteNode;
use crate::ast::node::foreach_node::ForEachNode;
use crate::ast::node::if_node::IfNode;
use crate::ast::node::include_node::IncludeNode;
use crate::ast::node::insert_node::InsertNode;
use crate::ast::node::node_type::NodeType;
use crate::ast::node::otherwise_node::OtherwiseNode;
use crate::ast::node::result_map_id_node::ResultMapIdNode;
use crate::ast::node::result_map_node::ResultMapNode;
use crate::ast::node::result_map_result_node::ResultMapResultNode;
use crate::ast::node::select_node::SelectNode;
use crate::ast::node::set_node::SetNode;
use crate::ast::node::sql_node::SqlNode;
use crate::ast::node::string_node::StringNode;
use crate::ast::node::trim_node::TrimNode;
use crate::ast::node::update_node::UpdateNode;
use crate::ast::node::when_node::WhenNode;
use crate::ast::node::where_node::WhereNode;
use crate::engine::runtime::RbatisEngine;
use crate::utils::xml_loader::{Element, load_xml};
pub struct Xml {}
impl Xml {
pub fn parser(xml_content: &str) -> HashMap<String, NodeType> {
return parser(xml_content);
}
}
pub fn parser(xml_content: &str) -> HashMap<String, NodeType> {
let nodes = load_xml(xml_content);
let data = loop_decode_xml(&nodes);
let mut m = HashMap::new();
for x in &data {
match x {
NodeType::NResultMapNode(node) => m.insert(node.id.clone(), x.clone()),
_ => {
continue;
}
};
}
for x in &data {
match x {
NodeType::NSelectNode(node) => m.insert(node.id.clone(), x.clone()),
NodeType::NDeleteNode(node) => m.insert(node.id.clone(), x.clone()),
NodeType::NUpdateNode(node) => m.insert(node.id.clone(), x.clone()),
NodeType::NInsertNode(node) => m.insert(node.id.clone(), x.clone()),
NodeType::NSqlNode(node) => m.insert(node.id.clone(), x.clone()),
_ => m.insert("unknow".to_string(), NodeType::Null),
};
}
//replace include node
do_replace_include_node(&mut m);
return m;
}
fn do_replace_include_node(arg: &mut HashMap<String, NodeType>) {
let arg_clone = arg.clone();
for (k, v) in arg {
let mut childs = v.childs_mut();
if childs.is_none() {
continue;
}
let childs = childs.take().unwrap();
let mut include_nodes = Vec::new();
loop_find_include_node(childs, &mut include_nodes);
if include_nodes.is_empty() {
continue;
}
for item in include_nodes {
match item {
NodeType::NInclude(include) => {
if include.refid.is_empty() {
panic!("[rbatis] include node refid must have an value!");
}
let mut v = find_node(&arg_clone, &include.refid);
if v.is_none() {
panic!(format!("[rbatis] include node refid = '{}' not find!", &include.refid));
}
include.childs = vec![v.take().unwrap()];
}
_ => {}
}
}
}
}
fn find_node(arg: &HashMap<String, NodeType>, id: &str) -> Option<NodeType> {
for (k, v) in arg {
if k.eq(id) {
return Some(v.clone());
}
}
return None;
}
fn loop_find_include_node<'m>(m: &'m mut Vec<NodeType>, result: &mut Vec<&'m mut NodeType>) {
for x in m {
match x {
NodeType::NInclude(_) => {
result.push(x);
}
_ => {
let childs = x.childs_mut();
if childs.is_some() {
return loop_find_include_node(childs.unwrap(), result);
}
}
}
}
}
pub fn loop_decode_xml(xml_vec: &Vec<Element>) -> Vec<NodeType> {
let mut nodes = vec![];
for xml in xml_vec {
let child_nodes;
if xml.childs.len() > 0 {
child_nodes = loop_decode_xml(&(&xml).childs);
} else {
child_nodes = vec![];
}
let tag_str = xml.tag.as_str();
//println!("tag_str:{}",tag_str);
match tag_str {
"mapper" => {
//mapper 不做处理,直接返回子节点
return child_nodes;
}
"select" => nodes.push(NodeType::NSelectNode(SelectNode {
id: xml.get_attr("id"),
childs: child_nodes,
})),
"update" => nodes.push(NodeType::NUpdateNode(UpdateNode {
id: xml.get_attr("id"),
childs: child_nodes,
})),
"insert" => nodes.push(NodeType::NInsertNode(InsertNode {
id: xml.get_attr("id"),
childs: child_nodes,
})),
"delete" => nodes.push(NodeType::NDeleteNode(DeleteNode {
id: xml.get_attr("id"),
childs: child_nodes,
})),
"if" => nodes.push(NodeType::NIf(IfNode {
childs: child_nodes,
test: xml.get_attr("test"),
})),
"trim" => nodes.push(NodeType::NTrim(TrimNode {
childs: child_nodes,
prefix: xml.get_attr("prefix"),
suffix: xml.get_attr("suffix"),
suffix_overrides: xml.get_attr("suffix_overrides"),
prefix_overrides: xml.get_attr("prefix_overrides"),
})),
"foreach" => nodes.push(NodeType::NForEach(ForEachNode {
childs: child_nodes,
collection: xml.get_attr("collection"),
index: xml.get_attr("index"),
item: xml.get_attr("item"),
open: xml.get_attr("open"),
close: xml.get_attr("close"),
separator: xml.get_attr("separator"),
})),
"choose" => nodes.push(NodeType::NChoose(ChooseNode {
when_nodes: filter_when_nodes(&child_nodes),
otherwise_node: filter_otherwise_nodes(child_nodes),
})),
"when" => nodes.push(NodeType::NWhen(WhenNode {
childs: child_nodes,
test: xml.get_attr("test"),
})),
"where" => nodes.push(NodeType::NWhere(WhereNode {
childs: child_nodes,
})),
"otherwise" => nodes.push(NodeType::NOtherwise(OtherwiseNode {
childs: child_nodes,
})),
"bind" => nodes.push(NodeType::NBind(BindNode {
name: xml.get_attr("name"),
value: xml.get_attr("value"),
})),
"include" => {
if child_nodes.len() > 0 {
panic!("[rabatis] the <include> node child element must be empty!");
}
nodes.push(NodeType::NInclude(IncludeNode {
refid: xml.get_attr("refid"),
childs: child_nodes,
}))
}
"set" => nodes.push(NodeType::NSet(SetNode {
childs: child_nodes,
})),
"id" => nodes.push(NodeType::NResultMapIdNode(ResultMapIdNode {
column: xml.get_attr("column"),
lang_type: xml.get_attr("lang_type"),
})),
"result" => nodes.push(NodeType::NResultMapResultNode(ResultMapResultNode {
column: xml.get_attr("column"),
lang_type: xml.get_attr("lang_type"),
version_enable: xml.get_attr("version_enable"),
logic_enable: xml.get_attr("logic_enable"),
logic_undelete: xml.get_attr("logic_undelete"),
logic_deleted: xml.get_attr("logic_deleted"),
})),
"result_map" => nodes.push(NodeType::NResultMapNode(ResultMapNode::new(xml.get_attr("id"),
xml.get_attr("table"),
filter_result_map_id_nodes(&child_nodes),
filter_result_map_result_nodes(&child_nodes), ))),
"sql" => {
nodes.push(NodeType::NSqlNode(SqlNode {
id: xml.get_attr("id"),
childs: child_nodes,
}))
}
"" => {
let data = xml.data.as_str();
let tag = xml.tag.as_str();
let n = StringNode::new(data);
nodes.push(NodeType::NString(n));
}
_ => {}
}
}
return nodes;
}
pub fn filter_result_map_result_nodes(arg: &Vec<NodeType>) -> Vec<ResultMapResultNode> {
let mut data = vec![];
for x in arg {
if let NodeType::NResultMapResultNode(result_node) = x {
data.push(result_node.clone());
}
}
return data;
}
pub fn filter_result_map_id_nodes(arg: &Vec<NodeType>) -> Option<ResultMapIdNode> {
for x in arg {
if let NodeType::NResultMapIdNode(id_node) = x {
return Option::Some(id_node.clone());
}
}
return Option::None;
}
pub fn filter_when_nodes(arg: &Vec<NodeType>) -> Option<Vec<NodeType>> {
let mut data = vec![];
for x in arg {
if let NodeType::NWhen(when_node) = x {
data.push(NodeType::NWhen(when_node.clone()))
} else {}
}
if data.len() == 0 {
return Option::None;
} else {
return Some(data);
}
}
pub fn filter_otherwise_nodes(arg: Vec<NodeType>) -> Option<Box<NodeType>> {
let mut data = vec![];
for x in arg {
if let NodeType::NOtherwise(node) = x {
data.push(NodeType::NOtherwise(node))
} else {}
}
if data.len() > 0 {
if data.len() > 1 {
panic!("otherwise_nodes length can not > 1;")
}
let d0 = data[0].clone();
return Option::Some(Box::new(d0));
} else {
return Option::None;
}
}
|
//
// Copyright 2019 Sͬeͥbͭaͭsͤtͬian
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
// NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
// PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
use std::io::prelude::*;
use std::net::TcpStream;
use std::net::TcpListener;
use std::fs;
use std::process::Command;
use std::env;
use std::path::Path;
// Let's go
fn main () {
let path = env::current_dir();
let path_str = path.unwrap().into_os_string().into_string();
let get_ip_exec = path_str.unwrap() + &"/get_IP";
let mut ip = execute_process (get_ip_exec);
ip = ip.trim().to_string();
ip = ip + &":80";
//DEBUG println! ("IP: >{}<",ip);
let listener = TcpListener::bind (ip).unwrap();
for stream in listener.incoming () {
let stream = stream.unwrap();
handle_connection(stream);
}
}
// Welcome Wo(Men), nice to meet you.
fn handle_connection (mut stream: TcpStream) {
let mut buffer = [0;512];
stream.read(&mut buffer).unwrap();
let mut uri_path = get_path (String::from_utf8(buffer.to_vec()).unwrap());
// normalize path, a simple path
// a lonly slash is the index.shtml file
let path = env::current_dir();
let path_str = path.unwrap().into_os_string().into_string();
if "/" == uri_path {
uri_path = uri_path + &"index.shtml";
}
// a slash at beginning need previous path
if uri_path.starts_with ("/") {
uri_path = format!("{}{}", path_str.unwrap(),uri_path);
}
//DEBUG println! ("URI requested: {}", uri_path);
let mut response = format!("HTTP/1.1 404 NOT FOUND\n\rContent-Type: text/html;charset=utf-8\n\r\n\r{}","<html><head><title>Somewhere over the rainbow...</title></head><body>...blue birds fly</body></html>");
let path_object_string = format! ("{}", uri_path);
let path_object = Path::new(&path_object_string);
if path_object.exists() {
let contents = replace_ssi_command (fs::read_to_string(uri_path).unwrap());
response = format!("HTTP/1.1 200 OK\n\rContent-Type: text/html;charset=utf-8\n\r\n\r{}",contents);
}
stream.write (response.as_bytes()).unwrap();
stream.flush().unwrap();
}
// How can I help you?
fn get_path (http_header : String) -> String {
//GET / HTTP/1.1
let lines: Vec<&str> = http_header.split("\r\n").collect();
for (pos, line) in lines.iter().enumerate() {
if 0 == pos {
//DEBUG println! ("LINE {}: {:#?}",pos,line);
let token_line: Vec<&str> = line.split(" ").collect();
for (pos_in_line, token) in token_line.iter().enumerate() {
match pos_in_line {
0 => {
let _http_method = token;
}
1 => {
let http_uri = token;
//DEBUG println! ("URI >{}< requested", http_uri);
return format! ("{}",http_uri);
}
_ => {
let _ignored = token;
}
}
}
}
}
return format!("Yes we can!");
}
// My pleasure!
fn replace_ssi_command (to_parse : String) -> String {
let mut result = "".to_string() ;
{
// looking for start and split
let tokens: Vec<&str> = to_parse.split("<!--").collect();
for (_pos, comment) in tokens.iter().enumerate() {
const SSI_STATEMENT : char = '#';
match comment.chars().next() {
// OK we found an SSI statement
Some(SSI_STATEMENT) => {
let tokens: Vec<&str> = comment.split("-->").collect();
for (pos, cmd) in tokens.iter().enumerate() {
if 0 == pos {
let ssi_result = do_ssi_command (cmd.to_string());
//println! ("I found:{}", ssi_result);
result = result + &ssi_result;
}
else {
result = result + &cmd;
}
}
},
// do it for all other (not) matches
_ => {
result = result + &comment;
},
};
}
}
return result;
}
// For you? I execute all my love!
fn do_ssi_exec (params : &Vec<&str>) -> String {
// normalize... (1.=#exec, 2.=cmd[.], 3.=.)
// log (info, "Exec parameter: {:#?} ");
let mut contained : char = ' ';
let mut container = String::from("");
for (pos, token) in params.iter().enumerate() {
if 0 < pos {
if token.ends_with("=") {
contained = '=';
container = container + &token;
}
else {
if '=' == contained {
contained = ' ';
contained = token.get(..1).unwrap().chars().next().unwrap();
container = container + &token;
}
else {
if ' ' == contained {
container = container + &token;
}
else {
container = container + &" " + &token;
if token.ends_with (contained) {
contained = ' ';
}
}
}
}
//DEBUG println! ("normalizes cmd: {}",container);
}
}
if 0 < params.len() {
let tokens: Vec<&str> = container.split("=").collect();
let mut command : String = "".to_string();
for (pos, token) in tokens.iter().enumerate () {
if 1 == pos {
command = token.replace ("\"", "");
}
}
return execute_process (command);
}
// Hey! I'm not soooo stupid. Give me something to do or don't call me!
return to_string("");
}
fn execute_process (command : String) -> String {
let mut cmd = Command::new ("");
let cmd_tokens : Vec<&str> = command.split(" ").collect();
for (pos, token) in cmd_tokens.iter().enumerate() {
if 0 == pos {
cmd = Command::new (token);
}
else {
if 0 < token.len() {
cmd.arg (token);
}
}
}
//DEBUG println! ("{:#?}", cmd);
let cmd_result = cmd.output().expect ("404 program not found");
let cmd_result_as_string = String::from_utf8_lossy (cmd_result.stdout.as_slice());
return format! ("{}",cmd_result_as_string);
}
// Come on, let me do this work for you!
fn do_ssi_command (ssi_command : String) -> String {
// incomming #exec "cmd" => split it do ist
let tokens: Vec<&str> = ssi_command.split(" ").collect();
let mut exec_result = "".to_string();
for (pos, token) in tokens.iter().enumerate () {
if 0 == pos {
//println! ("command: {}",token);
match token {
&"#exec" => {
exec_result = do_ssi_exec (&tokens);
//DEBUG println! ("Method return: {}", exec_result);
return exec_result;
},
_ => {
// I'm lost in translate. Do you really know what you mean?
}
}
}
}
// \n\r
return to_string (&exec_result);
}
fn to_string (src : &str) -> String {
return format! ("{}",src);
}
// Help me! I'm lost in EOF
|
extern crate gst;
use std::io;
use std::io::prelude::*;
use std::thread;
fn player_loop(mut playbin : gst::PlayBin) {
let stdin = io::stdin();
for line in stdin.lock().lines() {
let line = line.unwrap();
let mut line_split = line.split(' ');
let command = line_split.next();
let argument : Vec<&str> = line_split.collect();
let argument = argument.join(" ");
match command.unwrap() {
"PAUSE" => {
if playbin.is_playing() {
playbin.pause();
println!("INFO PLAYBACK paused");
} else {
playbin.play();
println!("INFO PLAYBACK playing");
}
}
"RESUME" if playbin.is_paused() => {
playbin.play();
println!("INFO PLAYBACK playing");
}
"LOAD" => {
let track_path = String::from("file://") + argument.as_str();
println!("INFO LOADING {}", track_path);
playbin.set_null_state();
playbin.set_uri(&track_path);
playbin.play();
println!("INFO PLAYBACK playing");
}
"SEEK" => {
let duration_s = playbin.duration_s().unwrap();
let position_s = playbin.position_s().unwrap();
let seek_param = String::from(argument);
let (seek_operator, seek_rest) = seek_param.split_at(1);
let seek_parsed_s = seek_rest.parse::<f64>().unwrap();
let seek_position =
match seek_operator {
"+" => position_s + seek_parsed_s,
"-" => position_s - seek_parsed_s,
"%" => duration_s * (seek_parsed_s * 0.01),
_ => seek_parsed_s // check bounds
};
playbin.set_position_s(seek_position);
}
"VOLUME" => {
let volume = argument.parse::<f64>().unwrap();
playbin.set_volume(volume)
}
_ => {
println!("ERROR unknown command '{}'", line);
}
}
}
println!("INFO EOF quitting");
// Exit on EOF
std::process::exit(1);
}
fn main(){
gst::init();
let playbin = gst::PlayBin::new("audio_player").expect("Couldn't create playbin");
let mut mainloop = gst::MainLoop::new();
let mut bus = playbin.bus().expect("Couldn't get pipeline bus");
let bus_receiver = bus.receiver();
println!("INFO Started remote-player 0.1.0");
mainloop.spawn();
thread::spawn(move || player_loop(playbin));
for message in bus_receiver.iter() {
match message.parse(){
gst::Message::ErrorParsed{ref error, ..} => {
println!("ERROR GSTREAMER {}", error.message());
break
}
gst::Message::Eos(_) => {
println!("INFO PLAYBACK stopped");
}
_ => {
// println!("msg of type `{}` from element `{}`", message.type_name(), message.src_name());
}
}
}
mainloop.quit();
}
|
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("connection error")]
ConnectionError(mobc::Error<mobc_diesel::Error>),
#[error("database error")]
DatabaseError(diesel::result::Error),
}
impl From<mobc::Error<mobc_diesel::Error>> for Error {
fn from(error: mobc::Error<mobc_diesel::Error>) -> Self {
Error::ConnectionError(error)
}
}
impl From<diesel::result::Error> for Error {
fn from(error: diesel::result::Error) -> Self {
Error::DatabaseError(error)
}
}
|
use std::env;
fn build_windows() {
#[cfg(windows)]
windows::build!(
windows::win32::windows_programming::{GetUserNameA, GetComputerNameExA, GetTickCount64},
windows::win32::system_services::{GlobalMemoryStatusEx, GetSystemPowerStatus},
);
}
fn build_macos() {
println!("cargo:rustc-link-lib=framework=Foundation");
println!("cargo:rustc-link-lib=framework=IOKit");
}
fn main() {
match env::var("CARGO_CFG_TARGET_OS").as_ref().map(|x| &**x) {
Ok("macos") => build_macos(),
Ok("windows") => build_windows(),
_ => {}
}
}
|
/* Copyright (C) 2016 Yutaka Kamei */
#![allow(non_snake_case)]
use std::error::Error;
use std::fmt::{self, Display};
use regex::Regex;
use rustc_serialize::json;
#[derive(Debug)]
pub struct ScimFilterError {
message: String,
rest: Vec<String>,
}
impl Display for ScimFilterError {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
write!(f, "{}", self.message)
}
}
impl Error for ScimFilterError {
fn description(&self) -> &str {
&*self.message
}
}
pub type ScimFilterResult<T> = Result<T, ScimFilterError>;
#[derive(Debug, PartialEq)]
pub enum Filter {
Singular(AttrExp),
Not(Box<Filter>),
And(Box<Filter>, Box<Filter>),
Or(Box<Filter>, Box<Filter>),
}
#[derive(Debug, PartialEq)]
pub enum AttrExp {
Pr(AttrPath),
Eq(AttrPath, CompValue),
Ne(AttrPath, CompValue),
Co(AttrPath, CompValue),
Sw(AttrPath, CompValue),
Ew(AttrPath, CompValue),
Ge(AttrPath, CompValue),
Le(AttrPath, CompValue),
Gt(AttrPath, CompValue),
Lt(AttrPath, CompValue),
}
#[derive(Debug, PartialEq)]
pub struct AttrPath {
uri: Option<String>,
attr: String,
sub_attr: Option<String>,
}
#[derive(Debug, PartialEq)]
pub enum CompValue {
True,
False,
Null,
Str(String),
Num(f64),
}
#[derive(Debug)]
struct Done<T> {
rest: Vec<String>,
done: T,
}
macro_rules! try_retain {
( $e:expr, $original:expr ) => {
try!($e.map_err(|mut e| {
e.rest = $original.clone();
e
}))
};
}
pub fn filter_expression(s: &str) -> ScimFilterResult<Filter> {
match FILTER(tokenize(s)) {
Ok(done) => { Ok(done.done) },
Err(err) => { Err(err) },
}
}
fn FILTER(mut tokens: Vec<String>) -> ScimFilterResult<Done<Filter>> {
let _tokens = tokens.clone();
if tokens.is_empty() {
Err(ScimFilterError {
message: format!("invalid FILTER: tokens is empty"),
rest: tokens,
})
} else if tokens[0] == "(".to_string() {
tokens.remove(0);
let mut filter = try_retain!(FILTER(tokens), _tokens);
if filter.rest.get(0) == Some(&")".to_string()) {
filter.rest.remove(0);
Ok(Done {
rest: filter.rest,
done: filter.done,
})
} else {
Err(ScimFilterError {
message: format!("invalid FILTER: tokens does not close by right parenthesis"),
rest: _tokens,
})
}
} else if tokens.contains(&"or".to_string()) || tokens.contains(&"and".to_string()) {
let mut is_or = true;
for tok in &tokens {
match tok.as_ref() {
"or" => { is_or = true; break; }
"and" => { is_or = false; break; }
_ => { continue }
}
}
let mut splitn = tokens.splitn_mut(2, |s| {
*s == "or".to_string() || *s == "and".to_string()
});
let left_filter = try_retain!(FILTER(splitn.next().unwrap().to_vec()), _tokens);
let right_filter = try_retain!(FILTER(splitn.next().unwrap().to_vec()), _tokens);
if is_or {
Ok(Done {
rest: right_filter.rest,
done: Filter::Or(Box::new(left_filter.done), Box::new(right_filter.done)),
})
} else {
Ok(Done {
rest: right_filter.rest,
done: Filter::And(Box::new(left_filter.done), Box::new(right_filter.done)),
})
}
} else if tokens[0] == "not".to_string() {
tokens.remove(0);
let filter = try_retain!(FILTER(tokens), _tokens);
Ok(Done {
rest: filter.rest,
done: Filter::Not(Box::new(filter.done)),
})
} else {
attrExp(tokens).map(|attr_exp| {
Done {
rest: attr_exp.rest,
done: Filter::Singular(attr_exp.done),
}
})
}
}
fn attrExp(tokens: Vec<String>) -> ScimFilterResult<Done<AttrExp>> {
if tokens.is_empty() {
Err(ScimFilterError {
message: format!("invalid attrExp: tokens is empty"),
rest: tokens,
})
} else if tokens.len() < 2 {
Err(ScimFilterError {
message: format!("invalid attrExp: tokens MUST include at least 2 items"),
rest: tokens,
})
} else {
let _tokens = tokens.clone();
let mut attr_path = try_retain!(attrPath(tokens), _tokens);
match attr_path.rest.remove(0).as_ref() {
"pr" => {
Ok(Done {
rest: attr_path.rest,
done: AttrExp::Pr(attr_path.done),
})
},
"eq" => {
let comp_value = try_retain!(compValue(attr_path.rest), _tokens);
Ok(Done {
rest: comp_value.rest,
done: AttrExp::Eq(attr_path.done, comp_value.done),
})
},
"ne" => {
let comp_value = try_retain!(compValue(attr_path.rest), _tokens);
Ok(Done {
rest: comp_value.rest,
done: AttrExp::Ne(attr_path.done, comp_value.done),
})
},
"co" => {
let comp_value = try_retain!(compValue(attr_path.rest), _tokens);
Ok(Done {
rest: comp_value.rest,
done: AttrExp::Co(attr_path.done, comp_value.done),
})
},
"sw" => {
let comp_value = try_retain!(compValue(attr_path.rest), _tokens);
Ok(Done {
rest: comp_value.rest,
done: AttrExp::Sw(attr_path.done, comp_value.done),
})
},
"ew" => {
let comp_value = try_retain!(compValue(attr_path.rest), _tokens);
Ok(Done {
rest: comp_value.rest,
done: AttrExp::Ew(attr_path.done, comp_value.done),
})
},
"ge" => {
let comp_value = try_retain!(compValue(attr_path.rest), _tokens);
Ok(Done {
rest: comp_value.rest,
done: AttrExp::Ge(attr_path.done, comp_value.done),
})
},
"le" => {
let comp_value = try_retain!(compValue(attr_path.rest), _tokens);
Ok(Done {
rest: comp_value.rest,
done: AttrExp::Le(attr_path.done, comp_value.done),
})
},
"gt" => {
let comp_value = try_retain!(compValue(attr_path.rest), _tokens);
Ok(Done {
rest: comp_value.rest,
done: AttrExp::Gt(attr_path.done, comp_value.done),
})
},
"lt" => {
let comp_value = try_retain!(compValue(attr_path.rest), _tokens);
Ok(Done {
rest: comp_value.rest,
done: AttrExp::Lt(attr_path.done, comp_value.done),
})
},
op => {
Err(ScimFilterError {
message: format!("invalid attrExp: \"{}\" operator not supported", op),
rest: _tokens,
})
},
}
}
}
fn compValue(mut tokens: Vec<String>) -> ScimFilterResult<Done<CompValue>> {
if tokens.is_empty() {
Err(ScimFilterError {
message: format!("invalid compValue: tokens is empty"),
rest: tokens,
})
} else {
let comp_value = match tokens[0].as_ref() {
"true" => CompValue::True,
"false" => CompValue::False,
"null" => CompValue::Null,
_ => {
if let Ok(v) = json::decode::<String>(&tokens[0]) {
CompValue::Str(v)
} else if let Ok(v) = json::decode::<f64>(&tokens[0]) {
CompValue::Num(v)
} else {
return Err(ScimFilterError {
message: format!("invalid compValue: \"{}\" is not JSON value",
tokens[0]),
rest: tokens,
})
}
},
};
tokens.remove(0);
Ok(Done {
rest: tokens,
done: comp_value,
})
}
}
fn attrPath(mut tokens: Vec<String>) -> ScimFilterResult<Done<AttrPath>> {
if tokens.is_empty() {
Err(ScimFilterError {
message: format!("invalid attrPath: tokens is empty"),
rest: tokens,
})
} else {
let _tokens = tokens.clone();
let uri = if tokens[0].starts_with("urn:ietf:params:scim:schemas:") {
let s = tokens.remove(0);
let uri_attr : Vec<String> = s.rsplitn(2, ':')
.map(|s| s.to_string())
.collect();
tokens.insert(0, uri_attr[0].clone());
Some(uri_attr[1].clone())
} else {
None
};
if tokens.get(0).is_none() {
Err(ScimFilterError {
message: format!("Invalid attrPath: Insufficient tokens"),
rest: _tokens,
})
} else if tokens[0].contains('.') { // With sub_attr
let attr_sub : Vec<String> = tokens[0].splitn(2, '.')
.map(|s| s.to_string())
.collect();
tokens[0] = attr_sub[0].clone();
tokens.insert(1, attr_sub[1].clone());
let attr = try_retain!(ATTRNAME(tokens), _tokens);
let (rest, sub_done) = match ATTRNAME(attr.rest) {
Ok(sub_attr) => (sub_attr.rest, Some(sub_attr.done)),
Err(err) => (err.rest, None),
};
Ok(Done {
rest: rest,
done: AttrPath {
uri: uri,
attr: attr.done,
sub_attr: sub_done,
},
})
} else {
let attr = try_retain!(ATTRNAME(tokens), _tokens);
Ok(Done {
rest: attr.rest,
done: AttrPath {
uri: uri,
attr: attr.done,
sub_attr: None,
},
})
}
}
}
fn ATTRNAME(mut tokens: Vec<String>) -> ScimFilterResult<Done<String>> {
lazy_static! {
static ref RE: Regex = Regex::new(r"^[a-zA-Z][a-zA-Z0-9_-]*$").unwrap();
}
if tokens.is_empty() {
Err(ScimFilterError {
message: format!("invalid ATTRNAME: tokens is empty"),
rest: tokens,
})
} else {
if RE.is_match(&tokens[0]) {
let s = tokens.remove(0);
Ok(Done {
rest: tokens,
done: s,
})
} else {
Err(ScimFilterError {
message: format!("Invalid ATTRNAME: \"{}\"", tokens[0]),
rest: tokens,
})
}
}
}
fn tokenize(s: &str) -> Vec<String> {
s.replace("(", " ( ")
.replace(")", " ) ")
.split_whitespace()
.map(|s| s.to_string())
.collect()
}
#[test]
fn test_FILTER() {
let test_cases = [
/* NOTE: These test cases are not readable for narrow displays */
("userName eq \"bjensen\"",
Filter::Singular(AttrExp::Eq(AttrPath { uri: None, attr: format!("userName"), sub_attr: None },
CompValue::Str(format!("bjensen"))))
),
("userName sw \"J\"",
Filter::Singular(AttrExp::Sw(AttrPath { uri: None, attr: format!("userName"), sub_attr: None },
CompValue::Str(format!("J"))))
),
("urn:ietf:params:scim:schemas:core:2.0:User:userName sw \"J\"",
Filter::Singular(AttrExp::Sw(AttrPath { uri: Some(format!("urn:ietf:params:scim:schemas:core:2.0:User")), attr: format!("userName"), sub_attr: None },
CompValue::Str(format!("J"))))
),
("title pr",
Filter::Singular(AttrExp::Pr(AttrPath { uri: None, attr: format!("title"), sub_attr: None }))
),
("meta.lastModified gt \"2011-05-13T04:42:34Z\"",
Filter::Singular(AttrExp::Gt(AttrPath { uri: None, attr: format!("meta"), sub_attr: Some(format!("lastModified")) },
CompValue::Str(format!("2011-05-13T04:42:34Z"))))
),
("meta.lastModified ge \"2011-05-13T04:42:34Z\"",
Filter::Singular(AttrExp::Ge(AttrPath { uri: None, attr: format!("meta"), sub_attr: Some(format!("lastModified")) },
CompValue::Str(format!("2011-05-13T04:42:34Z"))))
),
("meta.lastModified lt \"2011-05-13T04:42:34Z\"",
Filter::Singular(AttrExp::Lt(AttrPath { uri: None, attr: format!("meta"), sub_attr: Some(format!("lastModified")) },
CompValue::Str(format!("2011-05-13T04:42:34Z"))))
),
("meta.lastModified le \"2011-05-13T04:42:34Z\"",
Filter::Singular(AttrExp::Le(AttrPath { uri: None, attr: format!("meta"), sub_attr: Some(format!("lastModified")) },
CompValue::Str(format!("2011-05-13T04:42:34Z"))))
),
("title pr and userType eq \"Employee\"",
Filter::And(Box::new(Filter::Singular(AttrExp::Pr(AttrPath { uri: None, attr: format!("title"), sub_attr: None }))),
Box::new(Filter::Singular(AttrExp::Eq(AttrPath { uri: None, attr: format!("userType"), sub_attr: None },
CompValue::Str(format!("Employee"))))))
),
("title pr or userType eq \"Intern\"",
Filter::Or(Box::new(Filter::Singular(AttrExp::Pr(AttrPath { uri: None, attr: format!("title"), sub_attr: None }))),
Box::new(Filter::Singular(AttrExp::Eq(AttrPath { uri: None, attr: format!("userType"), sub_attr: None },
CompValue::Str(format!("Intern"))))))
),
("userType eq \"Employee\" and (emails co \"example.com\" or emails.value co \"example.org\")",
Filter::And(Box::new(Filter::Singular(AttrExp::Eq(AttrPath { uri: None, attr: format!("userType"), sub_attr: None },
CompValue::Str(format!("Employee"))))),
Box::new(Filter::Or(Box::new(Filter::Singular(AttrExp::Co(AttrPath { uri: None, attr: format!("emails"), sub_attr: None },
CompValue::Str(format!("example.com"))))),
Box::new(Filter::Singular(AttrExp::Co(AttrPath { uri: None, attr: format!("emails"), sub_attr: Some(format!("value")) },
CompValue::Str(format!("example.org"))))))))
),
("userType eq \"Employee\" and (emails.type eq \"work\")",
Filter::And(Box::new(Filter::Singular(AttrExp::Eq(AttrPath { uri: None, attr: format!("userType"), sub_attr: None },
CompValue::Str(format!("Employee"))))),
Box::new(Filter::Singular(AttrExp::Eq(AttrPath { uri: None, attr: format!("emails"), sub_attr: Some(format!("type")) },
CompValue::Str(format!("work"))))))
),
];
for case in test_cases.iter() {
assert_eq!(FILTER(tokenize(case.0)).unwrap().done, case.1);
}
}
#[test]
fn test_attrExp() {
let expect1_attr = AttrPath {
uri: None,
attr: format!("userName"),
sub_attr: None,
};
let expect1_val = CompValue::Str(format!("john"));
let expect2_attr = AttrPath {
uri: None,
attr: format!("title"),
sub_attr: None,
};
assert_eq!(attrExp(tokenize("userName eq \"john\"")).unwrap().done,
AttrExp::Eq(expect1_attr, expect1_val));
assert_eq!(attrExp(tokenize("title pr")).unwrap().done,
AttrExp::Pr(expect2_attr));
}
#[test]
fn test_compValue() {
assert_eq!(compValue(tokenize("true")).unwrap().done, CompValue::True);
assert_eq!(compValue(tokenize("false")).unwrap().done, CompValue::False);
assert_eq!(compValue(tokenize("null")).unwrap().done, CompValue::Null);
assert_eq!(compValue(tokenize("0.2e+5")).unwrap().done, CompValue::Num(0.2e+5));
assert_eq!(compValue(tokenize("\"john\"")).unwrap().done, CompValue::Str(format!("john")));
}
#[test]
fn test_attrPath() {
assert_eq!(attrPath(tokenize("userName")).unwrap().done, AttrPath {
uri: None,
attr: format!("userName"),
sub_attr: None,
});
assert_eq!(attrPath(tokenize("name.givenName")).unwrap().done, AttrPath {
uri: None,
attr: format!("name"),
sub_attr: Some(format!("givenName")),
});
assert_eq!(attrPath(tokenize("urn:ietf:params:scim:schemas:core:2.0:User:userName")).unwrap().done, AttrPath {
uri: Some(format!("urn:ietf:params:scim:schemas:core:2.0:User")),
attr: format!("userName"),
sub_attr: None,
});
assert_eq!(attrPath(tokenize("urn:ietf:params:scim:schemas:core:2.0:User:emails.value")).unwrap().done, AttrPath {
uri: Some(format!("urn:ietf:params:scim:schemas:core:2.0:User")),
attr: format!("emails"),
sub_attr: Some(format!("value")),
});
}
#[test]
fn test_ATTRNAME() {
assert_eq!(ATTRNAME(tokenize("a b c d\t\nk")).unwrap().done, format!("a"));
assert_eq!(ATTRNAME(tokenize("abc ! c d\t\nk")).unwrap().done, format!("abc"));
assert_eq!(ATTRNAME(tokenize("a-bc ! c d\t\nk")).unwrap().done, format!("a-bc"));
assert_eq!(ATTRNAME(tokenize("a_bc ! c d\t\nk")).unwrap().done, format!("a_bc"));
assert_eq!(ATTRNAME(tokenize("a1bc ! c d\t\nk")).unwrap().done, format!("a1bc"));
assert!(ATTRNAME(tokenize("1abc ! c d\t\nk")).is_err())
}
#[test]
fn test_tokenize() {
macro_rules! vec_str {
( $( $e:expr ),* ) => {
vec![$( $e.to_string() ),*]
};
}
assert_eq!(tokenize("a b c d\t\nk"), vec_str!["a", "b", "c", "d", "k"]);
assert_eq!(tokenize("(a b) c d\t\nk"), vec_str!["(", "a", "b", ")", "c", "d", "k"]);
}
|
#![allow(dead_code)]
mod colors;
mod components;
mod config;
mod contour;
mod extensions;
mod grid;
mod prelude;
mod snapshot;
use std::env;
use prelude::*;
fn main() {
nannou::app(start).update(update).exit(snapshot::exit).run();
}
fn start(app: &App) -> Model {
let config_params = config::load();
let is_animated = env::args().any(|argument| argument == "--animate");
let is_still = !is_animated;
if is_still {
app.set_loop_mode(LoopMode::loop_ntimes(1));
}
let mut window_builder = app
.new_window()
.view(draw)
.size(config_params.width, config_params.height)
// .max_size(10_000, 10_000)
// .maximized(true)
.decorations(false);
if is_animated {
window_builder = window_builder.key_released(capture_frame_on_s);
}
window_builder.build().unwrap();
let mut snapshot = snapshot::save();
if is_still {
snapshot.capture_frame(app);
}
let rand = snapshot.get_rand();
let main_window = app.main_window().rect();
let container = main_window
.clone()
.scale(config_params.scale, config_params.scale);
let artwork_params = components::artwork::Params {
app,
rand,
container,
};
Model {
snapshot,
root_component: components::artwork::new(artwork_params),
container,
}
}
fn update(_app: &App, _model: &mut Model, _update: Update) {}
pub fn draw(app: &App, model: &Model, frame: Frame) {
let mut rand = model.snapshot.get_rand();
let draw = app.draw();
draw.background().color(soft_white());
let mut params = RenderParams {
app,
model,
rand: &mut rand,
draw: &draw,
container: &model.container,
};
model.root_component.render(&mut params);
draw.to_frame(app, &frame).unwrap();
}
fn capture_frame_on_s(app: &App, model: &mut Model, key: Key) {
if key == Key::S {
model.snapshot.capture_frame(app);
}
}
|
use proc_macro2::TokenStream;
use quote::{quote, ToTokens};
use syn::{
braced,
parse::{Parse, ParseStream, Result},
punctuated::Punctuated,
Ident, ItemEnum, Token, Type,
};
#[derive(Debug, PartialEq)]
pub(crate) struct Event {
pub event_name: Ident,
pub event_type: Type,
}
impl Parse for Event {
/// example event:
///
/// ```text
/// S1 = S1
/// ```
fn parse(input: ParseStream<'_>) -> Result<Self> {
/// S1 = S1
/// __
let event_name: Ident = Ident::parse(input)?;
/// S1 = S1
/// _
let _: Token![=] = input.parse()?;
/// S1 = S1
/// __
let event_type: Type = Type::parse(input)?;
Ok(Event {
event_name,
event_type,
})
}
}
impl ToTokens for Event {
fn to_tokens(&self, tokens: &mut TokenStream) {
let event_name = &self.event_name;
let event_type = &self.event_type;
tokens.extend(quote!(
#event_name(#event_type)
));
}
}
#[derive(Debug, PartialEq)]
pub(crate) struct Events(pub Vec<Event>);
impl Parse for Events {
/// example events:
///
/// ```text
/// Events {
/// S1 = S1,
/// S2 = S2,
/// S3 = S3,
/// S4 = S4,
/// S5 = S5
/// }
/// ```
fn parse(input: ParseStream<'_>) -> Result<Self> {
/// Events { ... }
/// --------------
let events_magic = Ident::parse(input)?;
if events_magic != "Events" {
return Err(input.error("expected Events { ... }"));
}
let content;
braced!(content in input);
let mut transitions: Vec<Event> = Vec::new();
let events: Punctuated<Event, Token![,]> = content.parse_terminated(Event::parse)?;
Ok(Events(events.into_iter().collect()))
}
}
impl ToTokens for Events {
fn to_tokens(&self, tokens: &mut TokenStream) {
let events = &self.0;
tokens.extend(quote!(
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
#(#events),*
}
));
}
}
#[cfg(test)]
mod tests {
use super::*;
use proc_macro2::TokenStream;
use syn::{self, parse_quote};
#[test]
fn test_events_parse_and_to_tokens() {
let events: Events = syn::parse2(quote! {
Events {
E1 = E1
}
})
.unwrap();
let left = quote! {
#[derive(Clone, Debug, PartialEq)]
pub enum Event {
E1(E1)
}
};
let mut right = TokenStream::new();
events.to_tokens(&mut right);
assert_eq!(format!("{}", left), format!("{}", right))
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.