text stringlengths 8 4.13M |
|---|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// run-pass
// Regression test for issue #39984.
//
// The key here is that the error type of the `Ok` call ought to be
// constrained to `String`, even though it is dead-code.
fn main() {}
fn t() -> Result<(), String> {
return Err("".into());
Ok(())
}
|
extern crate iron;
#[macro_use] extern crate mime;
extern crate router;
extern crate urlencoded;
extern crate math_utils;
use math_utils::gcd;
use iron::prelude::*;
use iron::status;
use router::Router;
use urlencoded::UrlEncodedBody;
use std::fs::File;
use std::io::prelude::*;
use std::str::FromStr;
fn main() {
const PORT: u16 = 3000;
let url = format!("localhost:{}", PORT);
let mut router = Router::new();
router.get("/", get_index, "root_get");
router.get("/gcd", get_gcd, "gcd_get");
router.post("/gcd", post_gcd, "gcd_post");
println!("Serving on url {}...", url);
Iron::new(router).http(url)
.expect("failed to start iron server");
}
fn get_index(_request: &mut Request) -> IronResult<Response> {
let mut response = Response::new();
let mut index_html = String::new();
let mut file = File::open("./pages/index.html")
.expect("html to exist on pages folder");
file.read_to_string(&mut index_html).unwrap();
response.set_mut(status::Ok);
response.set_mut(mime!(Text/Html; Charset=Utf8));
response.set_mut(index_html);
Ok(response)
}
fn get_gcd(_request: &mut Request) -> IronResult<Response> {
let mut response = Response::new();
let mut gcd_html = String::new();
let mut file = File::open("./pages/gcd/form.html")
.expect("html to exist on pages folder");
file.read_to_string(&mut gcd_html).unwrap();
response.set_mut(status::Ok);
response.set_mut(mime!(Text/Html; Charset=Utf8));
response.set_mut(gcd_html);
Ok(response)
}
fn post_gcd(request: &mut Request) -> IronResult<Response> {
let mut response = Response::new();
let form_data = match request.get_ref::<UrlEncodedBody>() {
Err(e) => {
response.set_mut(status::BadRequest);
response.set_mut(format!("Error parsing form data: {:?}\n", e));
return Ok(response);
},
Ok(map) => map,
};
let unparsed_numbers = match form_data.get("n") {
None => {
response.set_mut(status::BadRequest);
response.set_mut(format!("form data has no 'n' parameter\n"));
return Ok(response);
},
Some(nums) => nums,
};
let mut numbers = Vec::new();
let mut numbers_str = String::from("");
for unparsed in unparsed_numbers {
match u64::from_str(&unparsed) {
Err(_) => {
response.set_mut(status::BadRequest);
response.set_mut(
format!("Value for 'n' parameter not a number: {:?}\n",
unparsed));
return Ok(response);
},
Ok(n) => {
numbers.push(n);
numbers_str.push_str(unparsed);
numbers_str.push(' ');
},
}
}
let mut d = numbers[0];
for m in &numbers[1..] {
d = gcd(d, *m);
}
let mut gcd_template = String::new();
let mut file = File::open("./pages/gcd/result.template.html")
.expect("html to exist on pages folder");
file.read_to_string(&mut gcd_template).unwrap();
let gcd_template = gcd_template.replace("{:?}", &numbers_str[..]);
let gcd_template = gcd_template.replace("{}", &d.to_string()[..]);
response.set_mut(status::Ok);
response.set_mut(mime!(Text/Html; Charset=Utf8));
response.set_mut(gcd_template);
Ok(response)
}
|
use std::env;
use std::io::{Write};
use std::io::Result as IoResult;
use std::io::{stdout, stderr};
use std::rc::Rc;
use std::cell::RefCell;
use std::iter::Peekable;
use std::slice::Iter;
use std::hash::Hash;
use std::hash::Hasher;
use std::str::FromStr;
use std::process::exit;
#[allow(unused_imports)] #[allow(deprecated)]
use std::ascii::AsciiExt;
use std::collections::HashMap;
use std::collections::hash_map::Entry;
use std::collections::HashSet;
use super::action::{Action, ParseResult};
use super::action::ParseResult::{Parsed, Help, Exit, Error};
use super::action::TypedAction;
use super::action::Action::{Flag, Single, Push, Many};
use super::action::IArgAction;
use super::generic::StoreAction;
use super::help::{HelpAction, wrap_text};
use action::IFlagAction;
use self::ArgumentKind::{Positional, ShortOption, LongOption, Delimiter};
static OPTION_WIDTH: usize = 24;
static TOTAL_WIDTH: usize = 79;
enum ArgumentKind {
Positional,
ShortOption,
LongOption,
Delimiter, // Barely "--"
}
impl ArgumentKind {
fn check(name: &str) -> ArgumentKind {
let mut iter = name.chars();
let char1 = iter.next();
let char2 = iter.next();
let char3 = iter.next();
return match char1 {
Some('-') => match char2 {
Some('-') => match char3 {
Some(_) => LongOption, // --opt
None => Delimiter, // just --
},
Some(_) => ShortOption, // -opts
None => Positional, // single dash
},
Some(_) | None => Positional,
}
}
}
struct GenericArgument<'parser> {
id: usize,
varid: usize,
name: &'parser str,
help: &'parser str,
action: Action<'parser>,
}
struct GenericOption<'parser> {
id: usize,
varid: Option<usize>,
names: Vec<&'parser str>,
help: &'parser str,
action: Action<'parser>,
}
struct EnvVar<'parser> {
varid: usize,
name: &'parser str,
action: Box<IArgAction + 'parser>,
}
impl<'a> Hash for GenericOption<'a> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.id.hash(state);
}
}
impl<'a> PartialEq for GenericOption<'a> {
fn eq(&self, other: &GenericOption<'a>) -> bool {
return self.id == other.id;
}
}
impl<'a> Eq for GenericOption<'a> {}
impl<'a> Hash for GenericArgument<'a> {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.id.hash(state);
}
}
impl<'a> PartialEq for GenericArgument<'a> {
fn eq(&self, other: &GenericArgument<'a>) -> bool {
return self.id == other.id;
}
}
impl<'a> Eq for GenericArgument<'a> {}
pub struct Var {
id: usize,
metavar: String,
required: bool,
}
impl Hash for Var {
fn hash<H>(&self, state: &mut H) where H: Hasher {
self.id.hash(state);
}
}
impl PartialEq for Var {
fn eq(&self, other: &Var) -> bool {
return self.id == other.id;
}
}
impl Eq for Var {}
struct Context<'ctx, 'parser: 'ctx> {
parser: &'ctx ArgumentParser<'parser>,
set_vars: HashSet<usize>,
list_options: HashMap<Rc<GenericOption<'parser>>, Vec<&'ctx str>>,
list_arguments: HashMap<Rc<GenericArgument<'parser>>, Vec<&'ctx str>>,
arguments: Vec<&'ctx str>,
iter: Peekable<Iter<'ctx, String>>,
stderr: &'ctx mut (Write + 'ctx),
}
impl<'a, 'b> Context<'a, 'b> {
fn parse_option(&mut self, opt: Rc<GenericOption<'b>>,
optarg: Option<&'a str>)
-> ParseResult
{
let value = match optarg {
Some(value) => value,
None => match self.iter.next() {
Some(value) => {
&value[..]
}
None => {
return match opt.action {
Many(_) => Parsed,
_ => Error(format!(
// TODO(tailhook) is {:?} ok?
"Option {:?} requires an argument", opt.names)),
};
}
},
};
match opt.varid {
Some(varid) => { self.set_vars.insert(varid); }
None => {}
}
match opt.action {
Single(ref action) => {
return action.parse_arg(value);
}
Push(_) => {
(match self.list_options.entry(opt.clone()) {
Entry::Occupied(occ) => occ.into_mut(),
Entry::Vacant(vac) => vac.insert(Vec::new()),
}).push(value);
return Parsed;
}
Many(_) => {
let vec = match self.list_options.entry(opt.clone()) {
Entry::Occupied(occ) => occ.into_mut(),
Entry::Vacant(vac) => vac.insert(Vec::new()),
};
vec.push(value);
match optarg {
Some(_) => return Parsed,
_ => {}
}
loop {
match self.iter.peek() {
None => { break; }
Some(arg) if arg.starts_with('-') => {
break;
}
Some(value) => {
vec.push(&value[..]);
}
}
self.iter.next();
}
return Parsed;
}
_ => panic!(),
};
}
fn parse_long_option(&mut self, arg: &'a str) -> ParseResult {
let mut equals_iter = arg.splitn(2, '=');
let optname = equals_iter.next().unwrap();
let valueref = equals_iter.next();
let opt = self.parser.long_options.get(&optname.to_string());
match opt {
Some(opt) => {
match opt.action {
Flag(ref action) => {
match valueref {
Some(_) => {
return Error(format!(
"Option {} does not accept an argument",
optname));
}
None => {
match opt.varid {
Some(varid) => {
self.set_vars.insert(varid);
}
None => {}
}
return action.parse_flag();
}
}
}
Single(_) | Push(_) | Many(_) => {
return self.parse_option(opt.clone(), valueref);
}
}
}
None => {
return Error(format!("Unknown option {}", arg));
}
}
}
fn parse_short_options<'x>(&'x mut self, arg: &'a str) -> ParseResult {
let mut iter = arg.char_indices();
iter.next();
for (idx, ch) in iter {
let opt = match self.parser.short_options.get(&ch) {
Some(opt) => { opt }
None => {
return Error(format!("Unknown short option \"{}\"", ch));
}
};
let res = match opt.action {
Flag(ref action) => {
match opt.varid {
Some(varid) => { self.set_vars.insert(varid); }
None => {}
}
action.parse_flag()
}
Single(_) | Push(_) | Many(_) => {
let value;
if idx + 1 < arg.len() {
value = Some(&arg[idx+1..arg.len()]);
} else {
value = None;
}
return self.parse_option(opt.clone(), value);
}
};
match res {
Parsed => { continue; }
x => { return x; }
}
}
return Parsed;
}
fn postpone_argument(&mut self, arg: &'a str) {
self.arguments.push(arg);
}
fn parse_options(&mut self) -> ParseResult {
self.iter.next(); // Command name
loop {
let next = self.iter.next();
let arg = match next {
Some(arg) => { arg }
None => { break; }
};
let res = match ArgumentKind::check(&arg[..]) {
Positional => {
self.postpone_argument(&arg[..]);
if self.parser.stop_on_first_argument {
break;
}
continue;
}
LongOption => self.parse_long_option(&arg[..]),
ShortOption => self.parse_short_options(&arg[..]),
Delimiter => {
if !self.parser.silence_double_dash {
self.postpone_argument("--");
}
break;
}
};
match res {
Parsed => continue,
_ => return res,
}
}
loop {
match self.iter.next() {
None => break,
Some(arg) => self.postpone_argument(&arg[..]),
}
}
return Parsed;
}
fn parse_arguments(&mut self) -> ParseResult {
let mut pargs = self.parser.arguments.iter();
for arg in self.arguments.iter() {
let opt;
loop {
match pargs.next() {
Some(option) => {
if self.set_vars.contains(&option.varid) {
continue;
}
opt = option;
break;
}
None => match self.parser.catchall_argument {
Some(ref option) => {
opt = option;
break;
}
None => return Error(format!(
"Unexpected argument {}", arg)),
}
};
}
let res = match opt.action {
Single(ref act) => {
self.set_vars.insert(opt.varid);
act.parse_arg(*arg)
},
Many(_) | Push(_) => {
(match self.list_arguments.entry(opt.clone()) {
Entry::Occupied(occ) => occ.into_mut(),
Entry::Vacant(vac) => vac.insert(Vec::new()),
}).push(*arg);
Parsed
},
_ => unreachable!(),
};
match res {
Parsed => continue,
_ => return res,
}
}
return Parsed;
}
fn parse_list_vars(&mut self) -> ParseResult {
for (opt, lst) in self.list_options.iter() {
match opt.action {
Push(ref act) | Many(ref act) => {
let res = act.parse_args(&lst[..]);
match res {
Parsed => continue,
_ => return res,
}
}
_ => panic!(),
}
}
for (opt, lst) in self.list_arguments.iter() {
match opt.action {
Push(ref act) | Many(ref act) => {
let res = act.parse_args(&lst[..]);
match res {
Parsed => continue,
_ => return res,
}
}
_ => panic!(),
}
}
return Parsed;
}
fn parse_env_vars(&mut self) -> ParseResult {
for evar in self.parser.env_vars.iter() {
match env::var(evar.name) {
Ok(val) => {
match evar.action.parse_arg(&val[..]) {
Parsed => {
self.set_vars.insert(evar.varid);
continue;
}
Error(err) => {
writeln!(self.stderr,
"WARNING: Environment variable {}: {}",
evar.name, err).ok();
}
_ => unreachable!(),
}
}
Err(_) => {}
}
}
return Parsed;
}
fn check_required(&mut self) -> ParseResult {
// Check for required arguments
for var in self.parser.vars.iter() {
if var.required && !self.set_vars.contains(&var.id) {
// First try positional arguments
for opt in self.parser.arguments.iter() {
if opt.varid == var.id {
return Error(format!(
"Argument {} is required", opt.name));
}
}
// Then options
let mut all_options = vec!();
for opt in self.parser.options.iter() {
match opt.varid {
Some(varid) if varid == var.id => {}
_ => { continue }
}
all_options.extend(opt.names.clone().into_iter());
}
if all_options.len() > 1 {
return Error(format!(
"One of the options {:?} is required", all_options));
} else if all_options.len() == 1 {
return Error(format!(
"Option {:?} is required", all_options));
}
// Then envvars
for envvar in self.parser.env_vars.iter() {
if envvar.varid == var.id {
return Error(format!(
"Environment var {} is required", envvar.name));
}
}
}
}
return Parsed;
}
fn parse(parser: &ArgumentParser, args: &Vec<String>, stderr: &mut Write)
-> ParseResult
{
let mut ctx = Context {
parser: parser,
iter: args.iter().peekable(),
set_vars: HashSet::new(),
list_options: HashMap::new(),
list_arguments: HashMap::new(),
arguments: Vec::new(),
stderr: stderr,
};
match ctx.parse_env_vars() {
Parsed => {}
x => { return x; }
}
match ctx.parse_options() {
Parsed => {}
x => { return x; }
}
match ctx.parse_arguments() {
Parsed => {}
x => { return x; }
}
match ctx.parse_list_vars() {
Parsed => {}
x => { return x; }
}
match ctx.check_required() {
Parsed => {}
x => { return x; }
}
return Parsed;
}
}
pub struct Ref<'parser:'refer, 'refer, T: 'parser> {
cell: Rc<RefCell<&'parser mut T>>,
varid: usize,
parser: &'refer mut ArgumentParser<'parser>,
}
impl<'parser, 'refer, T> Ref<'parser, 'refer, T> {
pub fn add_option<'x, A: TypedAction<T>>(&'x mut self,
names: &[&'parser str], action: A, help: &'parser str)
-> &'x mut Ref<'parser, 'refer, T>
{
{
let var = &mut self.parser.vars[self.varid];
if var.metavar.is_empty() {
let mut longest_name = names[0];
let mut llen = longest_name.len();
for name in names.iter() {
if name.len() > llen {
longest_name = *name;
llen = longest_name.len();
}
}
if llen > 2 {
var.metavar = longest_name[2..llen]
.to_ascii_uppercase().replace("-", "_");
}
}
}
self.parser.add_option_for(Some(self.varid), names,
action.bind(self.cell.clone()),
help);
return self;
}
pub fn add_argument<'x, A: TypedAction<T>>(&'x mut self,
name: &'parser str, action: A, help: &'parser str)
-> &'x mut Ref<'parser, 'refer, T>
{
let act = action.bind(self.cell.clone());
let opt = Rc::new(GenericArgument {
id: self.parser.arguments.len(),
varid: self.varid,
name: name,
help: help,
action: act,
});
match opt.action {
Flag(_) => panic!("Flag arguments can't be positional"),
Many(_) | Push(_) => {
match self.parser.catchall_argument {
Some(ref y) => panic!(format!(
"Option {} conflicts with option {}",
name, y.name)),
None => {},
}
self.parser.catchall_argument = Some(opt);
}
Single(_) => {
self.parser.arguments.push(opt);
}
}
{
let var = &mut self.parser.vars[self.varid];
if var.metavar.is_empty() {
var.metavar = name.to_string();
}
}
return self;
}
pub fn metavar<'x>(&'x mut self, name: &str)
-> &'x mut Ref<'parser, 'refer, T>
{
{
let var = &mut self.parser.vars[self.varid];
var.metavar = name.to_string();
}
return self;
}
pub fn required<'x>(&'x mut self)
-> &'x mut Ref<'parser, 'refer, T>
{
{
let var = &mut self.parser.vars[self.varid];
var.required = true;
}
return self;
}
}
impl<'parser, 'refer, T: 'static + FromStr> Ref<'parser, 'refer, T> {
pub fn envvar<'x>(&'x mut self, varname: &'parser str)
-> &'x mut Ref<'parser, 'refer, T>
{
self.parser.env_vars.push(Rc::new(EnvVar {
varid: self.varid,
name: varname,
action: Box::new(StoreAction { cell: self.cell.clone() }),
}));
return self;
}
}
/// The main argument parser class
pub struct ArgumentParser<'parser> {
description: &'parser str,
vars: Vec<Box<Var>>,
options: Vec<Rc<GenericOption<'parser>>>,
arguments: Vec<Rc<GenericArgument<'parser>>>,
env_vars: Vec<Rc<EnvVar<'parser>>>,
catchall_argument: Option<Rc<GenericArgument<'parser>>>,
short_options: HashMap<char, Rc<GenericOption<'parser>>>,
long_options: HashMap<String, Rc<GenericOption<'parser>>>,
stop_on_first_argument: bool,
silence_double_dash: bool,
}
impl<'parser> ArgumentParser<'parser> {
/// Create an empty argument parser
pub fn new() -> ArgumentParser<'parser> {
let mut ap = ArgumentParser {
description: "",
vars: Vec::new(),
env_vars: Vec::new(),
arguments: Vec::new(),
catchall_argument: None,
options: Vec::new(),
short_options: HashMap::new(),
long_options: HashMap::new(),
stop_on_first_argument: false,
silence_double_dash: true,
};
ap.add_option_for(None, &["-h", "--help"], Flag(Box::new(HelpAction)),
"Show this help message and exit");
return ap;
}
/// Borrow mutable variable for an argument
///
/// This returns `Ref` object which should be used configure the option
pub fn refer<'x, T>(&'x mut self, val: &'parser mut T)
-> Box<Ref<'parser, 'x, T>>
{
let cell = Rc::new(RefCell::new(val));
let id = self.vars.len();
self.vars.push(Box::new(Var {
id: id,
required: false,
metavar: "".to_string(),
}));
return Box::new(Ref {
cell: cell.clone(),
varid: id,
parser: self,
});
}
/// Add option to argument parser
///
/// This is only useful for options that don't store value. For
/// example `Print(...)`
pub fn add_option<F:IFlagAction + 'parser>(&mut self,
names: &[&'parser str], action: F, help: &'parser str)
{
self.add_option_for(None, names, Flag(Box::new(action)), help);
}
/// Set description of the command
pub fn set_description(&mut self, descr: &'parser str) {
self.description = descr;
}
fn add_option_for(&mut self, var: Option<usize>,
names: &[&'parser str],
action: Action<'parser>, help: &'parser str)
{
let opt = Rc::new(GenericOption {
id: self.options.len(),
varid: var,
names: names.to_vec(),
help: help,
action: action,
});
if names.is_empty() {
panic!("At least one name for option must be specified");
}
for nameptr in names.iter() {
let name = *nameptr;
match ArgumentKind::check(name) {
Positional|Delimiter => {
panic!("Bad argument name {}", name);
}
LongOption => {
self.long_options.insert(
name.to_string(), opt.clone());
}
ShortOption => {
if name.len() > 2 {
panic!("Bad short argument {}", name);
}
self.short_options.insert(
name.as_bytes()[1] as char, opt.clone());
}
}
}
self.options.push(opt);
}
/// Print help
///
/// Usually command-line option is used for printing help,
/// this is here for any awkward cases
pub fn print_help(&self, name: &str, writer: &mut Write) -> IoResult<()> {
return HelpFormatter::print_help(self, name, writer);
}
/// Print usage
///
/// Usually printed into stderr on error of command-line parsing
pub fn print_usage(&self, name: &str, writer: &mut Write) -> IoResult<()>
{
return HelpFormatter::print_usage(self, name, writer);
}
/// Parse arguments
///
/// This is most powerful method. Usually you need `parse_args`
/// or `parse_args_or_exit` instead
pub fn parse(&self, args: Vec<String>,
stdout: &mut Write, stderr: &mut Write)
-> Result<(), i32>
{
let name = if !args.is_empty() { &args[0][..] } else { "unknown" };
match Context::parse(self, &args, stderr) {
Parsed => return Ok(()),
Exit => return Err(0),
Help => {
self.print_help(name, stdout).unwrap();
return Err(0);
}
Error(message) => {
self.error(&name[..], &message[..], stderr);
return Err(2);
}
}
}
/// Write an error similar to one produced by the library itself
///
/// Only needed if you like to do some argument validation that is out
/// of scope of the argparse
pub fn error(&self, command: &str, message: &str, writer: &mut Write) {
self.print_usage(command, writer).unwrap();
writeln!(writer, "{}: {}", command, message).ok();
}
/// Configure parser to ignore options when first non-option argument is
/// encountered.
///
/// Useful for commands that want to pass following options to the
/// subcommand or subprocess, but need some options to be set before
/// command is specified.
pub fn stop_on_first_argument(&mut self, want_stop: bool) {
self.stop_on_first_argument = want_stop;
}
/// Do not put double-dash (bare `--`) into argument
///
/// The double-dash is used to stop parsing options and treat all the
/// following tokens as the arguments regardless of whether they start
/// with dash (minus) or not.
///
/// The method only useful for `List` arguments. On by default. The method
/// allows to set option to `false` so that `cmd xx -- yy` will get
/// ``xx -- yy`` as arguments instead of ``xx yy`` by default. This is
/// useful if your ``--`` argument is meaningful. Only first double-dash
/// is ignored by default.
pub fn silence_double_dash(&mut self, silence: bool) {
self.silence_double_dash = silence;
}
/// Convenience method to parse arguments
///
/// On error returns error code that is supposed to be returned by
/// an application. (i.e. zero on `--help` and `2` on argument error)
pub fn parse_args(&self) -> Result<(), i32> {
// TODO(tailhook) can we get rid of collect?
return self.parse(env::args().collect(),
&mut stdout(), &mut stderr());
}
/// The simplest conveninece method
///
/// The method returns only in case of successful parsing or exits with
/// appropriate code (including successful on `--help`) otherwise.
pub fn parse_args_or_exit(&self) {
// TODO(tailhook) can we get rid of collect?
self.parse(env::args().collect(), &mut stdout(), &mut stderr())
.map_err(|c| exit(c))
.ok();
}
}
struct HelpFormatter<'a, 'b: 'a> {
name: &'a str,
parser: &'a ArgumentParser<'b>,
buf: &'a mut (Write + 'a),
}
impl<'a, 'b> HelpFormatter<'a, 'b> {
pub fn print_usage(parser: &ArgumentParser, name: &str, writer: &mut Write)
-> IoResult<()>
{
return HelpFormatter { parser: parser, name: name, buf: writer }
.write_usage();
}
pub fn print_help(parser: &ArgumentParser, name: &str, writer: &mut Write)
-> IoResult<()>
{
return HelpFormatter { parser: parser, name: name, buf: writer }
.write_help();
}
pub fn print_argument(&mut self, arg: &GenericArgument<'b>)
-> IoResult<()>
{
let mut num = 2;
try!(write!(self.buf, " {}", arg.name));
num += arg.name.len();
if num >= OPTION_WIDTH {
try!(write!(self.buf, "\n"));
for _ in 0..OPTION_WIDTH {
try!(write!(self.buf, " "));
}
} else {
for _ in num..OPTION_WIDTH {
try!(write!(self.buf, " "));
}
}
try!(wrap_text(self.buf, arg.help, TOTAL_WIDTH, OPTION_WIDTH));
try!(write!(self.buf, "\n"));
return Ok(());
}
pub fn print_option(&mut self, opt: &GenericOption<'b>) -> IoResult<()> {
let mut num = 2;
try!(write!(self.buf, " "));
let mut niter = opt.names.iter();
let name = niter.next().unwrap();
try!(write!(self.buf, "{}", name));
num += name.len();
for name in niter {
try!(write!(self.buf, ","));
try!(write!(self.buf, "{}", name));
num += name.len() + 1;
}
match opt.action {
Flag(_) => {}
Single(_) | Push(_) | Many(_) => {
try!(write!(self.buf, " "));
let var = &self.parser.vars[opt.varid.unwrap()];
try!(write!(self.buf, "{}", &var.metavar[..]));
num += var.metavar.len() + 1;
}
}
if num >= OPTION_WIDTH {
try!(write!(self.buf, "\n"));
for _ in 0..OPTION_WIDTH {
try!(write!(self.buf, " "));
}
} else {
for _ in num..OPTION_WIDTH {
try!(write!(self.buf, " "));
}
}
try!(wrap_text(self.buf, opt.help, TOTAL_WIDTH, OPTION_WIDTH));
try!(write!(self.buf, "\n"));
return Ok(());
}
fn write_help(&mut self) -> IoResult<()> {
try!(self.write_usage());
try!(write!(self.buf, "\n"));
if !self.parser.description.is_empty() {
try!(wrap_text(self.buf, self.parser.description,TOTAL_WIDTH, 0));
try!(write!(self.buf, "\n"));
}
if !self.parser.arguments.is_empty()
|| self.parser.catchall_argument.is_some()
{
try!(write!(self.buf, "\nPositional arguments:\n"));
for arg in self.parser.arguments.iter() {
try!(self.print_argument(&**arg));
}
match self.parser.catchall_argument {
Some(ref opt) => {
try!(self.print_argument(&**opt));
}
None => {}
}
}
if !self.parser.short_options.is_empty()
|| !self.parser.long_options.is_empty()
{
try!(write!(self.buf, "\nOptional arguments:\n"));
for opt in self.parser.options.iter() {
try!(self.print_option(&**opt));
}
}
return Ok(());
}
fn write_usage(&mut self) -> IoResult<()> {
try!(write!(self.buf, "Usage:\n "));
try!(write!(self.buf, "{}", self.name));
if !self.parser.options.is_empty() {
if self.parser.short_options.len() > 1
|| self.parser.long_options.len() > 1
{
try!(write!(self.buf, " [OPTIONS]"));
}
for opt in self.parser.arguments.iter() {
let var = &self.parser.vars[opt.varid];
try!(write!(self.buf, " "));
if !var.required {
try!(write!(self.buf, "["));
}
try!(write!(self.buf, "{}",
&opt.name.to_ascii_uppercase()[..]));
if !var.required {
try!(write!(self.buf, "]"));
}
}
match self.parser.catchall_argument {
Some(ref opt) => {
let var = &self.parser.vars[opt.varid];
try!(write!(self.buf, " "));
if !var.required {
try!(write!(self.buf, "["));
}
try!(write!(self.buf, "{}",
&opt.name.to_ascii_uppercase()[..]));
if !var.required {
try!(write!(self.buf, " ...]"));
} else {
try!(write!(self.buf, " [...]"));
}
}
None => {}
}
}
try!(write!(self.buf, "\n"));
return Ok(());
}
}
|
use anyhow::Result;
use std::str::FromStr;
use tracing::Level;
use tracing_subscriber::FmtSubscriber;
pub fn init<'a>(level: impl Into<Option<&'a str>>) -> Result<()> {
let level = match level.into() {
Some(l) => Level::from_str(l)?,
None => Level::INFO,
};
let subscriber = FmtSubscriber::builder().with_max_level(level).finish();
tracing::subscriber::set_global_default(subscriber)?;
Ok(())
}
|
pub mod node_type;
pub mod node;
pub mod string_node;
pub mod bind_node;
pub mod choose_node;
pub mod foreach_node;
pub mod if_node;
pub mod include_node;
pub mod otherwise_node;
pub mod trim_node;
pub mod when_node;
pub mod set_node;
pub mod where_node;
pub mod sql_node;
pub mod insert_node;
pub mod update_node;
pub mod delete_node;
pub mod select_node;
pub mod result_map_node;
pub mod result_map_id_node;
pub mod result_map_result_node; |
use crate::{
ray::Ray,
rtweekend::{fmax, fmin},
vec3::Point3,
};
use std::mem::swap;
#[derive(Clone)]
pub struct AABB {
pub _min: Point3,
pub _max: Point3,
}
impl AABB {
pub fn new(mi: Point3, ma: Point3) -> Self {
Self { _min: mi, _max: ma }
}
pub fn surrounding_box(box0: &AABB, box1: &AABB) -> Self {
let small = Point3::new(
fmin(box0._min.x, box1._min.x),
fmin(box0._min.y, box1._min.y),
fmin(box0._min.z, box1._min.z),
);
let big = Point3::new(
fmax(box0._max.x, box1._max.x),
fmax(box0._max.y, box1._max.y),
fmax(box0._max.z, box1._max.z),
);
Self {
_min: small,
_max: big,
}
}
pub fn hit(&self, r: &Ray, tmin: f64, tmax: f64) -> bool {
for a in 0..3 {
let inv_d = 1.0 / r.dir[a];
let mut t0 = (self._min[a] - r.orig[a]) * inv_d;
let mut t1 = (self._max[a] - r.orig[a]) * inv_d;
if inv_d < 0.0 {
swap(&mut t0, &mut t1);
}
t0 = if t0 > tmin { t0 } else { tmin };
t1 = if t1 < tmax { t1 } else { tmax };
if t1 <= t0 {
return false;
}
}
true
}
}
|
//! Runtime modules.
use std::{
collections::{BTreeMap, BTreeSet},
fmt::Debug,
};
use impl_trait_for_tuples::impl_for_tuples;
use crate::{
context::{Context, TxContext},
dispatcher, error,
error::Error as _,
event, modules, storage,
storage::{Prefix, Store},
types::{
message::MessageResult,
transaction::{
self, AuthInfo, Call, Transaction, TransactionWeight, UnverifiedTransaction,
},
},
};
/// Result of invoking the method handler.
pub enum DispatchResult<B, R> {
Handled(R),
Unhandled(B),
}
impl<B, R> DispatchResult<B, R> {
/// Transforms `DispatchResult<B, R>` into `Result<R, E>`, mapping `Handled(r)` to `Ok(r)` and
/// `Unhandled(_)` to `Err(err)`.
pub fn ok_or<E>(self, err: E) -> Result<R, E> {
match self {
DispatchResult::Handled(result) => Ok(result),
DispatchResult::Unhandled(_) => Err(err),
}
}
/// Transforms `DispatchResult<B, R>` into `Result<R, E>`, mapping `Handled(r)` to `Ok(r)` and
/// `Unhandled(_)` to `Err(err)` using the provided function.
pub fn ok_or_else<E, F: FnOnce() -> E>(self, errf: F) -> Result<R, E> {
match self {
DispatchResult::Handled(result) => Ok(result),
DispatchResult::Unhandled(_) => Err(errf()),
}
}
}
/// A variant of `types::transaction::CallResult` but used for dispatch purposes so the dispatch
/// process can use a different representation.
///
/// Specifically, this type is not serializable.
#[derive(Debug)]
pub enum CallResult {
/// Call has completed successfully.
Ok(cbor::Value),
/// Call has completed with failure.
Failed {
module: String,
code: u32,
message: String,
},
/// A fatal error has occurred and the batch must be aborted.
Aborted(dispatcher::Error),
}
impl CallResult {
/// Check whether the call result indicates a successful operation or not.
pub fn is_success(&self) -> bool {
matches!(self, CallResult::Ok(_))
}
}
impl From<CallResult> for transaction::CallResult {
fn from(v: CallResult) -> Self {
match v {
CallResult::Ok(data) => Self::Ok(data),
CallResult::Failed {
module,
code,
message,
} => Self::Failed {
module,
code,
message,
},
CallResult::Aborted(err) => Self::Failed {
module: err.module_name().to_string(),
code: err.code(),
message: err.to_string(),
},
}
}
}
/// A convenience function for dispatching method calls.
pub fn dispatch_call<C, B, R, E, F>(
ctx: &mut C,
body: cbor::Value,
f: F,
) -> DispatchResult<cbor::Value, CallResult>
where
C: TxContext,
B: cbor::Decode,
R: cbor::Encode,
E: error::Error,
F: FnOnce(&mut C, B) -> Result<R, E>,
{
DispatchResult::Handled((|| {
let args = match cbor::from_value(body)
.map_err(|err| modules::core::Error::InvalidArgument(err.into()))
{
Ok(args) => args,
Err(err) => return err.into_call_result(),
};
match f(ctx, args) {
Ok(value) => CallResult::Ok(cbor::to_value(value)),
Err(err) => err.into_call_result(),
}
})())
}
/// A convenience function for dispatching queries.
pub fn dispatch_query<C, B, R, E, F>(
ctx: &mut C,
body: cbor::Value,
f: F,
) -> DispatchResult<cbor::Value, Result<cbor::Value, error::RuntimeError>>
where
C: Context,
B: cbor::Decode,
R: cbor::Encode,
E: error::Error,
error::RuntimeError: From<E>,
F: FnOnce(&mut C, B) -> Result<R, E>,
{
DispatchResult::Handled((|| {
let args = cbor::from_value(body).map_err(|err| -> error::RuntimeError {
modules::core::Error::InvalidArgument(err.into()).into()
})?;
Ok(cbor::to_value(f(ctx, args)?))
})())
}
/// Method handler.
pub trait MethodHandler {
/// Add storage prefixes to prefetch.
fn prefetch(
_prefixes: &mut BTreeSet<Prefix>,
_method: &str,
body: cbor::Value,
_auth_info: &AuthInfo,
) -> DispatchResult<cbor::Value, Result<(), error::RuntimeError>> {
// Default implementation indicates that the call was not handled.
DispatchResult::Unhandled(body)
}
/// Dispatch a call.
fn dispatch_call<C: TxContext>(
_ctx: &mut C,
_method: &str,
body: cbor::Value,
) -> DispatchResult<cbor::Value, CallResult> {
// Default implementation indicates that the call was not handled.
DispatchResult::Unhandled(body)
}
/// Dispatch a query.
fn dispatch_query<C: Context>(
_ctx: &mut C,
_method: &str,
args: cbor::Value,
) -> DispatchResult<cbor::Value, Result<cbor::Value, error::RuntimeError>> {
// Default implementation indicates that the query was not handled.
DispatchResult::Unhandled(args)
}
/// Dispatch a message result.
fn dispatch_message_result<C: Context>(
_ctx: &mut C,
_handler_name: &str,
result: MessageResult,
) -> DispatchResult<MessageResult, ()> {
// Default implementation indicates that the query was not handled.
DispatchResult::Unhandled(result)
}
}
#[impl_for_tuples(30)]
impl MethodHandler for Tuple {
fn prefetch(
prefixes: &mut BTreeSet<Prefix>,
method: &str,
body: cbor::Value,
auth_info: &AuthInfo,
) -> DispatchResult<cbor::Value, Result<(), error::RuntimeError>> {
// Return on first handler that can handle the method.
for_tuples!( #(
let body = match Tuple::prefetch(prefixes, method, body, auth_info) {
DispatchResult::Handled(result) => return DispatchResult::Handled(result),
DispatchResult::Unhandled(body) => body,
};
)* );
DispatchResult::Unhandled(body)
}
fn dispatch_call<C: TxContext>(
ctx: &mut C,
method: &str,
body: cbor::Value,
) -> DispatchResult<cbor::Value, CallResult> {
// Return on first handler that can handle the method.
for_tuples!( #(
let body = match Tuple::dispatch_call::<C>(ctx, method, body) {
DispatchResult::Handled(result) => return DispatchResult::Handled(result),
DispatchResult::Unhandled(body) => body,
};
)* );
DispatchResult::Unhandled(body)
}
fn dispatch_query<C: Context>(
ctx: &mut C,
method: &str,
args: cbor::Value,
) -> DispatchResult<cbor::Value, Result<cbor::Value, error::RuntimeError>> {
// Return on first handler that can handle the method.
for_tuples!( #(
let args = match Tuple::dispatch_query::<C>(ctx, method, args) {
DispatchResult::Handled(result) => return DispatchResult::Handled(result),
DispatchResult::Unhandled(args) => args,
};
)* );
DispatchResult::Unhandled(args)
}
fn dispatch_message_result<C: Context>(
ctx: &mut C,
handler_name: &str,
result: MessageResult,
) -> DispatchResult<MessageResult, ()> {
// Return on first handler that can handle the method.
for_tuples!( #(
let result = match Tuple::dispatch_message_result::<C>(ctx, handler_name, result) {
DispatchResult::Handled(result) => return DispatchResult::Handled(result),
DispatchResult::Unhandled(result) => result,
};
)* );
DispatchResult::Unhandled(result)
}
}
/// Authentication handler.
pub trait AuthHandler {
/// Judge if an unverified transaction is good enough to undergo verification.
/// This takes place before even verifying signatures.
fn approve_unverified_tx<C: Context>(
_ctx: &mut C,
_utx: &UnverifiedTransaction,
) -> Result<(), modules::core::Error> {
// Default implementation doesn't do any checks.
Ok(())
}
/// Decode a transaction that was sent with module-controlled decoding and verify any
/// signatures.
///
/// Postcondition: if returning a Transaction, that transaction must pass `validate_basic`.
///
/// Returns Ok(Some(_)) if the module is in charge of the encoding scheme identified by _scheme
/// or Ok(None) otherwise.
fn decode_tx<C: Context>(
_ctx: &mut C,
_scheme: &str,
_body: &[u8],
) -> Result<Option<Transaction>, modules::core::Error> {
// Default implementation is not in charge of any schemes.
Ok(None)
}
/// Authenticate a transaction.
///
/// Note that any signatures have already been verified.
fn authenticate_tx<C: Context>(
_ctx: &mut C,
_tx: &Transaction,
) -> Result<(), modules::core::Error> {
// Default implementation rejects all transactions.
Err(modules::core::Error::NotAuthenticated)
}
/// Perform any action after authentication, within the transaction context.
fn before_handle_call<C: TxContext>(
_ctx: &mut C,
_call: &Call,
) -> Result<(), modules::core::Error> {
// Default implementation doesn't do anything.
Ok(())
}
}
#[impl_for_tuples(30)]
impl AuthHandler for Tuple {
fn approve_unverified_tx<C: Context>(
ctx: &mut C,
utx: &UnverifiedTransaction,
) -> Result<(), modules::core::Error> {
for_tuples!( #( Tuple::approve_unverified_tx(ctx, utx)?; )* );
Ok(())
}
fn decode_tx<C: Context>(
ctx: &mut C,
scheme: &str,
body: &[u8],
) -> Result<Option<Transaction>, modules::core::Error> {
for_tuples!( #(
let decoded = Tuple::decode_tx(ctx, scheme, body)?;
if (decoded.is_some()) {
return Ok(decoded);
}
)* );
Ok(None)
}
fn authenticate_tx<C: Context>(
ctx: &mut C,
tx: &Transaction,
) -> Result<(), modules::core::Error> {
// Return on first handler that can successfully authenticate the tx,
// skip the ones that return an error (which is also the default
// return value for the authenticate_tx handler).
let mut last_error = modules::core::Error::NotAuthenticated;
for_tuples!( #(
let result = match Tuple::authenticate_tx(ctx, tx) {
Ok(result) => return Ok(result),
Err(modules::core::Error::NotAuthenticated) => {},
Err(result) => last_error = result,
};
)* );
// Return the last error if no handlers were successful.
Err(last_error)
}
fn before_handle_call<C: TxContext>(
ctx: &mut C,
call: &Call,
) -> Result<(), modules::core::Error> {
for_tuples!( #( Tuple::before_handle_call(ctx, call)?; )* );
Ok(())
}
}
/// Migration handler.
pub trait MigrationHandler {
/// Genesis state type.
///
/// If this state is expensive to compute and not often updated, prefer
/// to make the genesis type something like `once_cell::unsync::Lazy<T>`.
type Genesis;
/// Initialize state from genesis or perform a migration.
///
/// Should return true in case metadata has been changed.
fn init_or_migrate<C: Context>(
_ctx: &mut C,
_meta: &mut modules::core::types::Metadata,
_genesis: Self::Genesis,
) -> bool {
// Default implementation doesn't perform any migrations.
false
}
}
#[allow(clippy::type_complexity)]
#[impl_for_tuples(30)]
impl MigrationHandler for Tuple {
for_tuples!( type Genesis = ( #( Tuple::Genesis ),* ); );
fn init_or_migrate<C: Context>(
ctx: &mut C,
meta: &mut modules::core::types::Metadata,
genesis: Self::Genesis,
) -> bool {
[for_tuples!( #( Tuple::init_or_migrate(ctx, meta, genesis.Tuple) ),* )]
.iter()
.any(|x| *x)
}
}
/// Block handler.
pub trait BlockHandler {
/// Perform any common actions at the start of the block (before any transactions have been
/// executed).
fn begin_block<C: Context>(_ctx: &mut C) {
// Default implementation doesn't do anything.
}
/// Perform any common actions at the end of the block (after all transactions have been
/// executed).
fn end_block<C: Context>(_ctx: &mut C) {
// Default implementation doesn't do anything.
}
/// Returns module per-batch weight limits.
fn get_block_weight_limits<C: Context>(_ctx: &mut C) -> BTreeMap<TransactionWeight, u64> {
BTreeMap::new()
}
}
#[impl_for_tuples(30)]
impl BlockHandler for Tuple {
fn begin_block<C: Context>(ctx: &mut C) {
for_tuples!( #( Tuple::begin_block(ctx); )* );
}
fn end_block<C: Context>(ctx: &mut C) {
for_tuples!( #( Tuple::end_block(ctx); )* );
}
// Ignore let and return for the empty tuple case.
#[allow(clippy::let_and_return)]
fn get_block_weight_limits<C: Context>(ctx: &mut C) -> BTreeMap<TransactionWeight, u64> {
let mut result = BTreeMap::new();
for_tuples!( #(
result.extend( Tuple::get_block_weight_limits(ctx) );
)* );
result
}
}
/// Invariant handler.
pub trait InvariantHandler {
/// Check invariants.
fn check_invariants<C: Context>(_ctx: &mut C) -> Result<(), modules::core::Error> {
// Default implementation doesn't do anything.
Ok(())
}
}
#[impl_for_tuples(30)]
impl InvariantHandler for Tuple {
/// Check the invariants in all modules in the tuple.
fn check_invariants<C: Context>(ctx: &mut C) -> Result<(), modules::core::Error> {
for_tuples!( #( Tuple::check_invariants(ctx)?; )* );
Ok(())
}
}
/// A runtime module.
pub trait Module {
/// Module name.
const NAME: &'static str;
/// Module version.
const VERSION: u32 = 1;
/// Module error type.
type Error: error::Error + 'static;
/// Module event type.
type Event: event::Event + 'static;
/// Module parameters.
type Parameters: Parameters + 'static;
/// Return the module's parameters.
fn params<S: Store>(store: S) -> Self::Parameters {
let store = storage::PrefixStore::new(store, &Self::NAME);
let store = storage::TypedStore::new(store);
store.get(Self::Parameters::STORE_KEY).unwrap_or_default()
}
/// Set the module's parameters.
fn set_params<S: Store>(store: S, params: Self::Parameters) {
let store = storage::PrefixStore::new(store, &Self::NAME);
let mut store = storage::TypedStore::new(store);
store.insert(Self::Parameters::STORE_KEY, params);
}
}
/// Parameters for a runtime module.
pub trait Parameters: Debug + Default + cbor::Encode + cbor::Decode {
type Error;
/// Store key used for storing parameters.
const STORE_KEY: &'static [u8] = &[0x00];
/// Perform basic parameter validation.
fn validate_basic(&self) -> Result<(), Self::Error> {
// No validation by default.
Ok(())
}
}
impl Parameters for () {
type Error = std::convert::Infallible;
}
|
use std::{
fs::File,
io,
io::{BufRead, BufReader},
};
pub fn find_two_items_that_sum_2020(input: &[u32]) -> Option<(u32, u32)> {
for i in input {
for j in input {
if i + j == 2020 {
return Some((*i, *j));
}
}
}
None
}
pub fn find_three_items_that_sum_2020(input: &[u32]) -> Option<Vec<u32>> {
for i in input {
for j in input {
for k in input {
if i + j + k == 2020 {
let mut numbers = Vec::new();
numbers.push(*i);
numbers.push(*j);
numbers.push(*k);
return Some(numbers);
}
}
}
}
None
}
pub fn load_input_file(file_name: &str) -> io::Result<Vec<u32>> {
let input = File::open(file_name)?;
let reader = BufReader::new(input);
let mut numbers = Vec::new();
for line in reader.lines() {
let nmb = line
.expect("Gap in input list")
.parse::<u32>()
.expect("Problems parsing");
numbers.push(nmb)
}
Ok(numbers)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_find_items_that_sum_2020() {
let input = [1721, 979, 366, 299, 675, 1456];
assert_eq!(find_two_items_that_sum_2020(&input), Some((1721, 299)))
}
#[test]
fn test_find_items_that_sum_2020_alternate_order() {
let input = [979, 675, 1721, 366, 1456, 299, 1456];
assert_eq!(find_two_items_that_sum_2020(&input), Some((1721, 299)))
}
#[test]
fn test_load_input_file() {
let input = load_input_file("day_1_test.txt").expect("Unable to load the file");
assert_eq!(input, [1472, 1757, 1404])
}
#[test]
fn test_find_three_items_that_sum_2020() {
let input = [1721, 979, 366, 299, 675, 1456];
assert_eq!(
find_three_items_that_sum_2020(&input),
Some(Vec::from([979, 366, 675]))
)
}
}
|
pub const MEMORY_SIZE_MAX: usize = std::i16::MAX as usize;
pub const NUM_OF_REGISTERS: usize = 8; |
extern crate bindgen;
fn osx_version() -> Result<String, std::io::Error> {
use std::process::Command;
let output = Command::new("defaults")
.arg("read")
.arg("loginwindow")
.arg("SystemVersionStampAsString")
.output()?
.stdout;
let version_str = std::str::from_utf8(&output).expect("invalid output from `defaults`");
let version = version_str.trim_right();
Ok(version.to_owned())
}
fn isysroot_path(platform: &str) -> Result<String, std::io::Error> {
use std::process::Command;
let output = Command::new("xcrun")
.arg("--sdk")
.arg(platform)
.arg("--show-sdk-path")
.output()?
.stdout;
let sdk_path =
std::str::from_utf8(&output).expect("invalid output from `xcrun --show-sdk-path`");
let directory = String::from(sdk_path.trim());
println!("SDK Directory: {}", directory);
Ok(directory)
}
fn parse_version(version: &str) -> Option<i32> {
version
.split(".")
.skip(1)
.next()
.and_then(|m| m.parse::<i32>().ok())
}
fn frameworks_path(platform: &str) -> Result<String, std::io::Error> {
// For 10.13 and higher:
//
// While macOS has its system frameworks located at "/System/Library/Frameworks"
// for actually linking against them (especially for cross-compilation) once
// has to refer to the frameworks as found within "Xcode.app/Contents/Developer/…".
if osx_version()
.and_then(|version| Ok(parse_version(&version).map(|v| v >= 13).unwrap_or(false)))
.unwrap_or(false)
{
use std::process::Command;
let output = Command::new("xcode-select").arg("-p").output()?.stdout;
let prefix_str = std::str::from_utf8(&output).expect("invalid output from `xcode-select`");
let prefix = prefix_str.trim_right();
let infix = if prefix == "/Library/Developer/CommandLineTools" {
format!("SDKs/{}.sdk", platform)
} else {
format!(
"Platforms/{}.platform/Developer/SDKs/{}.sdk",
platform, platform
)
};
let suffix = "System/Library/Frameworks";
let directory = format!("{}/{}/{}", prefix, infix, suffix);
Ok(directory)
} else {
Ok("/System/Library/Frameworks".to_string())
}
}
fn build(frameworks_path: &str, sysroot: &str, platform: &str, target: &str) {
// Generate one large set of bindings for all frameworks.
//
// We do this rather than generating a module per framework as some frameworks depend on other
// frameworks and in turn share types. To ensure all types are compatible across each
// framework, we feed all headers to bindgen at once.
//
// Only link to each framework and include their headers if their features are enabled and they
// are available on the target os.
use std::env;
use std::path::PathBuf;
let mut frameworks = vec![];
let mut headers = vec![];
#[cfg(feature = "audio_toolbox")]
{
println!("cargo:rustc-link-lib=framework=AudioToolbox");
frameworks.push("AudioToolbox");
headers.push("AudioToolbox.framework/Headers/AudioToolbox.h");
}
#[cfg(feature = "audio_unit")]
{
println!("cargo:rustc-link-lib=framework=AudioUnit");
frameworks.push("AudioUnit");
headers.push("AudioUnit.framework/Headers/AudioUnit.h");
}
#[cfg(feature = "core_audio")]
{
println!("cargo:rustc-link-lib=framework=CoreAudio");
frameworks.push("CoreAudio");
match platform {
"MacOSX" => headers.push("CoreAudio.framework/Headers/CoreAudio.h"),
"iPhoneOS" | "iPhoneSimulator" => {
headers.push("CoreAudio.framework/Headers/CoreAudioTypes.h")
}
_ => unreachable!(),
}
}
#[cfg(feature = "open_al")]
{
println!("cargo:rustc-link-lib=framework=OpenAL");
frameworks.push("OpenAL");
headers.push("OpenAL.framework/Headers/al.h");
headers.push("OpenAL.framework/Headers/alc.h");
}
#[cfg(all(feature = "core_midi", target_os = "macos"))]
{
if (platform == "MacOSX") {
println!("cargo:rustc-link-lib=framework=CoreMIDI");
frameworks.push("CoreMIDI");
headers.push("CoreMIDI.framework/Headers/CoreMIDI.h");
} else {
panic!("framework CoreMIDI is not supported by Apple on this platform");
}
}
// Get the cargo out directory.
let out_dir = PathBuf::from(env::var("OUT_DIR").expect("env variable OUT_DIR not found"));
// Begin building the bindgen params.
let mut builder = bindgen::Builder::default();
builder = builder
.clang_arg(format!("-F/{}", frameworks_path))
.clang_arg("-isysroot")
.clang_arg(sysroot);
// Add all headers.
for relative_path in headers {
let absolute_path = format!("{}/{}", frameworks_path, relative_path);
builder = builder.header(absolute_path);
}
// Link to all frameworks.
for relative_path in frameworks {
let absolute_path = format!("{}/{}", frameworks_path, relative_path);
builder = builder.link_framework(absolute_path);
}
// Generate the bindings.
let bindings = builder
.clang_arg("-target")
.clang_arg(target)
.trust_clang_mangling(false)
.derive_default(true)
.rustfmt_bindings(false)
.generate()
.expect("unable to generate bindings");
// Write them to the crate root.
bindings
.write_to_file(out_dir.join("coreaudio.rs"))
.expect("could not write bindings");
}
fn main() {
let (target, platform) = match std::env::var("TARGET") {
Ok(val) => match val.as_ref() {
"x86_64-apple-darwin" | "i686-apple-darwin" => (val, "MacOSX"),
"aarch64-apple-ios" => (String::from("arm64-apple-ios"), "iPhoneOS"),
"armv7-apple-ios" | "armv7s-apple-ios" | "i386-apple-ios" | "x86_64-apple-ios" => {
(val, "iPhoneOS")
}
_ => panic!("coreaudio-sys requires macos or ios target. Found: {}", val),
},
Err(_e) => {
panic!("TARGET environment variable not found (are you running this outside of cargo?)")
}
};
if let Ok(directory) = frameworks_path(platform) {
if let Ok(sysroot) = isysroot_path(&platform.to_lowercase()) {
build(&directory, &sysroot, platform, &target);
} else {
eprintln!("coreaudio-sys could not find sysroot path");
}
} else {
eprintln!("coreaudio-sys could not find frameworks path");
}
}
|
const INPUT: &str = include_str!("../input/2019/day1.txt");
pub fn parse_input() -> Vec<i32> {
INPUT.lines().map(|l| l.parse().unwrap()).collect()
}
pub fn part1() -> i32 {
let input = parse_input();
input.iter().map(|n| (n / 3) - 2).sum()
}
pub fn part2() -> i32 {
let input = parse_input();
let mut total = 0;
for module in input.iter() {
let mut fuel = (module / 3) - 2;
while fuel > 0 {
total += fuel;
fuel = (fuel / 3) - 2;
}
}
total
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn day01_part1() {
assert_eq!(part1(), 3_305_301);
}
#[test]
fn day01_part2() {
assert_eq!(part2(), 4_955_106);
}
}
|
use crate::{Actor, Addr, Context, Handler, Message, Result, Sender, Service};
use fnv::FnvHasher;
use std::any::Any;
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::marker::PhantomData;
type SubscriptionId = u64;
pub(crate) struct Subscribe<T: Message<Result = ()>> {
pub(crate) id: SubscriptionId,
pub(crate) sender: Sender<T>,
}
impl<T: Message<Result = ()>> Message for Subscribe<T> {
type Result = ();
}
pub(crate) struct Unsubscribe {
pub(crate) id: SubscriptionId,
}
impl Message for Unsubscribe {
type Result = ();
}
struct Publish<T: Message<Result = ()> + Clone>(T);
impl<T: Message<Result = ()> + Clone> Message for Publish<T> {
type Result = ();
}
/// Message broker is used to support publishing and subscribing to messages.
///
/// # Examples
///
/// ```rust
/// use xactor::*;
/// use std::time::Duration;
///
/// #[message]
/// #[derive(Clone)]
/// struct MyMsg(&'static str);
///
/// #[message(result = "String")]
/// struct GetValue;
///
/// #[derive(Default)]
/// struct MyActor(String);
///
/// #[async_trait::async_trait]
/// impl Actor for MyActor {
/// async fn started(&mut self, ctx: &mut Context<Self>) -> Result<()> {
/// ctx.subscribe::<MyMsg>().await;
/// Ok(())
/// }
/// }
///
/// #[async_trait::async_trait]
/// impl Handler<MyMsg> for MyActor {
/// async fn handle(&mut self, _ctx: &mut Context<Self>, msg: MyMsg) {
/// self.0 += msg.0;
/// }
/// }
///
/// #[async_trait::async_trait]
/// impl Handler<GetValue> for MyActor {
/// async fn handle(&mut self, _ctx: &mut Context<Self>, _msg: GetValue) -> String {
/// self.0.clone()
/// }
/// }
///
/// #[xactor::main]
/// async fn main() -> Result<()> {
/// let mut addr1 = MyActor::start_default().await?;
/// let mut addr2 = MyActor::start_default().await?;
///
/// Broker::from_registry().await?.publish(MyMsg("a"));
/// Broker::from_registry().await?.publish(MyMsg("b"));
///
/// sleep(Duration::from_secs(1)).await; // Wait for the messages
///
/// assert_eq!(addr1.call(GetValue).await?, "ab");
/// assert_eq!(addr2.call(GetValue).await?, "ab");
/// Ok(())
/// }
/// ```
pub struct Broker<T: Message<Result = ()>> {
subscribes: HashMap<SubscriptionId, Box<dyn Any + Send>, BuildHasherDefault<FnvHasher>>,
mark: PhantomData<T>,
}
impl<T: Message<Result = ()>> Default for Broker<T> {
fn default() -> Self {
Self {
subscribes: Default::default(),
mark: PhantomData,
}
}
}
impl<T: Message<Result = ()>> Actor for Broker<T> {}
impl<T: Message<Result = ()>> Service for Broker<T> {}
#[async_trait::async_trait]
impl<T: Message<Result = ()>> Handler<Subscribe<T>> for Broker<T> {
async fn handle(&mut self, _ctx: &mut Context<Self>, msg: Subscribe<T>) {
self.subscribes.insert(msg.id, Box::new(msg.sender));
}
}
#[async_trait::async_trait]
impl<T: Message<Result = ()>> Handler<Unsubscribe> for Broker<T> {
async fn handle(&mut self, _ctx: &mut Context<Self>, msg: Unsubscribe) {
self.subscribes.remove(&msg.id);
}
}
#[async_trait::async_trait]
impl<T: Message<Result = ()> + Clone> Handler<Publish<T>> for Broker<T> {
async fn handle(&mut self, _ctx: &mut Context<Self>, msg: Publish<T>) {
for sender in self.subscribes.values_mut() {
if let Some(sender) = sender.downcast_mut::<Sender<T>>() {
sender.send(msg.0.clone()).ok();
}
}
}
}
impl<T: Message<Result = ()> + Clone> Addr<Broker<T>> {
/// Publishes a message of the specified type.
pub fn publish(&mut self, msg: T) -> Result<()> {
self.send(Publish(msg))
}
}
|
use std::env;
use std::error::Error;
use std::fs;
use std::str;
type Matrix = Vec<Vec<f64>>;
pub fn kmer_prob(kmer: &[u8], matrix: &Matrix) -> f64 {
let mut prob = 1.;
for (i, nt) in kmer.iter().enumerate() {
let pos = match nt {
b'A' => 0,
b'C' => 1,
b'G' => 2,
b'T' => 3,
_ => unimplemented!(),
};
prob = prob * matrix[pos][i];
}
prob
}
pub fn profile_most_probable(text: &str, k: usize, matrix: &Matrix) -> String {
let mut most_probable_kmer = text[0..k].as_bytes();
let mut max_prob = kmer_prob(most_probable_kmer, matrix);
for kmer in text[1..].as_bytes().windows(k) {
let prob = kmer_prob(kmer, matrix);
if prob > max_prob {
max_prob = prob;
most_probable_kmer = kmer
}
}
String::from_utf8_lossy(most_probable_kmer).into()
}
fn main() -> Result<(), Box<dyn Error>> {
let input: String = env::args()
.nth(1)
.unwrap_or("data/rosalind_ba2c.txt".into());
let data = fs::read_to_string(input)?;
let mut lines = data.lines();
let text: String = lines.next().unwrap().into();
let k = lines.next().unwrap().parse()?;
let mut matrix: Matrix = vec![vec![0.0; k]; 4];
for i in 0..4 {
lines
.next()
.unwrap()
.split(' ')
.map(|x| x.parse().unwrap())
.take(k)
.enumerate()
.map(|(j, x)| matrix[i][j] = x)
.count();
}
println!("{}", profile_most_probable(&text, k, &matrix));
Ok(())
}
|
use std::fs::{create_dir_all, File};
use std::io::prelude::*;
use std::path::{Path, PathBuf};
use std::thread;
use actix_web::web;
use chrono::offset::Utc;
use indexmap::IndexMap;
use log::{error, info};
use meilisearch_core::{MainWriter, MainReader, UpdateReader};
use meilisearch_core::settings::Settings;
use meilisearch_core::update::{apply_settings_update, apply_documents_addition};
use serde::{Deserialize, Serialize};
use serde_json::json;
use tempfile::TempDir;
use crate::Data;
use crate::error::{Error, ResponseError};
use crate::helpers::compression;
use crate::routes::index;
use crate::routes::index::IndexResponse;
#[derive(Debug, Serialize, Deserialize, Copy, Clone)]
enum DumpVersion {
V1,
}
impl DumpVersion {
const CURRENT: Self = Self::V1;
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DumpMetadata {
indexes: Vec<crate::routes::index::IndexResponse>,
db_version: String,
dump_version: DumpVersion,
}
impl DumpMetadata {
/// Create a DumpMetadata with the current dump version of meilisearch.
pub fn new(indexes: Vec<crate::routes::index::IndexResponse>, db_version: String) -> Self {
DumpMetadata {
indexes,
db_version,
dump_version: DumpVersion::CURRENT,
}
}
/// Extract DumpMetadata from `metadata.json` file present at provided `dir_path`
fn from_path(dir_path: &Path) -> Result<Self, Error> {
let path = dir_path.join("metadata.json");
let file = File::open(path)?;
let reader = std::io::BufReader::new(file);
let metadata = serde_json::from_reader(reader)?;
Ok(metadata)
}
/// Write DumpMetadata in `metadata.json` file at provided `dir_path`
fn to_path(&self, dir_path: &Path) -> Result<(), Error> {
let path = dir_path.join("metadata.json");
let file = File::create(path)?;
serde_json::to_writer(file, &self)?;
Ok(())
}
}
/// Extract Settings from `settings.json` file present at provided `dir_path`
fn settings_from_path(dir_path: &Path) -> Result<Settings, Error> {
let path = dir_path.join("settings.json");
let file = File::open(path)?;
let reader = std::io::BufReader::new(file);
let metadata = serde_json::from_reader(reader)?;
Ok(metadata)
}
/// Write Settings in `settings.json` file at provided `dir_path`
fn settings_to_path(settings: &Settings, dir_path: &Path) -> Result<(), Error> {
let path = dir_path.join("settings.json");
let file = File::create(path)?;
serde_json::to_writer(file, settings)?;
Ok(())
}
/// Import settings and documents of a dump with version `DumpVersion::V1` in specified index.
fn import_index_v1(
data: &Data,
dumps_dir: &Path,
index_uid: &str,
document_batch_size: usize,
write_txn: &mut MainWriter,
) -> Result<(), Error> {
// open index
let index = data
.db
.open_index(index_uid)
.ok_or(Error::index_not_found(index_uid))?;
// index dir path in dump dir
let index_path = &dumps_dir.join(index_uid);
// extract `settings.json` file and import content
let settings = settings_from_path(&index_path)?;
let settings = settings.to_update().map_err(|e| Error::dump_failed(format!("importing settings for index {}; {}", index_uid, e)))?;
apply_settings_update(write_txn, &index, settings)?;
// create iterator over documents in `documents.jsonl` to make batch importation
// create iterator over documents in `documents.jsonl` to make batch importation
let documents = {
let file = File::open(&index_path.join("documents.jsonl"))?;
let reader = std::io::BufReader::new(file);
let deserializer = serde_json::Deserializer::from_reader(reader);
deserializer.into_iter::<IndexMap<String, serde_json::Value>>()
};
// batch import document every `document_batch_size`:
// create a Vec to bufferize documents
let mut values = Vec::with_capacity(document_batch_size);
// iterate over documents
for document in documents {
// push document in buffer
values.push(document?);
// if buffer is full, create and apply a batch, and clean buffer
if values.len() == document_batch_size {
let batch = std::mem::replace(&mut values, Vec::with_capacity(document_batch_size));
apply_documents_addition(write_txn, &index, batch, None)?;
}
}
// apply documents remaining in the buffer
if !values.is_empty() {
apply_documents_addition(write_txn, &index, values, None)?;
}
// sync index information: stats, updated_at, last_update
if let Err(e) = crate::index_update_callback_txn(index, index_uid, data, write_txn) {
return Err(Error::Internal(e));
}
Ok(())
}
/// Import dump from `dump_path` in database.
pub fn import_dump(
data: &Data,
dump_path: &Path,
document_batch_size: usize,
) -> Result<(), Error> {
info!("Importing dump from {:?}...", dump_path);
// create a temporary directory
let tmp_dir = TempDir::new()?;
let tmp_dir_path = tmp_dir.path();
// extract dump in temporary directory
compression::from_tar_gz(dump_path, tmp_dir_path)?;
// read dump metadata
let metadata = DumpMetadata::from_path(&tmp_dir_path)?;
// choose importation function from DumpVersion of metadata
let import_index = match metadata.dump_version {
DumpVersion::V1 => import_index_v1,
};
// remove indexes which have same `uid` than indexes to import and create empty indexes
let existing_index_uids = data.db.indexes_uids();
for index in metadata.indexes.iter() {
if existing_index_uids.contains(&index.uid) {
data.db.delete_index(index.uid.clone())?;
}
index::create_index_sync(&data.db, index.uid.clone(), index.name.clone(), index.primary_key.clone())?;
}
// import each indexes content
data.db.main_write::<_, _, Error>(|mut writer| {
for index in metadata.indexes {
import_index(&data, tmp_dir_path, &index.uid, document_batch_size, &mut writer)?;
}
Ok(())
})?;
info!("Dump importation from {:?} succeed", dump_path);
Ok(())
}
#[derive(Debug, Serialize, Deserialize, PartialEq, Clone)]
#[serde(rename_all = "snake_case")]
pub enum DumpStatus {
Done,
InProgress,
Failed,
}
#[derive(Debug, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct DumpInfo {
pub uid: String,
pub status: DumpStatus,
#[serde(skip_serializing_if = "Option::is_none", flatten)]
pub error: Option<serde_json::Value>,
}
impl DumpInfo {
pub fn new(uid: String, status: DumpStatus) -> Self {
Self { uid, status, error: None }
}
pub fn with_error(mut self, error: ResponseError) -> Self {
self.status = DumpStatus::Failed;
self.error = Some(json!(error));
self
}
pub fn dump_already_in_progress(&self) -> bool {
self.status == DumpStatus::InProgress
}
}
/// Generate uid from creation date
fn generate_uid() -> String {
Utc::now().format("%Y%m%d-%H%M%S%3f").to_string()
}
/// Infer dumps_dir from dump_uid
pub fn compressed_dumps_dir(dumps_dir: &Path, dump_uid: &str) -> PathBuf {
dumps_dir.join(format!("{}.dump", dump_uid))
}
/// Write metadata in dump
fn dump_metadata(data: &web::Data<Data>, dir_path: &Path, indexes: Vec<IndexResponse>) -> Result<(), Error> {
let (db_major, db_minor, db_patch) = data.db.version();
let metadata = DumpMetadata::new(indexes, format!("{}.{}.{}", db_major, db_minor, db_patch));
metadata.to_path(dir_path)
}
/// Export settings of provided index in dump
fn dump_index_settings(data: &web::Data<Data>, reader: &MainReader, dir_path: &Path, index_uid: &str) -> Result<(), Error> {
let settings = crate::routes::setting::get_all_sync(data, reader, index_uid)?;
settings_to_path(&settings, dir_path)
}
/// Export updates of provided index in dump
fn dump_index_updates(data: &web::Data<Data>, reader: &UpdateReader, dir_path: &Path, index_uid: &str) -> Result<(), Error> {
let updates_path = dir_path.join("updates.jsonl");
let updates = crate::routes::index::get_all_updates_status_sync(data, reader, index_uid)?;
let file = File::create(updates_path)?;
for update in updates {
serde_json::to_writer(&file, &update)?;
writeln!(&file)?;
}
Ok(())
}
/// Export documents of provided index in dump
fn dump_index_documents(data: &web::Data<Data>, reader: &MainReader, dir_path: &Path, index_uid: &str) -> Result<(), Error> {
let documents_path = dir_path.join("documents.jsonl");
let file = File::create(documents_path)?;
let dump_batch_size = data.dump_batch_size;
let mut offset = 0;
loop {
let documents = crate::routes::document::get_all_documents_sync(data, reader, index_uid, offset, dump_batch_size, None)?;
if documents.is_empty() { break; } else { offset += dump_batch_size; }
for document in documents {
serde_json::to_writer(&file, &document)?;
writeln!(&file)?;
}
}
Ok(())
}
/// Write error with a context.
fn fail_dump_process<E: std::error::Error>(data: &web::Data<Data>, dump_info: DumpInfo, context: &str, error: E) {
let error_message = format!("{}; {}", context, error);
error!("Something went wrong during dump process: {}", &error_message);
data.set_current_dump_info(dump_info.with_error(Error::dump_failed(error_message).into()))
}
/// Main function of dump.
fn dump_process(data: web::Data<Data>, dumps_dir: PathBuf, dump_info: DumpInfo) {
// open read transaction on Update
let update_reader = match data.db.update_read_txn() {
Ok(r) => r,
Err(e) => {
fail_dump_process(&data, dump_info, "creating RO transaction on updates", e);
return ;
}
};
// open read transaction on Main
let main_reader = match data.db.main_read_txn() {
Ok(r) => r,
Err(e) => {
fail_dump_process(&data, dump_info, "creating RO transaction on main", e);
return ;
}
};
// create a temporary directory
let tmp_dir = match TempDir::new() {
Ok(tmp_dir) => tmp_dir,
Err(e) => {
fail_dump_process(&data, dump_info, "creating temporary directory", e);
return ;
}
};
let tmp_dir_path = tmp_dir.path();
// fetch indexes
let indexes = match crate::routes::index::list_indexes_sync(&data, &main_reader) {
Ok(indexes) => indexes,
Err(e) => {
fail_dump_process(&data, dump_info, "listing indexes", e);
return ;
}
};
// create metadata
if let Err(e) = dump_metadata(&data, &tmp_dir_path, indexes.clone()) {
fail_dump_process(&data, dump_info, "generating metadata", e);
return ;
}
// export settings, updates and documents for each indexes
for index in indexes {
let index_path = tmp_dir_path.join(&index.uid);
// create index sub-dircetory
if let Err(e) = create_dir_all(&index_path) {
fail_dump_process(&data, dump_info, &format!("creating directory for index {}", &index.uid), e);
return ;
}
// export settings
if let Err(e) = dump_index_settings(&data, &main_reader, &index_path, &index.uid) {
fail_dump_process(&data, dump_info, &format!("generating settings for index {}", &index.uid), e);
return ;
}
// export documents
if let Err(e) = dump_index_documents(&data, &main_reader, &index_path, &index.uid) {
fail_dump_process(&data, dump_info, &format!("generating documents for index {}", &index.uid), e);
return ;
}
// export updates
if let Err(e) = dump_index_updates(&data, &update_reader, &index_path, &index.uid) {
fail_dump_process(&data, dump_info, &format!("generating updates for index {}", &index.uid), e);
return ;
}
}
// compress dump in a file named `{dump_uid}.dump` in `dumps_dir`
if let Err(e) = crate::helpers::compression::to_tar_gz(&tmp_dir_path, &compressed_dumps_dir(&dumps_dir, &dump_info.uid)) {
fail_dump_process(&data, dump_info, "compressing dump", e);
return ;
}
// update dump info to `done`
let resume = DumpInfo::new(
dump_info.uid,
DumpStatus::Done
);
data.set_current_dump_info(resume);
}
pub fn init_dump_process(data: &web::Data<Data>, dumps_dir: &Path) -> Result<DumpInfo, Error> {
create_dir_all(dumps_dir).map_err(|e| Error::dump_failed(format!("creating temporary directory {}", e)))?;
// check if a dump is already in progress
if let Some(resume) = data.get_current_dump_info() {
if resume.dump_already_in_progress() {
return Err(Error::dump_conflict())
}
}
// generate a new dump info
let info = DumpInfo::new(
generate_uid(),
DumpStatus::InProgress
);
data.set_current_dump_info(info.clone());
let data = data.clone();
let dumps_dir = dumps_dir.to_path_buf();
let info_cloned = info.clone();
// run dump process in a new thread
thread::spawn(move ||
dump_process(data, dumps_dir, info_cloned)
);
Ok(info)
}
|
/*
* Open Service Cloud API
*
* Open Service Cloud API to manage different backend cloud services.
*
* The version of the OpenAPI document: 0.0.3
* Contact: wanghui71leon@gmail.com
* Generated by: https://openapi-generator.tech
*/
#[derive(Debug, PartialEq, Serialize, Deserialize)]
pub struct PublicipRequestFragmentPublicip {
#[serde(rename = "type")]
pub _type: String,
#[serde(rename = "ip_address", skip_serializing_if = "Option::is_none")]
pub ip_address: Option<String>,
}
impl PublicipRequestFragmentPublicip {
pub fn new(_type: String) -> PublicipRequestFragmentPublicip {
PublicipRequestFragmentPublicip {
_type: _type,
ip_address: None,
}
}
}
|
//! A Function block is a block containing other blocks. It basically
//! contains a sequence of other blocks to execute one by one.
use super::BasicBlock;
use crate::label::Label;
use std::vec::Vec;
#[derive(Debug)]
pub struct Function<'block> {
label: Label,
args: Option<&'block Vec<&'block dyn BasicBlock>>,
stmts: &'block Vec<&'block dyn BasicBlock>,
retval: Option<&'block dyn BasicBlock>,
}
impl<'block> Function<'block> {
/// Create a new function block from a vector of blocks
///
/// # Example
///
/// ```
/// use stir::blocks::{Boolean, Function, BasicBlock};
///
/// let f_block = Boolean::new(false);
/// let t_block = Boolean::new(true);
///
/// let mut vec: Vec<&dyn BasicBlock> = vec!(&f_block, &t_block);
///
/// // Create a function with no arguments and no return value
/// let function_block = Function::new(None, &vec);
///
/// assert_eq!(function_block.interpret(), false);
/// ```
pub fn new(
args: Option<&'block Vec<&'block dyn BasicBlock>>,
stmts: &'block Vec<&'block dyn BasicBlock>,
) -> Function<'block> {
Function {
label: Label::new("function"),
args,
stmts,
retval: None,
}
}
pub fn set_retval(&mut self, retval: &'block dyn BasicBlock) {
self.retval = Some(retval);
}
pub fn get_arg(&self, idx: usize) -> Option<&'block dyn BasicBlock> {
match self.args {
Some(args) => Some(args[idx]),
None => None,
}
}
}
impl BasicBlock for Function<'_> {
fn label(&self) -> &String {
self.label.name()
}
fn interpret(&self) -> bool {
for statement in self.stmts.iter() {
statement.interpret();
}
match self.retval {
Some(val) => val.interpret(),
None => false,
}
}
fn output(&self) -> String {
String::from("function") // FIXME: Add logic
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::blocks::{Boolean, IfElse};
#[test]
fn test_single_stmt() {
let b = Boolean::new(false);
let mut vec: Vec<&dyn BasicBlock> = Vec::new();
vec.push(&b);
let f = Function::new(None, &vec);
assert_eq!(f.interpret(), false);
}
#[test]
fn test_multi_stmt() {
let c = Boolean::new(true);
let t = Boolean::new(false);
let f = Boolean::new(true);
let ie = IfElse::new(&c, &t, Some(&f));
let other_stmt = Boolean::new(true);
let mut vec: Vec<&dyn BasicBlock> = Vec::new();
vec.push(&ie);
vec.push(&other_stmt);
let f = Function::new(None, &vec);
assert_eq!(f.interpret(), false);
}
#[test]
fn test_true_stmt() {
let t = Boolean::new(true);
let mut vec: Vec<&dyn BasicBlock> = Vec::new();
vec.push(&t);
let f = Function::new(None, &vec);
assert!(!f.interpret());
}
#[test]
fn test_args() {
let arg0 = Boolean::new(false);
let arg1 = Boolean::new(true);
let arg2 = Boolean::new(true);
let args: Vec<&dyn BasicBlock> = vec![&arg0, &arg1, &arg2];
let no_body = vec![] as Vec<&dyn BasicBlock>;
let f = Function::new(Some(&args), &no_body);
assert_eq!(f.get_arg(0).unwrap().label(), arg0.label());
assert_eq!(f.get_arg(1).unwrap().label(), arg1.label());
assert_eq!(f.get_arg(2).unwrap().label(), arg2.label());
}
#[test]
fn test_retval() {
let true_retval = Boolean::new(true);
let no_body = vec![] as Vec<&dyn BasicBlock>;
let mut f = Function::new(None, &no_body);
f.set_retval(&true_retval);
assert!(f.interpret());
}
}
|
/*
* The mythical generator.
*/
use super::{PyCode, PyStrRef, PyType};
use crate::{
class::PyClassImpl,
coroutine::Coro,
frame::FrameRef,
function::OptionalArg,
protocol::PyIterReturn,
types::{Constructor, IterNext, Iterable, Representable, SelfIter, Unconstructible},
AsObject, Context, Py, PyObjectRef, PyPayload, PyRef, PyResult, VirtualMachine,
};
#[pyclass(module = false, name = "generator")]
#[derive(Debug)]
pub struct PyGenerator {
inner: Coro,
}
impl PyPayload for PyGenerator {
fn class(ctx: &Context) -> &'static Py<PyType> {
ctx.types.generator_type
}
}
#[pyclass(with(Py, Constructor, IterNext, Iterable))]
impl PyGenerator {
pub fn as_coro(&self) -> &Coro {
&self.inner
}
pub fn new(frame: FrameRef, name: PyStrRef) -> Self {
PyGenerator {
inner: Coro::new(frame, name),
}
}
#[pygetset(magic)]
fn name(&self) -> PyStrRef {
self.inner.name()
}
#[pygetset(magic, setter)]
fn set_name(&self, name: PyStrRef) {
self.inner.set_name(name)
}
#[pygetset]
fn gi_frame(&self, _vm: &VirtualMachine) -> FrameRef {
self.inner.frame()
}
#[pygetset]
fn gi_running(&self, _vm: &VirtualMachine) -> bool {
self.inner.running()
}
#[pygetset]
fn gi_code(&self, _vm: &VirtualMachine) -> PyRef<PyCode> {
self.inner.frame().code.clone()
}
#[pygetset]
fn gi_yieldfrom(&self, _vm: &VirtualMachine) -> Option<PyObjectRef> {
self.inner.frame().yield_from_target()
}
}
#[pyclass]
impl Py<PyGenerator> {
#[pymethod]
fn send(&self, value: PyObjectRef, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
self.inner.send(self.as_object(), value, vm)
}
#[pymethod]
fn throw(
&self,
exc_type: PyObjectRef,
exc_val: OptionalArg,
exc_tb: OptionalArg,
vm: &VirtualMachine,
) -> PyResult<PyIterReturn> {
self.inner.throw(
self.as_object(),
exc_type,
exc_val.unwrap_or_none(vm),
exc_tb.unwrap_or_none(vm),
vm,
)
}
#[pymethod]
fn close(&self, vm: &VirtualMachine) -> PyResult<()> {
self.inner.close(self.as_object(), vm)
}
}
impl Unconstructible for PyGenerator {}
impl Representable for PyGenerator {
#[inline]
fn repr_str(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<String> {
Ok(zelf.inner.repr(zelf.as_object(), zelf.get_id(), vm))
}
}
impl SelfIter for PyGenerator {}
impl IterNext for PyGenerator {
fn next(zelf: &Py<Self>, vm: &VirtualMachine) -> PyResult<PyIterReturn> {
zelf.send(vm.ctx.none(), vm)
}
}
pub fn init(ctx: &Context) {
PyGenerator::extend_class(ctx, ctx.types.generator_type);
}
|
use game::*;
use std::collections::HashSet;
impl Damager{
pub fn step(game: &mut Game1){
for damager in game.damagers.iter_mut(){
let mover=game.movers.at(damager.mover_id.id);
let allegiance=game.allegiances.at(damager.allegiance_id.id);
let mut improved_mover=mover.clone();
improved_mover.width+=damager.extra_radius;
improved_mover.height+=damager.extra_radius;
let mut speed_correction=improved_mover.clone();
speed_correction.x+=speed_correction.xspeed;
speed_correction.y+=speed_correction.yspeed;
for (damageable_id, damageable) in game.damageables.iter_id_mut(){
if damager.piercing==0 {break;}
let other_mover=game.movers.at(damageable.mover_id.id);
let other_allegiance=game.allegiances.at(damageable.allegiance_id.id);
if !allegiance.can_damage(other_allegiance) {continue};
if !(improved_mover.collide(other_mover)||speed_correction.collide(other_mover)) {continue;}
if damager.hit_once {
if damager.already_hit.contains(&damageable_id) {continue};
damager.already_hit.push(damageable_id);
}
damager.damage(damageable);
}
let mut damageable_terrains=HashSet::new();
for id in Chunk::get_colliding_damageable_terrains_small(&game.chunks, &improved_mover){
damageable_terrains.insert(id.id);
}
for id in Chunk::get_colliding_damageable_terrains_small(&game.chunks, &speed_correction){
damageable_terrains.insert(id.id);
}
for damageable_id in damageable_terrains{
if damager.piercing==0 {break;}
let damageable=game.terrain_damageables.at_mut(damageable_id);
let other_allegiance=game.allegiances.at(damageable.allegiance_id.id);
if !allegiance.can_damage(other_allegiance){continue}
if damager.hit_once {
if damager.already_hit_terrain.contains(&damageable_id) {continue};
damager.already_hit_terrain.push(damageable_id);
}
damager.damage_terrain(damageable);
}
}
}
pub fn damage_terrain(&mut self, other: &mut Damageable){
match self.damage_type{
DamageType::Flame=>{
other.hp-=self.damage},
DamageType::Normal=>{
other.hp-=self.damage}
};
self.piercing-=1;
}
pub fn damage(&mut self, other: &mut Damageable){
match self.damage_type{
DamageType::Flame=>{
other.burning+=self.damage},
DamageType::Normal=>{
other.hp-=self.damage}
};
self.piercing-=1;
}
pub fn default(mover_id: MoverID, allegiance_id: AllegianceID)->Damager{
Damager{mover_id: mover_id, damage: 0.0, damage_type: DamageType::Normal, allegiance_id: allegiance_id,
extra_radius: 0, piercing: -1, hit_once: true, already_hit: Vec::new(), already_hit_terrain: Vec::new()}
}
pub fn new(game: &mut Game1, mover_id: MoverID, allegiance_id: AllegianceID, damage: f64)->DamagerID{
let mut damager=Self::default(mover_id, allegiance_id);
damager.damage=damage;
DamagerID{id: game.damagers.add(damager)}
}
pub fn new_typed(game: &mut Game1, mover_id: MoverID, allegiance_id: AllegianceID, damage: f64, damage_type: DamageType)->DamagerID{
let mut damager=Self::default(mover_id, allegiance_id);
damager.damage=damage;
damager.damage_type=damage_type;
DamagerID{id: game.damagers.add(damager)}
}
pub fn remove(game: &mut Game1, id: DamagerID){
game.damagers.remove(id.id);
}
}
impl Damageable{
pub fn step(game: &mut Game1){
for damageable in game.damageables.iter_mut(){
if damageable.burning>0.0 {
let change=damageable.burning/128.0;
let change=change.max(damageable.burning.min(2.0));
damageable.burning-=change;
damageable.hp-=change;
} else {damageable.burning=0.0}
}
}
pub fn default(mover_id: MoverID, allegiance_id: AllegianceID)->Self{
Damageable{ mover_id: mover_id,
hp: DEFAULT_HEALTH,
max_hp: DEFAULT_HEALTH,
allegiance_id: allegiance_id,
burning: 0.0,
flammable: true
}
}
pub fn remove(game: &mut Game1, id: DamageableID){
game.damageables.remove(id.id);
}
}
impl DamageableTerrainWatcher{
pub fn end_step(game: &mut Game1){
let mut removed_watchers=Vec::new();
{
for (coords, watcher) in game.damageable_terrain_watchers.iter_mut(){
let chunk=game.chunks.get_mut(&watcher.chunk_coords);
if chunk.is_none() {
removed_watchers.push(coords.clone());
continue;
}
let chunk=chunk.unwrap();
if !chunk.damaged_since_last_frame {
continue;
}
let mut dead_watches=Vec::new();
for (id,watch) in watcher.watches.iter_mut().enumerate(){
let damageable=game.terrain_damageables.at_mut(chunk.damageable_terrain[watch.y][watch.x].at(watch.damageable_terrain_depth).damageable_id.id);
if damageable.hp<=0.0 {
dead_watches.push(id);
}
}
let mut updates=HashSet::new();
for id in dead_watches.iter(){
{
let ref watch=watcher.watches[*id];
chunk.terrain[watch.y][watch.x].remove(watch.sprite_depth);
chunk.damageable_terrain[watch.y][watch.x].remove(watch.damageable_terrain_depth);
chunk.solid[watch.y][watch.x]=chunk.solid[watch.y][watch.x]-1;
updates.insert((watch.x, watch.y));
}
}
for (x,y) in updates{
chunk.terrain_update(x,y);
}
for i in 0..dead_watches.len(){
let id=dead_watches[i];
for watch_id in dead_watches.iter_mut(){
if *watch_id>id {*watch_id=*watch_id-1}
}
watcher.watches.remove(id);
}
}
}
for coords in removed_watchers.drain(..){
game.damageable_terrain_watchers.remove(&coords);
}
}
}
impl Projectile{
pub fn default(mover_id: MoverID, damager_id: DamagerID)->Self{
Projectile{mover_id: mover_id, damager_id: damager_id, lifetime: 100, basic_drawn_id: BasicDrawnID{id: 0}}
}
pub fn initialise_sprite(game: &mut Game1, mover_id:MoverID, projectile_id: ProjectileID, sprite: u32){
let basic_drawn_id=BasicDrawn::new(&game.movers, &mut game.drawn_counter, &mut game.drawn, &mut game.basic_drawn, mover_id, sprite);
game.projectiles.at_mut(projectile_id.id).basic_drawn_id=basic_drawn_id;
}
pub fn new(game: &mut Game1, mover_id: MoverID, damager_id: DamagerID, lifetime: u8, sprite: u32)->ProjectileID{
let mut projectile=Self::default(mover_id, damager_id);
projectile.lifetime=lifetime;
let id=ProjectileID{id: game.projectiles.add(projectile)};
Self::initialise_sprite(game, mover_id, id, sprite);
id
}
pub fn end_step(game: &mut Game1){
let mut removed_projectiles=Vec::new();
for (id, projectile) in game.projectiles.iter_id_mut(){
if projectile.lifetime==0 {removed_projectiles.push(id);}
}
for id in removed_projectiles{
let projectile=game.projectiles[id].take().expect("Attempting to remove nonexistent projectiles");
{
Mover::remove(game,projectile.mover_id);
BasicDrawn::remove_with_drawn(game, projectile.basic_drawn_id);
Damager::remove(game, projectile.damager_id);
};
game.projectiles[id]=Some(projectile);
game.projectiles.remove(id);
}
}
pub fn step(game: &mut Game1){
let mut removed_projectiles=Vec::new();
for (id, projectile) in game.projectiles.iter_id_mut(){
if game.damagers.at(projectile.damager_id.id).piercing==0 {projectile.lifetime=0};
if projectile.lifetime==0 {removed_projectiles.push(id);continue;};
projectile.lifetime-=1;
}
}
}
impl Allegiance{
pub fn default()->Self{
Allegiance{allegiances: Vec::new()}
}
pub fn can_damage(&self, other: &Self)->bool{
for a in self.allegiances.iter(){
if other.allegiances.contains(a) {return false};
}
true
}
pub fn new(allegiances: &mut GVec<Allegiance>, which: Vec<i64>)->AllegianceID{
AllegianceID{id: allegiances.add(Allegiance{allegiances: which})}
}
pub fn remove(game: &mut Game1, id: AllegianceID)->Allegiance{
game.allegiances.remove(id.id)
}
}
pub fn step_damage(game: &mut Game1){
Damageable::step(game);
Damager::step(game);
Projectile::step(game);
}
pub fn end_step_damage(game: &mut Game1){
DamageableTerrainWatcher::end_step(game);
Projectile::end_step(game);
}
|
//
// accounts/mod.rs
//
pub mod types;
use self::types::*;
use accounts::types::CurrentUser::*;
use db::{Conn, PooledConnection};
use diesel::prelude::*;
use diesel::result::DatabaseErrorKind;
use diesel::result::Error::DatabaseError;
use result::Error;
use result::{Payload, Response};
use validator::Validate;
///
/// Helpers
///
/// Create a new session
pub fn create_session(conn: PooledConnection, user: &User) -> Result<Session, Error> {
use schema::sessions::dsl::*;
// Set old sessions as inactive
let _ = diesel::update(sessions)
.filter(uid.eq(user.id))
.set(active.eq(false))
.execute(&conn);
// Create a new session
let hash_base = format!(
"{}{}{}",
chrono::Utc::now(),
user.id.to_string(),
"8h9gfds98f9g9f8dgs98gf98d$5$$%",
);
let new_session = NewSession {
uid: user.id,
token: bcrypt::hash(&hash_base, bcrypt::DEFAULT_COST)?,
active: true,
created: chrono::Utc::now().naive_utc(),
updated: chrono::Utc::now().naive_utc(),
};
diesel::insert_into(sessions)
.values(&new_session)
.get_result(&conn)
.map_err(|e| Error::from(e))
}
/// Get user from key
pub fn user_from_key(conn: PooledConnection, key: String) -> Option<User> {
use schema::sessions::dsl::*;
use schema::users::dsl::id;
use schema::users::dsl::*;
// Load session and user
let mut user = None;
let session = sessions.filter(token.eq(key)).first::<Session>(&conn).ok();
if let Some(s) = session {
user = users.filter(id.eq(s.uid)).first::<User>(&conn).ok();
}
user
}
/// Check if the user is an admin
pub fn user_is_admin(user: &User) -> bool {
user.roles.iter().any(|r| match r {
Role::Admin => true,
_ => false,
})
}
///
/// Public API
///
/// Get all users
pub fn all_users(user: CurrentUser, conn: Conn) -> Response<Vec<User>> {
use schema::users::dsl::*;
let _ = match user {
Admin(user) => user,
_ => return Err(Error::AccessDenied),
};
let Conn(conn) = conn;
let u = users.limit(10).load::<User>(&conn)?;
Ok(Payload {
data: u,
success: true,
..Default::default()
})
}
/// User by id
pub fn user_by_id(user_id: i32, user: CurrentUser, conn: Conn) -> Response<User> {
use schema::users::dsl::*;
let _ = match user {
Admin(user) => user,
_ => return Err(Error::AccessDenied),
};
let Conn(conn) = conn;
let u = users.find(user_id).first::<User>(&conn)?;
Ok(Payload {
data: u,
success: true,
..Default::default()
})
}
/// Login
pub fn login(conn: Conn, input: LoginInput) -> Response<AuthPayload> {
use schema::users::dsl::*;
input.validate()?;
let Conn(conn) = conn;
// Load user
let user = match users.filter(email.eq(&input.email)).first::<User>(&conn) {
Ok(user) => user,
Err(_) => {
// Take hash time to return results
let _ = bcrypt::verify(&input.email, &input.email);
return Err(Error::from_custom_validation(
"email_doesnt_exist",
"email",
"Email doesn't exist",
));
}
};
// Check password
// Handle case where user doesn't exist
let pw_result = bcrypt::verify(&input.password, &user.password_hash).map_err(|_| {
return Error::from_custom_validation("password_invalid", "password", "Password is invalid");
})?;
// If password doesn't match, return error
if !pw_result {
return Err(Error::from_custom_validation(
"password_invalid",
"password",
"Password is invalid",
));
}
// Create a new session
let session = self::create_session(conn, &user)?;
// Return the auth payload
Ok(Payload {
data: AuthPayload {
token: Some(session.token),
user: Some(user),
},
success: true,
..Default::default()
})
}
/// Register
pub fn register(conn: Conn, input: RegistrationInput) -> Response<AuthPayload> {
use schema::users::dsl::*;
input.validate()?;
let input = input.clone();
let Conn(conn) = conn;
// Create user
let user = diesel::insert_into(users)
.values(&NewUser {
name: input.name,
email: input.email,
password_hash: bcrypt::hash(&input.password, bcrypt::DEFAULT_COST)?,
roles: vec![Role::Authenticated],
})
.get_result::<User>(&conn)
.map_err(|e| match e {
DatabaseError(DatabaseErrorKind::UniqueViolation, _info) => {
Error::from_custom_validation("email_taken", "email", "Email is taken")
}
_ => Error::from(e),
})?;
let session = self::create_session(conn, &user)?;
Ok(Payload {
data: AuthPayload {
token: Some(session.token),
user: Some(user),
},
success: true,
..Default::default()
})
}
/// Create user
///
/// Used by admins to create a user
pub fn create_user(user: CurrentUser, conn: Conn, input: CreateUserInput) -> Response<User> {
use schema::users::dsl::*;
let _ = match user {
Admin(user) => user,
_ => return Err(Error::AccessDenied),
};
input.validate()?;
// Create user
let user = diesel::insert_into(users)
.values(&NewUser {
name: input.name,
email: input.email,
password_hash: bcrypt::hash(&input.password, bcrypt::DEFAULT_COST)?,
roles: input.roles,
})
.get_result::<User>(&conn.0)
.map_err(|e| match e {
DatabaseError(DatabaseErrorKind::UniqueViolation, _info) => {
Error::from_custom_validation("email_taken", "email", "Email is taken")
}
_ => Error::from(e),
})?;
Ok(Payload {
data: user,
success: true,
..Default::default()
})
}
//
// Profiles
//
/// Create a new session
pub fn create_profile(
conn: Conn,
user: &CurrentUser,
profile_user_id: i32,
input: &ProfileInput,
) -> Response<Profile> {
use schema::profiles::dsl::*;
let _ = match user {
Admin(user) => user,
_ => return Err(Error::AccessDenied),
};
input.validate()?;
// Create user
let profile = diesel::insert_into(profiles)
.values(&NewProfile {
uid: profile_user_id,
title: input.title.clone(),
intro: input.intro.clone(),
body: input.body.clone(),
})
.get_result::<Profile>(&conn.0)
.map_err(|e| match e {
DatabaseError(DatabaseErrorKind::UniqueViolation, _info) => {
Error::from_custom_validation("profile_exists", "profile", "Profile exists")
}
_ => Error::from(e),
})?;
Ok(Payload {
data: profile,
success: true,
..Default::default()
})
}
/// Update Profile
pub fn update_profile(
conn: Conn,
user: &CurrentUser,
profile_user_id: i32,
input: &ProfileInput,
) -> Response<Profile> {
use schema::profiles::dsl::*;
let _ = match user {
Admin(user) => user,
_ => return Err(Error::AccessDenied),
};
input.validate()?;
let profile = profiles
.filter(uid.eq(profile_user_id))
.first::<Profile>(&conn.0)?;
let profile = diesel::update(&profile).set(input).get_result(&conn.0)?;
Ok(Payload {
data: profile,
success: true,
..Default::default()
})
}
/// Get profile
pub fn get_profile(user_id: i32, user: CurrentUser, conn: Conn) -> Response<Profile> {
use schema::profiles::dsl::*;
let _ = match user {
Admin(user) => user,
_ => return Err(Error::AccessDenied),
};
let profile = profiles.filter(uid.eq(user_id)).first::<Profile>(&conn.0)?;
Ok(Payload {
data: profile,
success: true,
..Default::default()
})
}
|
use syn::{Ident, Ty, Path, PathSegment};
pub fn ty_ident(ident: Ident) -> Ty {
ty_path(path_ident(ident))
}
pub fn ty_path(path: Path) -> Ty {
Ty::Path(None, path)
}
pub fn path_ident(ident: Ident) -> Path {
Path {
global: false,
segments: vec![PathSegment::ident(ident)],
}
}
|
pub mod response;
use crate::auth::Authenticator;
use crate::utils::options::CommentOption;
use crate::Client;
use async_trait::async_trait;
use crate::error::Error;
use crate::responses::listing::{GenericListing, ListingArray};
pub trait CommentType<'a>: Sized + Sync + Send {
fn get_permalink(&self) -> &String;
fn to_comment<A: Authenticator>(&'a self, me: &'a Client<A>) -> Comment<'a, A, Self>
where
Self: CommentType<'a>,
{
Comment { comment: self, me }
}
}
impl<'a> CommentType<'a> for String {
fn get_permalink(&self) -> &String {
self
}
}
pub struct Comment<'a, A: Authenticator, T: CommentType<'a>> {
pub comment: &'a T,
pub(crate) me: &'a Client<A>,
}
pub type Comments<'a, A, T> = GenericListing<Comment<'a, A, T>>;
#[async_trait(?Send)]
pub trait CommentRetriever {
async fn get_comments(&self, sort: Option<CommentOption>) -> Result<ListingArray, Error>;
}
#[async_trait(?Send)]
impl<'a, A: Authenticator, T: CommentType<'a>> CommentRetriever for Comment<'a, A, T> {
async fn get_comments(&self, sort: Option<CommentOption>) -> Result<ListingArray, Error> {
let mut path = self.comment.get_permalink().to_string();
if let Some(options) = sort {
options.extend(&mut path)
}
return self.me.get_json::<ListingArray>(&path, false, false).await;
}
}
|
// Copyright 2023 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 common_expression::types::string::StringColumnBuilder;
use common_expression::types::DataType;
use common_expression::types::NumberDataType;
use common_expression::types::UInt64Type;
use common_expression::BlockEntry;
use common_expression::ColumnId;
use common_expression::FromData;
use common_expression::Scalar;
use common_expression::TableDataType;
use common_expression::Value;
// Segment and Block id Bits when generate internal column `_row_id`
// Since `DEFAULT_BLOCK_PER_SEGMENT` is 1000, so `block_id` 10 bits is enough.
const NUM_BLOCK_ID_BITS: usize = 10;
const NUM_SEGMENT_ID_BITS: usize = 22;
pub const ROW_ID: &str = "_row_id";
pub const SNAPSHOT_NAME: &str = "_snapshot_name";
pub const SEGMENT_NAME: &str = "_segment_name";
pub const BLOCK_NAME: &str = "_block_name";
// meta data for generate internal columns
#[derive(Debug)]
pub struct InternalColumnMeta {
pub segment_id: usize,
pub block_id: usize,
pub block_location: String,
pub segment_location: String,
pub snapshot_location: String,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
pub enum InternalColumnType {
RowId,
BlockName,
SegmentName,
SnapshotName,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq)]
pub struct InternalColumn {
pub column_name: String,
pub column_type: InternalColumnType,
}
impl InternalColumn {
pub fn new(name: &str, column_type: InternalColumnType) -> Self {
InternalColumn {
column_name: name.to_string(),
column_type,
}
}
pub fn column_type(&self) -> &InternalColumnType {
&self.column_type
}
pub fn table_data_type(&self) -> TableDataType {
match &self.column_type {
InternalColumnType::RowId => TableDataType::Number(NumberDataType::UInt64),
InternalColumnType::BlockName => TableDataType::String,
InternalColumnType::SegmentName => TableDataType::String,
InternalColumnType::SnapshotName => TableDataType::String,
}
}
pub fn data_type(&self) -> DataType {
let t = &self.table_data_type();
t.into()
}
pub fn column_name(&self) -> &String {
&self.column_name
}
pub fn column_id(&self) -> ColumnId {
match &self.column_type {
InternalColumnType::RowId => u32::MAX,
InternalColumnType::BlockName => u32::MAX - 1,
InternalColumnType::SegmentName => u32::MAX - 2,
InternalColumnType::SnapshotName => u32::MAX - 3,
}
}
pub fn generate_column_values(&self, meta: &InternalColumnMeta, num_rows: usize) -> BlockEntry {
match &self.column_type {
InternalColumnType::RowId => {
let block_id = meta.block_id as u64;
let seg_id = meta.segment_id as u64;
let high_32bit = (seg_id << NUM_SEGMENT_ID_BITS) + (block_id << NUM_BLOCK_ID_BITS);
let mut row_ids = Vec::with_capacity(num_rows);
for i in 0..num_rows {
let row_id = high_32bit + i as u64;
row_ids.push(row_id);
}
BlockEntry {
data_type: DataType::Number(NumberDataType::UInt64),
value: Value::Column(UInt64Type::from_data(row_ids)),
}
}
InternalColumnType::BlockName => {
let mut builder = StringColumnBuilder::with_capacity(1, meta.block_location.len());
builder.put_str(&meta.block_location);
builder.commit_row();
BlockEntry {
data_type: DataType::String,
value: Value::Scalar(Scalar::String(builder.build_scalar())),
}
}
InternalColumnType::SegmentName => {
let mut builder =
StringColumnBuilder::with_capacity(1, meta.segment_location.len());
builder.put_str(&meta.segment_location);
builder.commit_row();
BlockEntry {
data_type: DataType::String,
value: Value::Scalar(Scalar::String(builder.build_scalar())),
}
}
InternalColumnType::SnapshotName => {
let mut builder =
StringColumnBuilder::with_capacity(1, meta.snapshot_location.len());
builder.put_str(&meta.snapshot_location);
builder.commit_row();
BlockEntry {
data_type: DataType::String,
value: Value::Scalar(Scalar::String(builder.build_scalar())),
}
}
}
}
}
|
// Copyright (C) 2019 Frank Rehberger
//
// Licensed under the Apache License, Version 2.0 or MIT License
#[cfg(test)]
extern crate test_generator;
#[cfg(test)]
mod tests {
use test_generator::test_resources;
// For all subfolders matching "res/*/input.txt" do generate a test function
// For example:
// In case of the following resources in these two folders "rest1/input.txt"
// and "res/set2/input.txt" the following test functions
// would be created
// ```
// #[test]
// fn verify_resource_res_set1_input_txt() {
// verify_resource("res/set1/input.txt".into());
// }
//
// #[test]
// fn verify_resource_res_set2_input_txt() {
// verify_resource("res/set2/input.txt".into());
// }
// ```
#[test_resources("res/*/input.txt")]
fn verify_resource(resource: &str) { assert!(std::path::Path::new(resource).exists()); }
}
#[cfg(test)]
extern crate test_generator_utest;
// demonstrating usage of utest-harness
mod testsuite {
use std::fs::File;
use std::io::prelude::*;
use test_generator_utest::utest;
// Defining a context structure, storing the resources
struct Context<'t> { file: File, name: &'t str }
// Setup - Initializing the resources
fn setup<'t>(filename: &str) -> Context {
// unwrap may panic
Context { file: File::create(filename).unwrap(), name: filename }
}
// Teardown - Releasing the resources
fn teardown(context: Context) {
let Context { file, name } = context;
// drop file resources
std::mem::drop(file);
// unwrap may panic
std::fs::remove_file(name).unwrap();
}
// Test - verify feature
fn test_write_hello_world(ctx: &Context) {
// may panic
let mut file = ctx.file.try_clone().unwrap();
// may panic
file.write_all(b"Hello, world!\n").unwrap();
std::mem::drop(file);
}
// Test - verify feature
fn test_write_hello_europe(ctx: &Context) {
// may panic
let mut file = ctx.file.try_clone().unwrap();
// may panic
file.write_all(b"Hello, Europe!\n").unwrap();
std::mem::drop(file);
}
utest!(hello_world,
|| setup("/tmp/hello_world.txt"),
|ctx_ref| test_write_hello_world(ctx_ref),
|ctx|teardown(ctx));
utest!(hello_europe,
|| setup("/tmp/hello_europe.txt"),
test_write_hello_europe,
teardown);
}
|
// Copyright 2023 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 std::sync::Arc;
use common_base::base::tokio::sync::Semaphore;
use common_base::runtime::Runtime;
use common_catalog::plan::PushDownInfo;
use common_catalog::table_context::TableContext;
use common_exception::Result;
use common_expression::RemoteExpr;
use common_expression::TableSchemaRef;
use common_functions::BUILTIN_FUNCTIONS;
use opendal::Operator;
use storages_common_pruner::BlockMetaIndex;
use storages_common_pruner::Limiter;
use storages_common_pruner::LimiterPrunerCreator;
use storages_common_pruner::PagePruner;
use storages_common_pruner::PagePrunerCreator;
use storages_common_pruner::RangePruner;
use storages_common_pruner::RangePrunerCreator;
use storages_common_pruner::TopNPrunner;
use storages_common_table_meta::meta::BlockMeta;
use storages_common_table_meta::meta::ClusterKey;
use storages_common_table_meta::meta::Location;
use tracing::warn;
use super::create_segment_location_vector;
use crate::pruning::BloomPruner;
use crate::pruning::BloomPrunerCreator;
use crate::pruning::FusePruningStatistics;
use crate::pruning::SegmentPruner;
pub struct PruningContext {
pub ctx: Arc<dyn TableContext>,
pub dal: Operator,
pub pruning_runtime: Arc<Runtime>,
pub pruning_semaphore: Arc<Semaphore>,
pub limit_pruner: Arc<dyn Limiter + Send + Sync>,
pub range_pruner: Arc<dyn RangePruner + Send + Sync>,
pub bloom_pruner: Option<Arc<dyn BloomPruner + Send + Sync>>,
pub page_pruner: Arc<dyn PagePruner + Send + Sync>,
pub pruning_stats: Arc<FusePruningStatistics>,
}
pub struct FusePruner {
pub table_schema: TableSchemaRef,
pub pruning_ctx: Arc<PruningContext>,
pub push_down: Option<PushDownInfo>,
}
impl FusePruner {
// Create normal fuse pruner.
pub fn create(
ctx: &Arc<dyn TableContext>,
dal: Operator,
table_schema: TableSchemaRef,
push_down: &Option<PushDownInfo>,
) -> Result<Self> {
Self::create_with_pages(ctx, dal, table_schema, push_down, None, vec![])
}
// Create fuse pruner with pages.
pub fn create_with_pages(
ctx: &Arc<dyn TableContext>,
dal: Operator,
table_schema: TableSchemaRef,
push_down: &Option<PushDownInfo>,
cluster_key_meta: Option<ClusterKey>,
cluster_keys: Vec<RemoteExpr<String>>,
) -> Result<Self> {
let func_ctx = ctx.get_function_context()?;
let filter_expr = push_down
.as_ref()
.and_then(|extra| extra.filter.as_ref().map(|f| f.as_expr(&BUILTIN_FUNCTIONS)));
// Limit prunner.
// if there are ordering/filter clause, ignore limit, even it has been pushed down
let limit = push_down
.as_ref()
.filter(|p| p.order_by.is_empty() && p.filter.is_none())
.and_then(|p| p.limit);
// prepare the limiter. in case that limit is none, an unlimited limiter will be returned
let limit_pruner = LimiterPrunerCreator::create(limit);
// Range filter.
// if filter_expression is none, an dummy pruner will be returned, which prunes nothing
let range_pruner =
RangePrunerCreator::try_create(func_ctx, &table_schema, filter_expr.as_ref())?;
// Bloom pruner.
// None will be returned, if filter is not applicable (e.g. unsuitable filter expression, index not available, etc.)
let bloom_pruner =
BloomPrunerCreator::create(func_ctx, &table_schema, dal.clone(), filter_expr.as_ref())?;
// Page pruner, used in native format
let page_pruner = PagePrunerCreator::try_create(
func_ctx,
&table_schema,
filter_expr.as_ref(),
cluster_key_meta,
cluster_keys,
)?;
// Constraint the degree of parallelism
let max_threads = ctx.get_settings().get_max_threads()? as usize;
let max_concurrency = {
let max_io_requests = ctx.get_settings().get_max_storage_io_requests()? as usize;
// Prevent us from miss-configured max_storage_io_requests setting, e.g. 0
let v = std::cmp::max(max_io_requests, 10);
if v > max_io_requests {
warn!(
"max_storage_io_requests setting is too low {}, increased to {}",
max_io_requests, v
)
}
v
};
// Pruning runtime.
let pruning_runtime = Arc::new(Runtime::with_worker_threads(
max_threads,
Some("pruning-worker".to_owned()),
)?);
let pruning_semaphore = Arc::new(Semaphore::new(max_concurrency));
let pruning_stats = Arc::new(FusePruningStatistics::default());
let pruning_ctx = Arc::new(PruningContext {
ctx: ctx.clone(),
dal,
pruning_runtime,
pruning_semaphore,
limit_pruner,
range_pruner,
bloom_pruner,
page_pruner,
pruning_stats,
});
Ok(FusePruner {
table_schema,
push_down: push_down.clone(),
pruning_ctx,
})
}
// Pruning chain:
// segment pruner -> block pruner -> topn pruner
pub async fn pruning(
&self,
segment_locs: Vec<Location>,
snapshot_loc: Option<String>,
segment_id_map: Option<HashMap<String, usize>>,
) -> Result<Vec<(BlockMetaIndex, Arc<BlockMeta>)>> {
let segment_locs =
create_segment_location_vector(segment_locs, snapshot_loc, segment_id_map);
// Segment pruner.
let segment_pruner =
SegmentPruner::create(self.pruning_ctx.clone(), self.table_schema.clone())?;
let metas = segment_pruner.pruning(segment_locs).await?;
// TopN pruner.
self.topn_pruning(metas)
}
// topn pruner:
// if there are ordering + limit clause and no filters, use topn pruner
fn topn_pruning(
&self,
metas: Vec<(BlockMetaIndex, Arc<BlockMeta>)>,
) -> Result<Vec<(BlockMetaIndex, Arc<BlockMeta>)>> {
let push_down = self.push_down.clone();
if push_down
.as_ref()
.filter(|p| !p.order_by.is_empty() && p.limit.is_some() && p.filter.is_none())
.is_some()
{
let schema = self.table_schema.clone();
let push_down = push_down.as_ref().unwrap();
let limit = push_down.limit.unwrap();
let sort = push_down.order_by.clone();
let topn_pruner = TopNPrunner::create(schema, sort, limit);
return topn_pruner.prune(metas);
}
Ok(metas)
}
// Pruning stats.
pub fn pruning_stats(&self) -> common_catalog::plan::PruningStatistics {
let stats = self.pruning_ctx.pruning_stats.clone();
let segments_range_pruning_before = stats.get_segments_range_pruning_before() as usize;
let segments_range_pruning_after = stats.get_segments_range_pruning_after() as usize;
let blocks_range_pruning_before = stats.get_blocks_range_pruning_before() as usize;
let blocks_range_pruning_after = stats.get_blocks_range_pruning_after() as usize;
let blocks_bloom_pruning_before = stats.get_blocks_bloom_pruning_before() as usize;
let blocks_bloom_pruning_after = stats.get_blocks_bloom_pruning_after() as usize;
common_catalog::plan::PruningStatistics {
segments_range_pruning_before,
segments_range_pruning_after,
blocks_range_pruning_before,
blocks_range_pruning_after,
blocks_bloom_pruning_before,
blocks_bloom_pruning_after,
}
}
}
|
use geo::algorithm::contains::Contains;
use rustler::types::ListIterator;
use rustler::{Encoder, Env, Error, NifResult, ResourceArc, Term};
mod atoms {
rustler::rustler_atoms! {
atom ok;
//atom error;
atom __true__ = "true";
atom __false__ = "false";
}
}
rustler::rustler_export_nifs! {
"Elixir.Ats.Native",
[
("multi_polygon", 1, multi_polygon),
("multi_polygon_contains?", 2, multi_polygon_contains, rustler::SchedulerFlags::DirtyCpu)
],
Some(on_load)
}
type Point = (f64, f64);
type GeoLine = Vec<Point>;
type Polygon = Vec<GeoLine>;
type MultiPolygon = Vec<Polygon>;
struct Continent {
coordinates: geo::MultiPolygon<f64>,
}
// Define Continent struct on load.
fn on_load<'a>(env: Env<'a>, _load_info: Term<'a>) -> bool {
rustler::resource_struct_init!(Continent, env);
true
}
/// Convert a term as a list iterator and map it with a function.
fn map_nif_list<'a, F, U>(term: Term<'a>, f: F) -> NifResult<Vec<U>>
where
F: Fn(Term<'a>) -> NifResult<U>,
{
let l: ListIterator = term.decode()?;
l.map(f).collect()
}
// Decode a number tuple.
fn decode_point<'a>(term: Term<'a>) -> NifResult<Point> {
let tuple = rustler::types::tuple::get_tuple(term)?;
let mut iter = tuple.into_iter().map(|x| match x.decode::<f64>() {
Ok(x) => Ok(x),
Err(_) => x.decode::<i64>().map(|i| i as f64),
});
let a = iter.next().unwrap()?;
let b = iter.next().unwrap()?;
Ok((a, b))
}
fn multi_polygon<'a>(env: Env<'a>, args: &[Term<'a>]) -> Result<Term<'a>, Error> {
let result: NifResult<MultiPolygon> = map_nif_list(args[0], |x| {
map_nif_list(x, |y| map_nif_list(y, |z| decode_point(z)))
});
let continent = Continent {
coordinates: create_geo_multi_polygon(&result?),
};
Ok(ResourceArc::new(continent).encode(env))
}
fn multi_polygon_contains<'a>(env: Env<'a>, args: &[Term<'a>]) -> Result<Term<'a>, Error> {
let shape: ResourceArc<Continent> = args[0].decode()?;
let point: (f64, f64) = decode_point(args[1])?;
let point: geo::Point<f64> = point.into();
if shape.coordinates.contains(&point) {
Ok(atoms::__true__().encode(env))
} else {
Ok(atoms::__false__().encode(env))
}
}
// Data conversion
fn create_geo_coordinate(point_type: &Point) -> geo::Coordinate<f64> {
geo::Coordinate {
x: point_type.0,
y: point_type.1,
}
}
fn create_geo_line_string(line_type: &GeoLine) -> geo::LineString<f64> {
geo::LineString(
line_type
.iter()
.map(|point_type| create_geo_coordinate(point_type))
.collect(),
)
}
fn create_geo_polygon(polygon_type: &Polygon) -> geo::Polygon<f64> {
let exterior = polygon_type
.get(0)
.map(|e| create_geo_line_string(e))
.unwrap_or_else(|| create_geo_line_string(&vec![]));
let interiors = if polygon_type.len() < 2 {
vec![]
} else {
polygon_type[1..]
.iter()
.map(|line_string_type| create_geo_line_string(line_string_type))
.collect()
};
geo::Polygon::new(exterior, interiors)
}
fn create_geo_multi_polygon(multi_polygon_type: &[Polygon]) -> geo::MultiPolygon<f64> {
geo::MultiPolygon(
multi_polygon_type
.iter()
.map(|polygon_type| create_geo_polygon(&polygon_type))
.collect(),
)
}
|
use gdk::enums::key;
use gdk::DragAction;
use gtk::*;
use url::Url;
use std::ffi::OsStr;
use std::path::PathBuf;
pub fn get_from_treeview_single(treeview: &TreeView, column: Option<i32>) -> Option<PathBuf> {
let selection = treeview.get_selection();
if let Some((model, iter)) = selection.get_selected() {
let res = model
.get_value(&iter, column.unwrap_or(0))
.get::<String>()
.unwrap();
return Some(PathBuf::from(res));
};
None
}
pub fn get_from_treeview_all(treeview: &TreeView, column: Option<i32>) -> Vec<PathBuf> {
let selection = treeview.get_selection();
let prev_mode = selection.get_mode();
if let SelectionMode::None = prev_mode {
selection.set_mode(SelectionMode::Multiple);
};
selection.select_all();
let all = get_from_treeview_multiple(&treeview, column);
selection.unselect_all();
selection.set_mode(prev_mode);
all
}
pub fn get_from_treeview_multiple(treeview: &TreeView, column: Option<i32>) -> Vec<PathBuf> {
let selection = treeview.get_selection();
let (paths, model) = selection.get_selected_rows();
paths
.iter()
.map(|path| {
let iter = model.get_iter(path).unwrap();
let s = model
.get_value(&iter, column.unwrap_or(0))
.get::<String>()
.unwrap();
PathBuf::from(s)
})
.collect()
}
// common for rrxml and mydxf views
pub fn treeview_connect_key_press(treeview: &TreeView, store: &ListStore) {
treeview.connect_key_press_event(clone!(treeview, store => move |_, key| {
// if event_key
let keyval = key.get_keyval();
if keyval == key::Delete {
let selection = treeview.get_selection();
let (paths, model) = selection.get_selected_rows();
for path in paths {
let iter = model.get_iter(&path).unwrap();
store.remove(&iter);
}
};
Inhibit(false)
}));
}
// common for rrxml and mydxf views
pub fn treeview_connect_with_drag_data_filtered(
treeview: &TreeView,
store: &ListStore,
filter: &'static str,
) {
let targets = vec![gtk::TargetEntry::new(
"text/uri-list",
TargetFlags::OTHER_APP,
0,
)];
treeview.drag_dest_set(DestDefaults::ALL, &targets, DragAction::COPY);
treeview.connect_drag_data_received(clone!( store => move |_w, _, _, _, d, _, _| {
let accepted_ext = Some(OsStr::new(filter));
for file in d.get_uris() {
let url = Url::parse(&file).expect("bad uri");
let path = url.to_file_path().unwrap();
if path.extension() != accepted_ext {
continue;
};
info!("got via drag&drop: {:?}", path);
let path = path.to_str().unwrap();
store_insert(&store, path);
}
}));
}
pub fn store_insert(store: &ListStore, s: &str) {
store.insert_with_values(None, &[0], &[&s]);
}
|
pub mod into_boxed;
pub mod lazy_option;
pub mod bool_cmpxchg;
pub mod option_overwrite;
|
pub struct Solution;
impl Solution {
pub fn max_sub_array(nums: Vec<i32>) -> i32 {
if nums.len() == 0 {
return 0;
}
let mut max_sum = std::i32::MIN;
let mut cur_sum = 0;
for val in nums {
cur_sum += val;
if cur_sum > max_sum {
max_sum = cur_sum;
}
if cur_sum < 0 {
cur_sum = 0;
}
}
max_sum
}
}
#[test]
fn test0053() {
assert_eq!(
Solution::max_sub_array(vec![-2, 1, -3, 4, -1, 2, 1, -5, 4]),
6
);
assert_eq!(Solution::max_sub_array(vec![-1]), -1);
}
|
#[repr(C)]
{maybe_pub}struct {name}([u8; ::type_sizes::{size_const_name}]);
impl ::cpp_utils::new_uninitialized::NewUninitialized for {name} {{
unsafe fn new_uninitialized() -> {name} {{
{name}(::std::mem::uninitialized())
}}
}}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type CardAddedEventArgs = *mut ::core::ffi::c_void;
pub type CardRemovedEventArgs = *mut ::core::ffi::c_void;
pub type SmartCard = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardActivationPolicyChangeResult(pub i32);
impl SmartCardActivationPolicyChangeResult {
pub const Denied: Self = Self(0i32);
pub const Allowed: Self = Self(1i32);
}
impl ::core::marker::Copy for SmartCardActivationPolicyChangeResult {}
impl ::core::clone::Clone for SmartCardActivationPolicyChangeResult {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardAppletIdGroup = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardAppletIdGroupActivationPolicy(pub i32);
impl SmartCardAppletIdGroupActivationPolicy {
pub const Disabled: Self = Self(0i32);
pub const ForegroundOverride: Self = Self(1i32);
pub const Enabled: Self = Self(2i32);
}
impl ::core::marker::Copy for SmartCardAppletIdGroupActivationPolicy {}
impl ::core::clone::Clone for SmartCardAppletIdGroupActivationPolicy {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardAppletIdGroupRegistration = *mut ::core::ffi::c_void;
pub type SmartCardAutomaticResponseApdu = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardAutomaticResponseStatus(pub i32);
impl SmartCardAutomaticResponseStatus {
pub const None: Self = Self(0i32);
pub const Success: Self = Self(1i32);
pub const UnknownError: Self = Self(2i32);
}
impl ::core::marker::Copy for SmartCardAutomaticResponseStatus {}
impl ::core::clone::Clone for SmartCardAutomaticResponseStatus {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardChallengeContext = *mut ::core::ffi::c_void;
pub type SmartCardConnection = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardCryptogramAlgorithm(pub i32);
impl SmartCardCryptogramAlgorithm {
pub const None: Self = Self(0i32);
pub const CbcMac: Self = Self(1i32);
pub const Cvc3Umd: Self = Self(2i32);
pub const DecimalizedMsd: Self = Self(3i32);
pub const Cvc3MD: Self = Self(4i32);
pub const Sha1: Self = Self(5i32);
pub const SignedDynamicApplicationData: Self = Self(6i32);
pub const RsaPkcs1: Self = Self(7i32);
pub const Sha256Hmac: Self = Self(8i32);
}
impl ::core::marker::Copy for SmartCardCryptogramAlgorithm {}
impl ::core::clone::Clone for SmartCardCryptogramAlgorithm {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardCryptogramGenerator = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardCryptogramGeneratorOperationStatus(pub i32);
impl SmartCardCryptogramGeneratorOperationStatus {
pub const Success: Self = Self(0i32);
pub const AuthorizationFailed: Self = Self(1i32);
pub const AuthorizationCanceled: Self = Self(2i32);
pub const AuthorizationRequired: Self = Self(3i32);
pub const CryptogramMaterialPackageStorageKeyExists: Self = Self(4i32);
pub const NoCryptogramMaterialPackageStorageKey: Self = Self(5i32);
pub const NoCryptogramMaterialPackage: Self = Self(6i32);
pub const UnsupportedCryptogramMaterialPackage: Self = Self(7i32);
pub const UnknownCryptogramMaterialName: Self = Self(8i32);
pub const InvalidCryptogramMaterialUsage: Self = Self(9i32);
pub const ApduResponseNotSent: Self = Self(10i32);
pub const OtherError: Self = Self(11i32);
pub const ValidationFailed: Self = Self(12i32);
pub const NotSupported: Self = Self(13i32);
}
impl ::core::marker::Copy for SmartCardCryptogramGeneratorOperationStatus {}
impl ::core::clone::Clone for SmartCardCryptogramGeneratorOperationStatus {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardCryptogramGetAllCryptogramMaterialCharacteristicsResult = *mut ::core::ffi::c_void;
pub type SmartCardCryptogramGetAllCryptogramMaterialPackageCharacteristicsResult = *mut ::core::ffi::c_void;
pub type SmartCardCryptogramGetAllCryptogramStorageKeyCharacteristicsResult = *mut ::core::ffi::c_void;
pub type SmartCardCryptogramMaterialCharacteristics = *mut ::core::ffi::c_void;
pub type SmartCardCryptogramMaterialPackageCharacteristics = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardCryptogramMaterialPackageConfirmationResponseFormat(pub i32);
impl SmartCardCryptogramMaterialPackageConfirmationResponseFormat {
pub const None: Self = Self(0i32);
pub const VisaHmac: Self = Self(1i32);
}
impl ::core::marker::Copy for SmartCardCryptogramMaterialPackageConfirmationResponseFormat {}
impl ::core::clone::Clone for SmartCardCryptogramMaterialPackageConfirmationResponseFormat {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardCryptogramMaterialPackageFormat(pub i32);
impl SmartCardCryptogramMaterialPackageFormat {
pub const None: Self = Self(0i32);
pub const JweRsaPki: Self = Self(1i32);
}
impl ::core::marker::Copy for SmartCardCryptogramMaterialPackageFormat {}
impl ::core::clone::Clone for SmartCardCryptogramMaterialPackageFormat {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardCryptogramMaterialPossessionProof = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardCryptogramMaterialProtectionMethod(pub i32);
impl SmartCardCryptogramMaterialProtectionMethod {
pub const None: Self = Self(0i32);
pub const WhiteBoxing: Self = Self(1i32);
}
impl ::core::marker::Copy for SmartCardCryptogramMaterialProtectionMethod {}
impl ::core::clone::Clone for SmartCardCryptogramMaterialProtectionMethod {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardCryptogramMaterialType(pub i32);
impl SmartCardCryptogramMaterialType {
pub const None: Self = Self(0i32);
pub const StaticDataAuthentication: Self = Self(1i32);
pub const TripleDes112: Self = Self(2i32);
pub const Aes: Self = Self(3i32);
pub const RsaPkcs1: Self = Self(4i32);
}
impl ::core::marker::Copy for SmartCardCryptogramMaterialType {}
impl ::core::clone::Clone for SmartCardCryptogramMaterialType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardCryptogramPlacementOptions(pub u32);
impl SmartCardCryptogramPlacementOptions {
pub const None: Self = Self(0u32);
pub const UnitsAreInNibbles: Self = Self(1u32);
pub const ChainOutput: Self = Self(2u32);
}
impl ::core::marker::Copy for SmartCardCryptogramPlacementOptions {}
impl ::core::clone::Clone for SmartCardCryptogramPlacementOptions {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardCryptogramPlacementStep = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardCryptogramStorageKeyAlgorithm(pub i32);
impl SmartCardCryptogramStorageKeyAlgorithm {
pub const None: Self = Self(0i32);
pub const Rsa2048: Self = Self(1i32);
}
impl ::core::marker::Copy for SmartCardCryptogramStorageKeyAlgorithm {}
impl ::core::clone::Clone for SmartCardCryptogramStorageKeyAlgorithm {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardCryptogramStorageKeyCapabilities(pub u32);
impl SmartCardCryptogramStorageKeyCapabilities {
pub const None: Self = Self(0u32);
pub const HardwareProtection: Self = Self(1u32);
pub const UnlockPrompt: Self = Self(2u32);
}
impl ::core::marker::Copy for SmartCardCryptogramStorageKeyCapabilities {}
impl ::core::clone::Clone for SmartCardCryptogramStorageKeyCapabilities {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardCryptogramStorageKeyCharacteristics = *mut ::core::ffi::c_void;
pub type SmartCardCryptogramStorageKeyInfo = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardCryptographicKeyAttestationStatus(pub i32);
impl SmartCardCryptographicKeyAttestationStatus {
pub const NoAttestation: Self = Self(0i32);
pub const SoftwareKeyWithoutTpm: Self = Self(1i32);
pub const SoftwareKeyWithTpm: Self = Self(2i32);
pub const TpmKeyUnknownAttestationStatus: Self = Self(3i32);
pub const TpmKeyWithoutAttestationCapability: Self = Self(4i32);
pub const TpmKeyWithTemporaryAttestationFailure: Self = Self(5i32);
pub const TpmKeyWithLongTermAttestationFailure: Self = Self(6i32);
pub const TpmKeyWithAttestation: Self = Self(7i32);
}
impl ::core::marker::Copy for SmartCardCryptographicKeyAttestationStatus {}
impl ::core::clone::Clone for SmartCardCryptographicKeyAttestationStatus {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardEmulationCategory(pub i32);
impl SmartCardEmulationCategory {
pub const Other: Self = Self(0i32);
pub const Payment: Self = Self(1i32);
}
impl ::core::marker::Copy for SmartCardEmulationCategory {}
impl ::core::clone::Clone for SmartCardEmulationCategory {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardEmulationType(pub i32);
impl SmartCardEmulationType {
pub const Host: Self = Self(0i32);
pub const Uicc: Self = Self(1i32);
pub const EmbeddedSE: Self = Self(2i32);
}
impl ::core::marker::Copy for SmartCardEmulationType {}
impl ::core::clone::Clone for SmartCardEmulationType {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardEmulator = *mut ::core::ffi::c_void;
pub type SmartCardEmulatorApduReceivedEventArgs = *mut ::core::ffi::c_void;
pub type SmartCardEmulatorConnectionDeactivatedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardEmulatorConnectionDeactivatedReason(pub i32);
impl SmartCardEmulatorConnectionDeactivatedReason {
pub const ConnectionLost: Self = Self(0i32);
pub const ConnectionRedirected: Self = Self(1i32);
}
impl ::core::marker::Copy for SmartCardEmulatorConnectionDeactivatedReason {}
impl ::core::clone::Clone for SmartCardEmulatorConnectionDeactivatedReason {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardEmulatorConnectionProperties = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardEmulatorConnectionSource(pub i32);
impl SmartCardEmulatorConnectionSource {
pub const Unknown: Self = Self(0i32);
pub const NfcReader: Self = Self(1i32);
}
impl ::core::marker::Copy for SmartCardEmulatorConnectionSource {}
impl ::core::clone::Clone for SmartCardEmulatorConnectionSource {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardEmulatorEnablementPolicy(pub i32);
impl SmartCardEmulatorEnablementPolicy {
pub const Never: Self = Self(0i32);
pub const Always: Self = Self(1i32);
pub const ScreenOn: Self = Self(2i32);
pub const ScreenUnlocked: Self = Self(3i32);
}
impl ::core::marker::Copy for SmartCardEmulatorEnablementPolicy {}
impl ::core::clone::Clone for SmartCardEmulatorEnablementPolicy {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardLaunchBehavior(pub i32);
impl SmartCardLaunchBehavior {
pub const Default: Self = Self(0i32);
pub const AboveLock: Self = Self(1i32);
}
impl ::core::marker::Copy for SmartCardLaunchBehavior {}
impl ::core::clone::Clone for SmartCardLaunchBehavior {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardPinCharacterPolicyOption(pub i32);
impl SmartCardPinCharacterPolicyOption {
pub const Allow: Self = Self(0i32);
pub const RequireAtLeastOne: Self = Self(1i32);
pub const Disallow: Self = Self(2i32);
}
impl ::core::marker::Copy for SmartCardPinCharacterPolicyOption {}
impl ::core::clone::Clone for SmartCardPinCharacterPolicyOption {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardPinPolicy = *mut ::core::ffi::c_void;
pub type SmartCardPinResetDeferral = *mut ::core::ffi::c_void;
pub type SmartCardPinResetHandler = *mut ::core::ffi::c_void;
pub type SmartCardPinResetRequest = *mut ::core::ffi::c_void;
pub type SmartCardProvisioning = *mut ::core::ffi::c_void;
pub type SmartCardReader = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardReaderKind(pub i32);
impl SmartCardReaderKind {
pub const Any: Self = Self(0i32);
pub const Generic: Self = Self(1i32);
pub const Tpm: Self = Self(2i32);
pub const Nfc: Self = Self(3i32);
pub const Uicc: Self = Self(4i32);
pub const EmbeddedSE: Self = Self(5i32);
}
impl ::core::marker::Copy for SmartCardReaderKind {}
impl ::core::clone::Clone for SmartCardReaderKind {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardReaderStatus(pub i32);
impl SmartCardReaderStatus {
pub const Disconnected: Self = Self(0i32);
pub const Ready: Self = Self(1i32);
pub const Exclusive: Self = Self(2i32);
}
impl ::core::marker::Copy for SmartCardReaderStatus {}
impl ::core::clone::Clone for SmartCardReaderStatus {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardStatus(pub i32);
impl SmartCardStatus {
pub const Disconnected: Self = Self(0i32);
pub const Ready: Self = Self(1i32);
pub const Shared: Self = Self(2i32);
pub const Exclusive: Self = Self(3i32);
pub const Unresponsive: Self = Self(4i32);
}
impl ::core::marker::Copy for SmartCardStatus {}
impl ::core::clone::Clone for SmartCardStatus {
fn clone(&self) -> Self {
*self
}
}
pub type SmartCardTriggerDetails = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct SmartCardTriggerType(pub i32);
impl SmartCardTriggerType {
pub const EmulatorTransaction: Self = Self(0i32);
pub const EmulatorNearFieldEntry: Self = Self(1i32);
pub const EmulatorNearFieldExit: Self = Self(2i32);
pub const EmulatorHostApplicationActivated: Self = Self(3i32);
pub const EmulatorAppletIdGroupRegistrationChanged: Self = Self(4i32);
pub const ReaderCardAdded: Self = Self(5i32);
}
impl ::core::marker::Copy for SmartCardTriggerType {}
impl ::core::clone::Clone for SmartCardTriggerType {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct SmartCardUnlockPromptingBehavior(pub i32);
impl SmartCardUnlockPromptingBehavior {
pub const AllowUnlockPrompt: Self = Self(0i32);
pub const RequireUnlockPrompt: Self = Self(1i32);
pub const PreventUnlockPrompt: Self = Self(2i32);
}
impl ::core::marker::Copy for SmartCardUnlockPromptingBehavior {}
impl ::core::clone::Clone for SmartCardUnlockPromptingBehavior {
fn clone(&self) -> Self {
*self
}
}
|
#[cfg(all(not(target_arch = "wasm32"), test))]
mod test;
use liblumen_alloc::erts::term::prelude::Term;
/// `/=/2` infix operator. Unlike `=/=`, converts between floats and integers.
#[native_implemented::function(erlang:/=/2)]
pub fn result(left: Term, right: Term) -> Term {
left.ne(&right).into()
}
|
//! State transition types
use borsh::{BorshDeserialize, BorshSchema, BorshSerialize};
use crate::{
borsh_state::{BorshState, InitBorshState},
error::Error,
};
use solana_program::{
account_info::AccountInfo, entrypoint::ProgramResult, program_error::ProgramError,
program_pack::IsInitialized,
};
struct Decimal {
pub value: u128,
pub decimals: u32,
}
#[derive(Clone, Debug, BorshSerialize, BorshDeserialize, BorshSchema, Default, PartialEq)]
pub struct PublicKey(pub [u8; 32]);
impl PublicKey {
pub fn is_account(&self, info: &AccountInfo) -> bool {
self.eq(&PublicKey(info.key.to_bytes()))
}
}
impl<'a> From<&'a AccountInfo<'a>> for PublicKey {
fn from(info: &'a AccountInfo<'a>) -> Self {
PublicKey(info.key.to_bytes())
}
}
pub trait Authority {
fn authority(&self) -> &PublicKey;
fn authorize(&self, account: &AccountInfo) -> ProgramResult {
if !account.is_signer {
return Err(ProgramError::MissingRequiredSignature);
}
if self.authority().0 != account.key.to_bytes() {
return Err(Error::OwnerMismatch)?;
}
Ok(())
}
}
#[derive(Clone, Debug, BorshSerialize, BorshDeserialize, BorshSchema, Default, PartialEq)]
pub struct ImpermenantLossStopLossConfig {
/// min_change_factor for stop-loss
pub min_change_factor: u64,
// token_a liquidity PK
pub token_a: PublicKey,
// token_b liquidity PK
pub token_b: PublicKey,
// token_a starting price
pub token_a_starting_price: u64,
// token_b starting price
pub token_b_starting_price: u64,
// liquidity_contract PK
pub liquidity_contract: PublicKey
}
/// Aggregator data.
#[derive(Clone, Debug, BorshSerialize, BorshDeserialize, BorshSchema, Default, PartialEq)]
pub struct ImpermenantLossStopLoss {
pub config: ImpermenantLossStopLossConfig,
/// is initialized
pub is_initialized: bool,
/// authority
pub owner: PublicKey,
/// min_change_factor for stop-loss
pub min_change_factor: u64,
// token_a liquidity PK
pub token_a: PublicKey,
// token_b liquidity PK
pub token_b: PublicKey,
// token_a starting price
pub token_a_starting_price: u64,
// token_b starting price
pub token_b_starting_price: u64,
// liquidity_contract PK
pub liquidity_contract: PublicKey
}
impl ImpermenantLossStopLoss {
}
impl Authority for ImpermenantLossStopLoss {
fn authority(&self) -> &PublicKey {
&self.owner
}
}
impl IsInitialized for ImpermenantLossStopLoss {
fn is_initialized(&self) -> bool {
self.is_initialized
}
}
impl BorshState for ImpermenantLossStopLoss {}
impl InitBorshState for ImpermenantLossStopLoss {}
mod tests {
use crate::borsh_utils;
use super::*;
#[test]
fn test_packed_len() {
println!(
"ImpermenantLossStopLoss len: {}",
borsh_utils::get_packed_len::<ImpermenantLossStopLoss>()
);
println!(
"ImpermenantLossStopLossConfig len: {}",
borsh_utils::get_packed_len::<ImpermenantLossStopLossConfig>()
);
}
}
|
// MinIO Rust Library for Amazon S3 Compatible Cloud Storage
// Copyright 2022 MinIO, Inc.
//
// 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.
#[derive(Clone, Debug, Default)]
pub struct Credentials {
pub access_key: String,
pub secret_key: String,
pub session_token: Option<String>,
}
pub trait Provider: std::fmt::Debug {
fn fetch(&self) -> Credentials;
}
#[derive(Clone, Debug)]
pub struct StaticProvider {
creds: Credentials,
}
impl StaticProvider {
pub fn new(access_key: &str, secret_key: &str, session_token: Option<&str>) -> StaticProvider {
StaticProvider {
creds: Credentials {
access_key: access_key.to_string(),
secret_key: secret_key.to_string(),
session_token: session_token.map(|v| v.to_string()),
},
}
}
}
impl Provider for StaticProvider {
fn fetch(&self) -> Credentials {
self.creds.clone()
}
}
|
use crate::database::Database;
use bitflags::_core::fmt::Debug;
use crate::Result;
use crate::types::chrono::NaiveDateTime;
use chrono::Local;
/// Associate [`Database`] with a `RawValue` of a generic lifetime.
///
/// ---
///
/// The upcoming Rust feature, [Generic Associated Types], should obviate
/// the need for this trait.
///
/// [Generic Associated Types]: https://www.google.com/search?q=generic+associated+types+rust&oq=generic+associated+types+rust&aqs=chrome..69i57j0l5.3327j0j7&sourceid=chrome&ie=UTF-8
pub trait HasRawValue<'c> {
type Database: Database;
/// The Rust type used to hold a not-yet-decoded value that has just been
/// received from the database.
type RawValue: RawValue<'c, Database = Self::Database>+Debug;
}
pub trait RawValue<'c> {
type Database: Database;
fn type_info(&self) -> Option<<Self::Database as Database>::TypeInfo>;
/// to an json value
fn try_to_json(&self) -> Result<serde_json::Value>;
}
pub trait DateTimeNow{
fn now()->NaiveDateTime;
}
impl DateTimeNow for NaiveDateTime{
fn now() -> NaiveDateTime {
let dt = Local::now();
dt.naive_local()
}
} |
mod mesh;
use std::fs::File;
use glium::{
draw_parameters::DrawParameters, implement_vertex, index, uniform, Display, Frame, Program,
Surface, VertexBuffer,
};
use glium_text::{FontTexture, TextDisplay, TextSystem};
use nalgebra::{Matrix4, Point3, Vector3, Vector4};
use mesh::Mesh;
const VERTEX_SHADER_SRC: &'static str = r#"
#version 140
in vec3 position;
uniform mat4 matrix;
uniform vec3 color;
out vec3 in_color;
void main() {
gl_Position = matrix * vec4(position, 1.0);
in_color = color;
}
"#;
const FRAGMENT_SHADER_SRC: &'static str = r#"
#version 140
in vec3 in_color;
out vec4 color;
void main() {
color = vec4(in_color, 1.0);
}
"#;
#[derive(Debug, Clone, Copy)]
struct Vertex {
position: [f32; 3],
}
implement_vertex!(Vertex, position);
pub struct Renderer {
program: Program,
text_system: TextSystem,
font: FontTexture,
sphere: Mesh,
}
impl Renderer {
pub fn new(display: &Display) -> Self {
let text_system = TextSystem::new(display);
let font = FontTexture::new(display, File::open("DejaVuSans.ttf").unwrap(), 24).unwrap();
Renderer {
program: Program::from_source(display, VERTEX_SHADER_SRC, FRAGMENT_SHADER_SRC, None)
.unwrap(),
text_system,
font,
sphere: Mesh::sphere(display),
}
}
pub fn draw(&mut self, display: &Display, t: f32, satellites: Vec<(u8, Vector3<f64>)>) {
let mut target = display.draw();
target.clear_color(0.0, 0.0, 0.02, 1.0);
let (width, height) = target.get_dimensions();
let aspect = width as f32 / height as f32;
let period = 20.0;
let dist = 80e6;
let matrix = Matrix4::new_perspective(aspect, 45.0_f32.to_radians(), 1000.0, 1e9)
* Matrix4::look_at_rh(
&Point3::new(
dist * (6.28 * t / period).sin(),
dist / 2.0,
dist * (6.28 * t / period).cos(),
),
&Point3::new(0.0, 0.0, 0.0),
&Vector3::new(0.0, 1.0, 0.0),
);
let uniforms = uniform! {
matrix: *(matrix.prepend_scaling(6371000.0)).as_ref(),
color: [0.4_f32, 1.0, 0.4],
};
self.sphere
.draw(&mut target, &self.program, &uniforms, &Default::default());
let scale = 5e5;
let sat_vertex_buffer = VertexBuffer::new(
display,
&vec![
Vertex {
position: [-scale, 0.0, 0.0],
},
Vertex {
position: [scale, 0.0, 0.0],
},
Vertex {
position: [0.0, -scale, 0.0],
},
Vertex {
position: [0.0, scale, 0.0],
},
Vertex {
position: [0.0, 0.0, -scale],
},
Vertex {
position: [0.0, 0.0, scale],
},
],
)
.unwrap();
let sat_index_buffer = index::NoIndices(index::PrimitiveType::LinesList);
for (sv_id, position) in satellites {
let pos = Vector3::new(position.x as f32, position.y as f32, position.z as f32);
let matrix = matrix.prepend_translation(&pos);
let uniforms = uniform! {
matrix: *matrix.as_ref(),
color: [0.0_f32, 0.8, 1.0],
};
target
.draw(
&sat_vertex_buffer,
&sat_index_buffer,
&self.program,
&uniforms,
&Default::default(),
)
.unwrap();
let satellite_pos = matrix * Vector4::new(0.0, 0.0, 0.0, 1.0);
let matrix = Matrix4::<f32>::identity()
.prepend_translation(&Vector3::new(
satellite_pos.x / satellite_pos.w,
satellite_pos.y / satellite_pos.w,
0.0,
))
.prepend_nonuniform_scaling(&Vector3::new(1.0 / 40.0 / aspect, 1.0 / 40.0, 1.0));
let label = format!("{}", sv_id);
self.draw_text(&mut target, &label, matrix, Default::default());
}
target.finish().unwrap();
}
fn draw_text(
&self,
target: &mut Frame,
text: &str,
matrix: Matrix4<f32>,
draw_parameters: DrawParameters,
) {
let text = TextDisplay::new(&self.text_system, &self.font, text);
glium_text::draw(
&text,
&self.text_system,
target,
*matrix.as_ref(),
(1.0, 1.0, 1.0, 1.0),
draw_parameters.clone(),
);
}
}
|
fn main() {
if std::env::var("CARGO_FEATURE_LIBDWARF").is_ok() {
println!("cargo:rustc-link-lib=static=dwarf");
}
if std::env::var("CARGO_FEATURE_ELFUTILS").is_ok() {
println!("cargo:rustc-link-lib=dylib=dw");
}
println!("cargo:rustc-link-lib=dylib=elf");
println!("cargo:rustc-link-lib=dylib=z");
println!("cargo:rustc-link-search=native=/usr/local/lib");
}
|
// Copyright 2020-2021, The Tremor Team
//
// 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 crate::errors::{Error, Result};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
/// The type or resource the url references
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
pub enum ResourceType {
/// This is a pipeline
Pipeline,
/// This is an onramp
Onramp,
/// This is an offramp
Offramp,
/// This is a binding
Binding,
}
/// The scrope of the URL
#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug)]
pub enum Scope {
/// This URL identifies a specific port
Port,
/// This URL identifies a servant (a running instance)
Servant,
/// This URL identifes an artefact (a non running configuration)
Artefact,
/// This URL identifies a type of artefact
Type,
}
/// module for standard port names
pub mod ports {
use beef::Cow;
/// standard input port
pub const IN: Cow<'static, str> = Cow::const_str("in");
/// standard output port
pub const OUT: Cow<'static, str> = Cow::const_str("out");
/// standard err port
pub const ERR: Cow<'static, str> = Cow::const_str("err");
/// standard metrics port
pub const METRICS: Cow<'static, str> = Cow::const_str("metrics");
}
/// A tremor URL identifying an entity in tremor
#[allow(clippy::module_name_repetitions)]
#[derive(Clone, Eq, PartialEq, Hash, Debug)]
pub struct TremorUrl {
scope: Scope,
host: String,
resource_type: Option<ResourceType>,
artefact: Option<String>,
instance: Option<String>,
instance_port: Option<String>,
}
fn decode_type(t: &str) -> Result<ResourceType> {
match t {
"pipeline" => Ok(ResourceType::Pipeline),
"onramp" => Ok(ResourceType::Onramp),
"offramp" => Ok(ResourceType::Offramp),
"binding" => Ok(ResourceType::Binding),
other => Err(format!("Bad Resource type: {}", other).into()),
}
}
impl fmt::Display for ResourceType {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
Self::Pipeline => write!(f, "pipeline"),
Self::Onramp => write!(f, "onramp"),
Self::Offramp => write!(f, "offramp"),
Self::Binding => write!(f, "binding"),
}
}
}
impl fmt::Display for TremorUrl {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let r = write!(f, "tremor://{}", self.host);
if let Some(resource_type) = &self.resource_type {
write!(f, "/{}", resource_type)?;
if let Some(artefact) = &self.artefact {
write!(f, "/{}", artefact)?;
if let Some(instance) = &self.instance {
write!(f, "/{}", instance)?;
if let Some(instance_port) = &self.instance_port {
write!(f, "/{}", instance_port)?;
};
};
};
};
r
}
}
impl TremorUrl {
/// Generates a minimal id of the form "{pfx}-{artefact}.{instance}"
#[must_use]
pub fn short_id(&self, pfx: &str) -> String {
let artefact_id = self.artefact().unwrap_or("-");
let instance_id = self.instance().unwrap_or("-");
format!("{}-{}.{}", pfx, artefact_id, instance_id)
}
/// Creates an URL from a given onramp id
///
/// # Errors
/// * if the id isn't a valid onramp id
pub fn from_onramp_id(id: &str) -> Result<Self> {
Self::parse(&format!("/onramp/{}", id))
}
/// Creates an URL from a given offramp id
///
/// # Errors
/// * if the passed ID isn't a valid offramp id
pub fn from_offramp_id(id: &str) -> Result<Self> {
Self::parse(&format!("/offramp/{}", id))
}
/// Parses a string into a Trmeor URL
///
/// # Errors
/// * If the url is not a valid tremor url
pub fn parse(url: &str) -> Result<Self> {
let (r, relative) = Self::parse_url(url, false)?;
if let Some(parts) = r
.path_segments()
.map(std::iter::Iterator::collect::<Vec<_>>)
{
let (scope, resource_type, artefact, instance, instance_port) = if relative {
// TODO: This is not correct!
match parts.as_slice() {
[port] => (Scope::Servant, None, None, None, Some((*port).to_string())),
[instance, port] => (
Scope::Type,
None,
None,
Some((*instance).to_string()),
Some((*port).to_string()),
),
[artefact, instance, port] => (
Scope::Artefact,
None,
Some((*artefact).to_string()),
Some((*instance).to_string()),
Some((*port).to_string()),
),
[resource_type, artefact, instance, port] => (
Scope::Port,
Some(decode_type(resource_type)?),
Some((*artefact).to_string()),
Some((*instance).to_string()),
Some((*port).to_string()),
),
_ => return Err(format!("Bad URL: {}", url).into()),
}
} else {
match parts.as_slice() {
[resource_type, artefact, instance, port] => (
Scope::Port,
Some(decode_type(resource_type)?),
Some((*artefact).to_string()),
Some((*instance).to_string()),
Some((*port).to_string()),
),
[resource_type, artefact, instance] => (
Scope::Servant,
Some(decode_type(resource_type)?),
Some((*artefact).to_string()),
Some((*instance).to_string()),
None,
),
[resource_type, artefact] => (
Scope::Artefact,
Some(decode_type(resource_type)?),
Some((*artefact).to_string()),
None,
None,
),
[resource_type] => (
Scope::Type,
Some(decode_type(resource_type)?),
None,
None,
None,
),
_ => return Err(format!("Bad URL: {}", url).into()),
}
};
let host = r.host_str().unwrap_or("localhost").to_owned();
Ok(Self {
scope,
host,
resource_type,
artefact,
instance,
instance_port,
})
} else {
Err(format!("Bad URL: {}", url).into())
}
}
fn parse_url(url: &str, relative: bool) -> Result<(url::Url, bool)> {
match url::Url::parse(url) {
Ok(r) => Ok((r, relative)),
Err(url::ParseError::RelativeUrlWithoutBase) => match url.get(0..1) {
Some("/") => Self::parse_url(&format!("tremor://{}", url), false),
_ => Self::parse_url(&format!("tremor:///{}", url), true),
},
Err(e) => Err(e.into()),
}
}
/// Trims the url to the instance
pub fn trim_to_instance(&mut self) {
self.instance_port = None;
self.scope = Scope::Servant;
}
/// Trims the url to the artefact
pub fn trim_to_artefact(&mut self) {
self.instance_port = None;
self.instance = None;
self.scope = Scope::Artefact;
}
/// Sets the instance of the URL, will extend
/// the scope to `Scope::Servant` if it was
/// `Artefact` before.
pub fn set_instance<S>(&mut self, i: &S)
where
S: ToString + ?Sized,
{
self.instance = Some(i.to_string());
if self.scope == Scope::Artefact {
self.scope = Scope::Servant;
}
}
/// Sets the port of the URL, will extend
/// the scope to `Scope::Port` if it was
/// `Servant` before.
pub fn set_port<S>(&mut self, i: &S)
where
S: ToString + ?Sized,
{
self.instance_port = Some(i.to_string());
if self.scope == Scope::Servant {
self.scope = Scope::Port;
}
}
/// Retrives the instance
#[must_use]
pub fn instance(&self) -> Option<&str> {
self.instance.as_deref()
}
/// Retrives the artefact
#[must_use]
pub fn artefact(&self) -> Option<&str> {
self.artefact.as_deref()
}
/// Retrives the port
#[must_use]
pub fn instance_port(&self) -> Option<&str> {
self.instance_port.as_deref()
}
/// Retrives the port
///
/// # Errors
/// * if the URL has no port
pub fn instance_port_required(&self) -> Result<&str> {
self.instance_port()
.ok_or_else(|| Error::from(format!("{} is missing an instance port", self)))
}
/// Retrives the type
#[must_use]
pub fn resource_type(&self) -> Option<ResourceType> {
self.resource_type
}
/// Retrives the scope
#[must_use]
pub fn scope(&self) -> Scope {
self.scope
}
/// returns true if `self` and `other` refer to the same instance, ignoring the port
#[must_use]
pub fn same_instance_as(&self, other: &Self) -> bool {
self.host == other.host
&& self.resource_type == other.resource_type
&& self.artefact == other.artefact
&& self.instance == other.instance
}
}
impl<'de> Deserialize<'de> for TremorUrl {
fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
where
D: Deserializer<'de>,
{
use serde::de::Error;
let s = String::deserialize(deserializer)?;
Self::parse(&s).map_err(|err| Error::custom(err.to_string()))
}
}
impl Serialize for TremorUrl {
fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!("{}", self))
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn bad_url() {
assert!(TremorUrl::parse("snot://").is_err())
}
#[test]
fn bad_url2() {
assert!(TremorUrl::parse("foo/bar/baz/bogo/mips/snot").is_err())
}
#[test]
fn url() -> Result<()> {
let url = TremorUrl::parse("tremor://127.0.0.1:1234/pipeline/main/01/in?format=json")?;
assert_eq!(Scope::Port, url.scope());
assert_eq!(Some(ResourceType::Pipeline), url.resource_type());
assert_eq!(Some("main"), url.artefact());
assert_eq!(Some("01"), url.instance());
assert_eq!(Some("in"), url.instance_port());
Ok(())
}
#[test]
fn short_url() -> Result<()> {
let url = TremorUrl::parse("/pipeline/main/01/in")?;
assert_eq!(Scope::Port, url.scope());
assert_eq!(Some(ResourceType::Pipeline), url.resource_type());
assert_eq!(Some("main"), url.artefact());
assert_eq!(Some("01"), url.instance());
assert_eq!(Some(ports::IN.as_ref()), url.instance_port());
Ok(())
}
#[test]
fn from_onramp_id() -> Result<()> {
let url = TremorUrl::from_onramp_id("test")?;
assert_eq!(Some(ResourceType::Onramp), url.resource_type());
assert_eq!(Some("test"), url.artefact());
Ok(())
}
#[test]
fn from_offramp_id() -> Result<()> {
let url = TremorUrl::from_offramp_id("test")?;
assert_eq!(Some(ResourceType::Offramp), url.resource_type());
assert_eq!(Some("test"), url.artefact());
Ok(())
}
#[test]
fn test_servant_scope() -> Result<()> {
let url = TremorUrl::parse("in")?;
assert_eq!(Scope::Servant, url.scope());
assert_eq!(None, url.resource_type());
assert_eq!(None, url.artefact());
Ok(())
}
#[test]
fn test_type_scope() -> Result<()> {
let url = TremorUrl::parse("01/in")?;
assert_eq!(Scope::Type, url.scope());
assert_eq!(None, url.resource_type());
assert_eq!(None, url.artefact());
assert_eq!(Some("01"), url.instance());
assert_eq!(Some(ports::IN.as_ref()), url.instance_port());
Ok(())
}
#[test]
fn test_artefact_scope() -> Result<()> {
let url = TremorUrl::parse("pipe/01/in")?;
assert_eq!(Scope::Artefact, url.scope());
assert_eq!(None, url.resource_type());
assert_eq!(Some("pipe"), url.artefact());
assert_eq!(Some("01"), url.instance());
assert_eq!(Some(ports::IN.as_ref()), url.instance_port());
Ok(())
}
#[test]
fn test_port_scope() -> Result<()> {
let url = TremorUrl::parse("binding/pipe/01/in")?;
assert_eq!(Scope::Port, url.scope());
assert_eq!(Some(ResourceType::Binding), url.resource_type());
assert_eq!(Some("pipe"), url.artefact());
assert_eq!(Some("01"), url.instance());
assert_eq!(Some(ports::IN.as_ref()), url.instance_port());
let url = TremorUrl::parse("onramp/id/01/out")?;
assert_eq!(Scope::Port, url.scope());
assert_eq!(Some(ResourceType::Onramp), url.resource_type());
assert_eq!(Some("id"), url.artefact());
assert_eq!(Some("01"), url.instance());
assert_eq!(Some(ports::OUT.as_ref()), url.instance_port());
let url = TremorUrl::parse("offramp/id/01/in")?;
assert_eq!(Scope::Port, url.scope());
assert_eq!(Some(ResourceType::Offramp), url.resource_type());
assert_eq!(Some("id"), url.artefact());
assert_eq!(Some("01"), url.instance());
assert_eq!(Some(ports::IN.as_ref()), url.instance_port());
Ok(())
}
#[test]
fn test_set_instance() -> Result<()> {
let mut url = TremorUrl::parse("tremor://127.0.0.1:1234/pipeline/main")?;
assert_eq!(Scope::Artefact, url.scope());
assert_eq!(Some(ResourceType::Pipeline), url.resource_type());
assert_eq!(Some("main"), url.artefact());
assert_eq!(None, url.instance());
url.set_instance("inst");
assert_eq!(Scope::Servant, url.scope());
assert_eq!(Some("inst"), url.instance());
Ok(())
}
}
|
use std::time::{Duration, Instant};
fn main() {
let response = String::from("HTTP/1.1 418 I'm a teapot\r\n");
let mut res: (&str, &str, &str) = ("", "", "");
let start = Instant::now();
for _ in 0..100_000_000 {
res = match parse_http(&response) {
Ok(data) => data,
Err(e) => {
println!("{}", e);
continue;
}
};
}
let duration = start.elapsed();
println!("version:{}\ncode:{}\ndescription:{}\n", res.0, res.1, res.2);
println!("Time elapsed in parse_response() is: {:?}", duration);
}
fn parse_http(s: &str) -> Result<(&str, &str, &str), &str> {
let mut parts = s.splitn(3, ' ');
let version = parts.next().ok_or("No Version")?;
let code = parts.next().ok_or("No status code")?;
let description = parts.next().ok_or("No description")?;
Ok((version, code, description))
}
|
#![feature(anonymous_lifetime_in_impl_trait)]
#![feature(box_patterns)]
#![feature(const_trait_impl)]
#![feature(let_chains)]
#![allow(clippy::borrow_interior_mutable_const)]
#![allow(clippy::declare_interior_mutable_const)]
use candy_frontend::{cst::Cst, position::Offset};
use existing_whitespace::{TrailingWithIndentationConfig, WhitespacePositionInBody};
use extension_trait::extension_trait;
use format::{format_csts, FormattingInfo};
use itertools::Itertools;
use text_edits::TextEdits;
use width::{Indentation, Width};
mod existing_parentheses;
mod existing_whitespace;
mod format;
mod format_collection;
mod formatted_cst;
mod text_edits;
mod width;
#[extension_trait]
pub impl<C: AsRef<[Cst]>> Formatter for C {
fn format_to_string(&self) -> String {
self.format_to_edits().apply()
}
fn format_to_edits(&self) -> TextEdits {
let csts = self.as_ref();
// TOOD: Is there an elegant way to avoid stringifying the whole CST?
let source = csts.iter().join("");
let mut edits = TextEdits::new(source);
let formatted = format_csts(
&mut edits,
Width::default(),
csts,
Offset::default(),
&FormattingInfo::default(),
);
if formatted.child_width() == Width::default() && !formatted.whitespace.has_comments() {
_ = formatted.into_empty_trailing(&mut edits);
} else {
let config = TrailingWithIndentationConfig::Body {
position: if formatted.child_width() == Width::default() {
WhitespacePositionInBody::Start
} else {
WhitespacePositionInBody::End
},
indentation: Indentation::default(),
};
_ = formatted.into_trailing_with_indentation_detailed(&mut edits, &config);
};
edits
}
}
|
use image::Rgba;
use tiny_fail::Fail;
pub fn get_scale(name: &str) -> Result<Box<dyn ColorScale>, Fail> {
match name {
"color" => Ok(Box::new(Colorful())),
"gray" => Ok(Box::new(Grayscale())),
name => Err(Fail::new(format!("unknown color scale: '{}'", name))),
}
}
pub trait ColorScale {
fn scale(&self, x: f32) -> Rgba<u8>;
fn background(&self) -> Option<Rgba<u8>> {
None
}
}
pub struct Colorful();
impl ColorScale for Colorful {
fn scale(&self, x: f32) -> Rgba<u8> {
let out_r = x * x;
let out_g = 1.0 - 4.0 * (x - 0.5).powi(2);
let out_b = 1.0 - x.powi(2);
let out_a = 1.0 - 0.5 * (1.0 - x).powi(2);
Rgba([
(255.0 * out_r) as u8,
(255.0 * out_g) as u8,
(255.0 * out_b) as u8,
(255.0 * out_a) as u8,
])
}
}
pub struct Grayscale();
impl ColorScale for Grayscale {
fn scale(&self, x: f32) -> Rgba<u8> {
let v = (255.0 * x) as u8;
let a = 255.0 * (1.0 - 0.5 * (1.0 - x).powi(2));
Rgba([v, v, v, a as u8])
}
fn background(&self) -> Option<Rgba<u8>> {
Some(Rgba([0, 0, 0, 127]))
}
}
|
use super::*;
use std::{iter, sync::Arc};
#[allow(unused_imports)]
use core_extensions::SelfOps;
use crate::{
test_utils::{must_panic, ShouldHavePanickedAt},
traits::IntoReprC,
};
#[cfg(feature = "rust_1_64")]
#[test]
fn const_as_slice_test() {
const RV: &RVec<u8> = &RVec::new();
const SLICE: &[u8] = RV.as_slice();
assert_eq!(SLICE, [0u8; 0]);
}
#[test]
#[allow(clippy::drop_non_drop)]
fn test_equality_between_vecs() {
struct F<T>(T);
fn eq<'a, 'b, T>(left: &RVec<&'a T>, right: &RVec<&'b T>) -> bool
where
T: std::cmp::PartialEq,
{
left == right
}
let aaa = F(3);
let bbb = F(5);
let ccc = F(8);
let ddd = F(13);
{
let v0 = rvec![&aaa.0, &bbb.0];
let v1 = rvec![&ccc.0, &ddd.0];
assert!(!eq(&v0, &v1));
}
// forcing the lifetime to extend to the end of the scope
drop(ccc);
drop(ddd);
drop(aaa);
drop(bbb);
}
fn _assert_covariant<'a: 'b, 'b, T>(x: RVec<&'a T>) -> RVec<&'b T> {
x
}
fn _assert_covariant_vec<'a: 'b, 'b, T>(x: Vec<&'a T>) -> Vec<&'b T> {
x
}
fn typical_list(upto: u8) -> (Vec<u8>, RVec<u8>) {
let orig = (b'a'..=upto).collect::<Vec<_>>();
(orig.clone(), orig.iter().cloned().collect())
}
#[test]
fn vec_drain() {
let (original, list) = typical_list(b'j');
let pointer = Arc::new(());
macro_rules! assert_eq_drain {
($range: expr, $after_drain: expr) => {
let range = $range;
{
let after_drain: Vec<u8> = $after_drain;
let mut list = list.clone();
let list_2 = list.drain(range.clone()).collect::<Vec<_>>();
assert_eq!(&*list_2, &original[range.clone()], "");
assert_eq!(&*list, &*after_drain,);
}
{
let length = 10;
let mut list_b = iter::repeat(pointer.clone())
.take(length)
.collect::<Vec<_>>();
let range_len = list[range.clone()].len();
list_b.drain(range.clone());
assert_eq!(list_b.len(), length - range_len);
assert_eq!(Arc::strong_count(&pointer), 1 + length - range_len);
}
};
}
assert_eq_drain!(.., vec![]);
assert_eq_drain!(..3, vec![b'd', b'e', b'f', b'g', b'h', b'i', b'j']);
assert_eq_drain!(3.., vec![b'a', b'b', b'c']);
assert_eq_drain!(3..5, vec![b'a', b'b', b'c', b'f', b'g', b'h', b'i', b'j']);
}
#[test]
fn insert_remove() {
let (original, list) = typical_list(b'd');
let assert_insert_remove = |position: usize, expected: Vec<u8>| {
let mut list = list.clone();
let val = list.try_remove(position).unwrap();
assert_eq!(&*list, &*expected);
list.insert(position, val);
assert_eq!(&*list, &*original);
};
//vec![b'a', b'b', b'c', b'd', b'e', b'f', b'g', b'h', b'i', b'j']
assert_insert_remove(0, vec![b'b', b'c', b'd']);
assert_insert_remove(1, vec![b'a', b'c', b'd']);
assert_insert_remove(2, vec![b'a', b'b', b'd']);
assert_insert_remove(3, vec![b'a', b'b', b'c']);
{
let mut list = RVec::new();
list.insert(0, b'a');
list.insert(1, b'b');
list.insert(1, b'c');
list.insert(0, b'd');
assert_eq!(&*list, &[b'd', b'a', b'c', b'b']);
}
}
#[test]
fn remove_panics() -> Result<(), ShouldHavePanickedAt> {
let mut list = RVec::new();
for (i, elem) in (10..20).enumerate() {
must_panic(|| list.remove(i))?;
list.push(elem);
list.remove(i);
list.push(elem);
}
Ok(())
}
#[test]
fn swap_remove() {
let mut list = vec![10, 11, 12, 13, 14, 15].into_c();
assert_eq!(list.swap_remove(5), 15);
assert_eq!(&*list, &*vec![10, 11, 12, 13, 14]);
assert_eq!(list.swap_remove(0), 10);
assert_eq!(&*list, &*vec![14, 11, 12, 13]);
assert_eq!(list.swap_remove(1), 11);
assert_eq!(&*list, &*vec![14, 13, 12]);
}
#[test]
fn push_pop() {
let mut list = RVec::<u32>::new();
assert_eq!(list.pop(), None);
for elem in 10..=13 {
list.push(elem);
}
assert_eq!(&*list, &[10, 11, 12, 13]);
assert_eq!(list.pop(), Some(13));
assert_eq!(&*list, &[10, 11, 12]);
assert_eq!(list.pop(), Some(12));
assert_eq!(&*list, &[10, 11]);
assert_eq!(list.pop(), Some(11));
assert_eq!(&*list, &[10]);
assert_eq!(list.pop(), Some(10));
assert_eq!(&*list, <&[u32]>::default());
assert_eq!(list.pop(), None);
}
#[test]
fn truncate() {
{
let orig = vec![0, 1, 2, 3, 4];
let mut list = orig.clone().into_c();
list.truncate(6);
assert_eq!(&*list, &*orig);
for i in (0..5).rev() {
list.truncate(i);
assert_eq!(&*list, &orig[..i]);
}
}
{
let pointer = Arc::new(());
let length = 10;
let mut list = iter::repeat(pointer.clone())
.take(length)
.collect::<Vec<_>>();
assert_eq!(Arc::strong_count(&pointer), 1 + length);
for i in (0..list.len()).rev() {
list.truncate(i);
assert_eq!(Arc::strong_count(&pointer), 1 + i);
}
assert_eq!(Arc::strong_count(&pointer), 1);
}
}
#[test]
fn retain() {
let orig = vec![2, 3, 4, 5, 6, 7, 8];
let copy = orig.clone().piped(RVec::from);
{
let mut copy = copy.clone();
copy.retain(|&v| v % 2 == 0);
assert_eq!(&*copy, &[2, 4, 6, 8][..]);
}
{
let mut copy = copy.clone();
copy.retain(|&v| v % 2 == 1);
assert_eq!(&*copy, &[3, 5, 7][..]);
}
{
let mut copy = copy.clone();
copy.retain(|_| true);
assert_eq!(&*copy, &*orig);
}
{
let mut copy = copy.clone();
copy.retain(|_| false);
assert_eq!(&*copy, <&[i32]>::default());
}
{
let mut copy = copy.clone();
let mut i = 0;
copy.retain(|_| {
let cond = i % 2 == 0;
i += 1;
cond
});
assert_eq!(&*copy, &[2, 4, 6, 8][..]);
}
{
let mut copy = copy.clone();
let mut i = 0;
copy.retain(|_| {
let cond = i % 3 == 0;
i += 1;
cond
});
assert_eq!(&*copy, &[2, 5, 8][..]);
}
{
let mut copy = copy;
let mut i = 0;
must_panic(|| {
copy.retain(|_| {
i += 1;
if i == 4 {
panic!()
}
true
});
})
.unwrap();
assert_eq!(©[..], &orig[..]);
}
}
#[test]
fn resize() {
let full = vec![1, 2, 3, 4, 5];
let mut list = RVec::new();
for i in 1..=5 {
list.resize(i, i);
assert_eq!(list[i - 1], i);
}
assert_eq!(&*list, &*full);
for i in (1..=5).rev() {
list.resize(i, 0);
assert_eq!(&*list, &full[..i]);
}
}
#[test]
fn extend_from_slice() {
let mut list = RVec::new();
let from: Vec<String> = vec!["hello 0".into(), "hello 1".into(), "hello 2".into()];
list.extend_from_slice(&[]);
list.extend_from_slice(&from);
assert_eq!(&*list, &*from);
let from2: Vec<String> = vec!["fuck".into(), "that".into()];
let from_upto2 = from.iter().chain(from2.iter()).cloned().collect::<Vec<_>>();
list.extend_from_slice(&from2);
assert_eq!(&*list, &*from_upto2);
}
#[test]
fn extend_from_copy_slice() {
let mut list = RVec::new();
let from: Vec<&str> = vec!["hello 0", "hello 1", "hello 2"];
list.extend_from_copy_slice(&[]);
list.extend_from_copy_slice(&from);
assert_eq!(&*list, &*from);
let from2: Vec<&str> = vec!["fuck", "that"];
let from_upto2 = from.iter().chain(from2.iter()).cloned().collect::<Vec<_>>();
list.extend_from_copy_slice(&from2);
assert_eq!(&*list, &*from_upto2);
}
#[test]
fn extend() {
let mut list = RVec::new();
let from: Vec<&str> = vec!["hello 0", "hello 1", "hello 2"];
list.extend(from.iter().cloned());
let from_empty: &[&str] = &[];
list.extend(from_empty.iter().cloned());
assert_eq!(&*list, &*from);
let from2: Vec<&str> = vec!["fuck", "that"];
let from_upto2 = from.iter().chain(from2.iter()).cloned().collect::<Vec<_>>();
list.extend(from2.iter().cloned());
assert_eq!(&*list, &*from_upto2);
}
#[test]
fn append() {
let mut into = RVec::<u16>::new();
into.append(&mut RVec::new());
assert_eq!(into, Vec::<u16>::new());
{
let mut from = rvec![3u16, 5, 8];
into.append(&mut from);
assert_eq!(into, [3u16, 5, 8][..]);
assert_eq!(from, Vec::<u16>::new());
}
into.append(&mut RVec::new());
assert_eq!(into, [3u16, 5, 8][..]);
{
let mut from = rvec![13u16];
into.append(&mut from);
assert_eq!(into, [3u16, 5, 8, 13][..]);
assert_eq!(from, Vec::<u16>::new());
}
}
#[test]
fn into_iter() {
assert_eq!(RVec::<()>::new().into_iter().next(), None);
let arc = Arc::new(0);
let orig = vec![arc.clone(), arc.clone(), arc.clone(), arc.clone()];
let mut list = orig.clone().into_c();
assert_eq!(list.clone().into_iter().collect::<Vec<_>>(), orig);
assert_eq!(Arc::strong_count(&arc), 9);
assert_eq!((&list).into_iter().cloned().collect::<Vec<_>>(), orig);
assert_eq!(
(&mut list)
.into_iter()
.map(|v: &mut Arc<i32>| v.clone())
.collect::<Vec<_>>(),
orig
);
}
#[test]
fn into_iter_as_str() {
let mut orig = vec![10, 11, 12, 13];
let mut iter = orig.clone().into_c().into_iter();
let mut i = 0;
loop {
assert_eq!(&orig[i..], iter.as_slice());
assert_eq!(&mut orig[i..], iter.as_mut_slice());
i += 1;
if iter.next().is_none() {
break;
}
}
}
#[test]
fn clone() {
let orig = vec![10, 11, 12, 13];
let clon = orig.clone();
assert_ne!(orig.as_ptr(), clon.as_ptr());
assert_eq!(orig, clon);
}
#[test]
fn from_vec() {
let orig = vec![10, 11, 12, 13];
let buffer_ptr = orig.as_ptr();
let list = orig.into_c();
assert_eq!(buffer_ptr, list.as_ptr());
}
#[test]
fn test_drop() {
let pointer = Arc::new(());
let length = 10;
let list = iter::repeat(pointer.clone())
.take(length)
.collect::<Vec<_>>();
assert_eq!(Arc::strong_count(&pointer), 1 + length);
drop(list);
assert_eq!(Arc::strong_count(&pointer), 1);
}
#[test]
fn into_vec() {
let orig = vec![10, 11, 12, 13];
let list = orig.clone().into_c();
{
let list = list.clone();
let list_ptr = list.as_ptr();
let list_1 = list.into_vec();
assert_eq!(list_ptr, list_1.as_ptr());
assert_eq!(orig, list_1);
}
{
let list = list.set_vtable_for_testing();
let list_ptr = list.as_ptr() as usize;
let list_1 = list.into_vec();
// No, MIR interpreter,
// I'm not dereferencing a pointer here, I am comparing their adresses.
assert_ne!(list_ptr, list_1.as_ptr() as usize);
assert_eq!(orig, list_1);
}
}
#[test]
fn rvec_macro() {
assert_eq!(RVec::<u32>::new(), rvec![]);
assert_eq!(RVec::from(vec![0]), rvec![0]);
assert_eq!(RVec::from(vec![0, 3]), rvec![0, 3]);
assert_eq!(RVec::from(vec![0, 3, 6]), rvec![0, 3, 6]);
assert_eq!(RVec::from(vec![1; 10]), rvec![1;10]);
}
// Adapted from Vec tests
// (from rustc 1.50.0-nightly (eb4fc71dc 2020-12-17))
#[test]
fn retain_panic() {
use std::{panic::AssertUnwindSafe, rc::Rc, sync::Mutex};
struct Check {
index: usize,
drop_counts: Rc<Mutex<RVec<usize>>>,
}
impl Drop for Check {
fn drop(&mut self) {
self.drop_counts.lock().unwrap()[self.index] += 1;
println!("drop: {}", self.index);
}
}
let check_count = 10;
let drop_counts = Rc::new(Mutex::new(rvec![0_usize; check_count]));
let mut data: RVec<Check> = (0..check_count)
.map(|index| Check {
index,
drop_counts: Rc::clone(&drop_counts),
})
.collect();
let _ = std::panic::catch_unwind(AssertUnwindSafe(move || {
let filter = |c: &Check| {
if c.index == 2 {
panic!("panic at index: {}", c.index);
}
// Verify that if the filter could panic again on another element
// that it would not cause a double panic and all elements of the
// vec would still be dropped exactly once.
if c.index == 4 {
panic!("panic at index: {}", c.index);
}
c.index < 6
};
data.retain(filter);
}));
let drop_counts = drop_counts.lock().unwrap();
assert_eq!(check_count, drop_counts.len());
for (index, count) in drop_counts.iter().cloned().enumerate() {
assert_eq!(
1, count,
"unexpected drop count at index: {} (count: {})",
index, count
);
}
}
#[test]
fn test_index() {
let s = rvec![1, 2, 3, 4, 5];
assert_eq!(s.index(0), &1);
assert_eq!(s.index(4), &5);
assert_eq!(s.index(..2), rvec![1, 2]);
assert_eq!(s.index(1..2), rvec![2]);
assert_eq!(s.index(3..), rvec![4, 5]);
}
#[test]
fn test_index_mut() {
let mut s = rvec![1, 2, 3, 4, 5];
assert_eq!(s.index_mut(0), &mut 1);
assert_eq!(s.index_mut(4), &mut 5);
assert_eq!(s.index_mut(..2), &mut rvec![1, 2]);
assert_eq!(s.index_mut(1..2), &mut rvec![2]);
assert_eq!(s.index_mut(3..), &mut rvec![4, 5]);
}
#[test]
fn test_slice() {
let s = rvec![1, 2, 3, 4, 5];
assert_eq!(s.slice(..), rslice![1, 2, 3, 4, 5]);
assert_eq!(s.slice(..2), rslice![1, 2]);
assert_eq!(s.slice(1..2), rslice![2]);
assert_eq!(s.slice(3..), rslice![4, 5]);
}
#[test]
fn test_slice_mut() {
let mut s = rvec![1, 2, 3, 4, 5];
assert_eq!(
s.slice_mut(..),
RSliceMut::from_mut_slice(&mut [1, 2, 3, 4, 5])
);
assert_eq!(s.slice_mut(..2), RSliceMut::from_mut_slice(&mut [1, 2]));
assert_eq!(s.slice_mut(1..2), RSliceMut::from_mut_slice(&mut [2]));
assert_eq!(s.slice_mut(3..), RSliceMut::from_mut_slice(&mut [4, 5]));
}
|
#![no_std]
#![no_main]
// pick a panicking behavior
use panic_halt as _; // you can put a breakpoint on `rust_begin_unwind` to catch panics
use cortex_m_rt::entry;
//semi hosting
use cortex_m_semihosting::hprintln;
#[entry]
fn main() -> ! {
hprintln!("Hello world from logging").unwrap();
loop {
// your code goes here
}
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use super::*;
use crate::{protocol::response::Response, request_builder::RequestParams};
use failure::Fail;
use futures::future::BoxFuture;
use futures::prelude::*;
/// This is the collection of Errors that can occur during the installation of an update.
///
/// This is a placeholder stub implementation.
///
#[derive(Debug, Fail)]
pub enum StubInstallErrors {
#[fail(display = "Stub Installer Failure")]
Failed,
}
/// This is the collection of Errors that can occur during the creation of an Install Plan from the
/// Omaha Response.
///
/// This is a placeholder stub implementation.
///
#[derive(Debug, Fail)]
pub enum StubPlanErrors {
#[fail(display = "Stub Plan Creation Failure")]
Failed,
}
/// A stub implementation of the Install Plan.
///
pub struct StubPlan;
impl Plan for StubPlan {
type Error = StubPlanErrors;
fn try_create_from(
_request_params: &RequestParams,
response: &Response,
) -> Result<Self, Self::Error> {
if response.protocol_version != "3.0" {
Err(StubPlanErrors::Failed)
} else {
Ok(StubPlan)
}
}
fn id(&self) -> String {
String::new()
}
}
/// The Installer is responsible for performing (or triggering) the installation of the update
/// that's referred to by the InstallPlan.
///
#[derive(Debug, Default)]
pub struct StubInstaller {
pub should_fail: bool,
}
impl Installer for StubInstaller {
type InstallPlan = StubPlan;
type Error = StubInstallErrors;
/// Perform the installation as given by the install plan (as parsed form the Omaha server
/// response). If given, provide progress via the observer, and a final finished or Error
/// indication via the Future.
fn perform_install(
&mut self,
_install_plan: &StubPlan,
_observer: Option<&dyn ProgressObserver>,
) -> BoxFuture<Result<(), StubInstallErrors>> {
if self.should_fail {
future::ready(Err(StubInstallErrors::Failed)).boxed()
} else {
future::ready(Ok(())).boxed()
}
}
}
|
#[doc(hidden)]
#[macro_export]
macro_rules! _sabi_type_layouts {
(internal; $ty:ty )=>{{
$crate::pmr::get_type_layout::<$ty>
}};
(internal; $ty:ty = SABI_OPAQUE_FIELD)=>{
$crate::pmr::__sabi_opaque_field_type_layout::<$ty>
};
(internal; $ty:ty = OPAQUE_FIELD)=>{
$crate::pmr::__opaque_field_type_layout::<$ty>
};
(
$( $ty:ty $( = $assoc_const:ident )? ,)*
) => {{
$crate::rslice![
$(
$crate::_sabi_type_layouts!(internal; $ty $( = $assoc_const )? ),
)*
]
}};
}
|
use nom::branch::alt;
use nom::bytes::complete::tag;
use nom::character::complete::*;
use nom::combinator::*;
use nom::multi::*;
use nom::sequence::*;
use nom::IResult;
use std::collections::HashMap;
fn main() {
let text = std::fs::read_to_string("input").unwrap();
let (mut parser, msgs) = all_consuming(input)(&*text).unwrap().1;
let p1 = msgs.iter().filter(|m| parser.valid(m)).count();
dbg!(p1);
parser.0.insert(8, rule("42 | 42 8").unwrap().1);
parser.0.insert(11, rule("42 31 | 42 11 31").unwrap().1);
let p2 = msgs.iter().filter(|m| parser.valid(m)).count();
dbg!(p2);
}
#[derive(Clone, Debug)]
struct Parser(HashMap<usize, Rule>);
#[derive(Clone, Debug)]
enum Rule {
Alt(Vec<Vec<usize>>),
Char(char),
}
impl Parser {
fn valid(&self, input: &str) -> bool {
self.parse(0, input.as_bytes()).iter().any(|l| l.len() == 0)
}
fn parse<'a>(&self, rule: usize, input: &'a [u8]) -> Vec<&'a [u8]> {
let options = match &self.0[&rule] {
Rule::Char(c) => {
if input.len() > 0 && input[0] == *c as u8 {
vec![&input[1..]]
} else {
vec![]
}
}
Rule::Alt(alts) => alts
.iter()
.flat_map(|seq| {
seq.iter().fold(vec![input], |inputs, rule| {
inputs.iter().flat_map(|i| self.parse(*rule, i)).collect()
})
})
.collect(),
};
options
}
}
fn input(i: &str) -> IResult<&str, (Parser, Vec<&str>)> {
separated_pair(parser, tag("\n\n"), many1(terminated(alpha1, newline)))(i)
}
fn parser(i: &str) -> IResult<&str, Parser> {
map(
separated_list1(newline, separated_pair(number, tag(": "), rule)),
|v| Parser(v.into_iter().collect()),
)(i)
}
fn rule(i: &str) -> IResult<&str, Rule> {
alt((
map(separated_list1(tag(" | "), seq), Rule::Alt),
map(delimited(tag("\""), anychar, tag("\"")), Rule::Char),
))(i)
}
fn seq(i: &str) -> IResult<&str, Vec<usize>> {
separated_list1(tag(" "), number)(i)
}
fn number(i: &str) -> IResult<&str, usize> {
map_res(digit1, std::str::FromStr::from_str)(i)
}
#[test]
fn t0() {
let parser = parser(
r#"0: 4 1 5
1: 2 3 | 3 2
2: 4 4 | 5 5
3: 4 5 | 5 4
4: "a"
5: "b""#,
)
.unwrap()
.1;
assert!(parser.valid("ababbb"));
assert!(parser.valid("abbbab"));
assert!(!parser.valid("bababa"));
assert!(!parser.valid("aaabbb"));
assert!(!parser.valid("aaaabbb"));
}
|
#[doc = "Reader of register ACSTAT1"]
pub type R = crate::R<u32, super::ACSTAT1>;
#[doc = "Reader of field `OVAL`"]
pub type OVAL_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 1 - Comparator Output Value"]
#[inline(always)]
pub fn oval(&self) -> OVAL_R {
OVAL_R::new(((self.bits >> 1) & 0x01) != 0)
}
}
|
use std::collections::BinaryHeap;
use std::collections::HashMap;
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use std::time::{SystemTime, UNIX_EPOCH};
use super::messages::{Chat, Message};
use lazy_static::lazy_static;
pub(crate) fn timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u64
}
lazy_static! {
static ref USERS: HashMap<u64, Vec<u64>> = {
let file = File::open("contacts.json").expect("unable to open contacts.json");
let reader = BufReader::new(file);
let m: HashMap<_, _> = serde_json::from_reader(reader).unwrap();
m
};
}
pub struct ChatRoom {
chat: Chat,
log: BinaryHeap<Message>,
}
impl ChatRoom {
pub fn new(chat: Chat) -> Self {
ChatRoom {
chat,
log: BinaryHeap::new(),
}
}
}
#[derive(Default)]
pub struct ChatService {
chats: HashMap<(u64, u64), ChatRoom>,
chat_keys: HashMap<u64, (u64, u64)>,
}
impl ChatService {
/// Adds a new chat - user a and b must have each other in their contact lists
pub fn add_chat(&mut self, chat: Chat) -> Result<(), Box<dyn Error>> {
let user_a = chat.participant_ids[0];
let user_b = chat.participant_ids[1];
if self.chats.contains_key(&(user_a, user_b)) {
return Err("Chat already exists".into());
}
let a = USERS.get(&user_a);
let b = USERS.get(&user_b);
if let (Some(a), Some(b)) = (a, b) {
if a.contains(&user_b) && b.contains(&user_a) {
self.chat_keys.insert(chat.id, (user_a, user_b));
let chatroom = ChatRoom::new(chat);
self.chats.insert((user_a, user_b), chatroom);
return Ok(());
} else {
if !a.contains(&user_b) {
return Err(format!(
"user {} does not have user {} in their contact list.",
user_a, user_b
)
.into());
}
if !b.contains(&user_a) {
return Err(format!(
"user {} does not have user {} in their contact list.",
user_b, user_a
)
.into());
}
}
}
Err("unable to create chat".into())
}
pub fn send_message(&mut self, chat_id: u64, message: Message) -> Result<(), Box<dyn Error>> {
let key = match self.chat_keys.get(&chat_id) {
Some(key) => key,
None => return Err(format!("Unable to find chat with id {}", chat_id).into()),
};
match self.chats.get_mut(&key) {
Some(chat) => {
println!(
"adding message to log for chat id {} users {:?}",
chat_id, key
);
chat.log.push(message);
}
None => return Err(format!("Unable to find chat for {:?}", key).into()),
}
Ok(())
}
pub fn get_messages(&self, chat_id: u64) -> Result<Vec<Message>, Box<dyn Error>> {
println!("GET MESSAGES");
let key = match self.chat_keys.get(&chat_id) {
Some(key) => key,
None => return Err("Unable to find key".into()),
};
let chat = match self.chats.get(&key) {
Some(chat) => chat,
None => return Err("Unable to find chatroom".into()),
};
let current_log = chat.log.clone();
println!("chat log : {:?}", chat.log);
Ok(current_log.into_sorted_vec())
}
pub fn get_user_chats(&self, user_id: u64) -> Vec<&Chat> {
self.chats
.iter()
.filter(|((a, b), _)| *a == user_id || *b == user_id)
.map(|(_, v)| &v.chat)
.collect::<Vec<_>>()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn msg(src: u64, dst: u64) -> Message {
let ts = timestamp();
Message {
id: String::new(),
timestamp: ts,
source_user_id: src,
destination_user_id: dst,
message: format!("{} to {} at {}", src, dst, ts),
}
}
#[test]
fn test_chat_service() {
let mut service = ChatService::default();
// adding message to log for chat id 11872 users (58534, 74827)
let chat = Chat {
id: 11872,
participant_ids: [58534, 74827],
};
service.add_chat(chat).unwrap();
for i in 0..10 {
service.send_message(11872, msg(58534, 74827)).unwrap();
}
let messages = service.get_messages(11872).unwrap();
assert_eq!(messages.len(), 10);
let mut high_mark = 0;
for msg in messages {
if high_mark == 0 {
high_mark = msg.timestamp;
}
assert!(high_mark >= msg.timestamp);
}
}
}
|
use std::collections::HashMap;
use std::time::{Duration, Instant};
use crate::event::NetworkEvent;
use crate::network::PacketHeader;
pub const HIGH_FREQUENCY: u8 = 40;
pub const LOW_FREQUENCY: u8 = 20;
pub const LATENCY_THRESHOLD: f32 = 250.0;
pub const MIN_RECOVERY_COOLDOWN: Duration = Duration::from_secs(1);
pub const MAX_RECOVERY_COOLDOWN: Duration = Duration::from_secs(60);
pub const RECOVERY_COOLDOWN_UPDATE_PERIOD: Duration = Duration::from_secs(10);
pub const PING_SMOOTHING: u16 = 10;
#[derive(Debug)]
pub struct ConnectionData {
pub local_sequence: u16,
pub remote_sequence: u16,
pub ack: u32,
pub ping: f32,
//pub send_kbps: f32,
//pub receive_kbps: f32,
pub last_response_time: Instant,
pub frequency: u8,
pub last_frequency_change: Instant,
pub last_cooldown_update: Instant,
pub recovery_cooldown: Duration,
pub send_accumulator: u128,
//pub sent_bits_accumulator: u64,
//pub received_bits_accumulator: u64,
pub unacked_events: Vec<(Vec<u16>, Instant, Box<dyn NetworkEvent>)>,
pub packet_times: Vec<(u16, Instant)>,
pub incomplete_payloads: HashMap<Vec<u16>, (Instant, Vec<Option<(PacketHeader, Vec<u8>)>>)>,
}
impl ConnectionData {
pub fn new() -> Self {
let now = Instant::now();
Self {
local_sequence: 0,
remote_sequence: 0,
ack: 0,
ping: 0.0,
last_response_time: now,
frequency: HIGH_FREQUENCY,
last_frequency_change: now,
last_cooldown_update: now,
recovery_cooldown: Duration::from_secs(2),
send_accumulator: 0,
unacked_events: Vec::new(),
packet_times: Vec::new(),
incomplete_payloads: HashMap::new(),
}
}
pub fn ack_sequence(&mut self, sequence: u16) {
let distance = wrapped_distance(sequence, self.remote_sequence);
if distance < 0 {
// This sequence is more recent than anything we've had before
self.remote_sequence = sequence;
self.ack <<= distance.abs();
self.ack_sequence(sequence);
} else {
let mask: u32 = 0x00000001 << distance;
self.ack |= mask;
}
}
}
pub fn wrapped_distance(mut a: u16, mut b: u16) -> i16 {
let sign = if b > a {
1
} else {
std::mem::swap(&mut a, &mut b);
-1
};
if b - a <= 32768 {
sign * (b - a) as i16
} else {
sign * (a as i32 - 65536 + b as i32) as i16
}
}
#[cfg(test)]
mod tests {
use crate::network::packet_header::PacketHeader;
use super::*;
#[test]
fn correct_acks() {
let mut cd = ConnectionData::new();
cd.ack_sequence(18);
cd.ack_sequence(20);
let ph = PacketHeader {
sequence: 0,
ack_start: cd.remote_sequence,
ack: cd.ack,
part: 0,
total: 0,
sizes: Vec::new(),
};
assert!(ph.acked(&[18, 20]));
assert!(ph.acked(&[17]) == false);
assert!(ph.acked(&[19]) == false);
assert!(ph.acked(&[21]) == false);
}
} |
use std::sync::Arc;
use super::Backend;
pub trait Fence {
fn value(&self) -> u64;
fn await_value(&self, value: u64);
}
pub struct FenceValuePair<B: Backend> {
pub fence: Arc<B::Fence>,
pub value: u64
}
impl<B: Backend> FenceValuePair<B> {
pub fn is_signalled(&self) -> bool {
self.fence.value() >= self.value
}
}
impl<B: Backend> Clone for FenceValuePair<B> {
fn clone(&self) -> Self {
Self {
fence: self.fence.clone(),
value: self.value
}
}
} |
//! Constants for use in connection URLs.
//!
//! Database connections are configured with an instance of [`ConnectParams`](crate::ConnectParams).
//! Instances of [`ConnectParams`](crate::ConnectParams)
//! can be created using a [`ConnectParamsBuilder`](crate::ConnectParamsBuilder), or from a URL.
//!
//! Also [`ConnectParamsBuilder`](crate::ConnectParamsBuilder)s can be created from a URL.
//!
//! Such a URL is supposed to have the form
//!
//! ```text
//! <scheme>://<username>:<password>@<host>:<port>[<options>]
//! ```
//! where
//! > `<scheme>` = `hdbsql` | `hdbsqls`
//! > `<username>` = the name of the DB user to log on
//! > `<password>` = the password of the DB user
//! > `<host>` = the host where HANA can be found
//! > `<port>` = the port at which HANA can be found on `<host>`
//! > `<options>` = `?<key>[=<value>][{&<key>[=<value>]}]`
//!
//! __Supported options are:__
//! - `db=<databasename>` specifies the (MDC) database to which you want to connect
//! - `client_locale=<value>` is used in language-dependent handling within the
//! SAP HANA database calculation engine
//! - `client_locale_from_env` (no value) lets the driver read the client's locale from the
//! environment variabe LANG
//! - `<networkgroup>` = a network group
//! - the [TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security) options
//!
//!
//! __The [TLS](https://en.wikipedia.org/wiki/Transport_Layer_Security) options are:__
//! - `tls_certificate_dir=<value>`: points to a folder with pem files that contain
//! certificates; all pem files in that folder are evaluated
//! - `tls_certificate_env=<value>`: denotes an environment variable that contains
//! certificates
//! - `use_mozillas_root_certificates` (no value): use the root certificates from
//! [`https://mkcert.org/`](https://mkcert.org/)
//! - `insecure_omit_server_certificate_check` (no value): lets the driver omit the validation of
//! the server's identity. Don't use this option in productive setups!
//!
//! __To configure TLS__, use the scheme `hdbsqls` and at least one of the TLS options.
//!
//! __For a plain connection without TLS__, use the scheme `hdbsql` and none of the TLS options.
//!
//! ### Examples
//!
//! `ConnectParams` is immutable, the URL must contain all necessary information:
//! ```rust
//! use hdbconnect::IntoConnectParams;
//!
//! let conn_params = "hdbsql://my_user:my_passwd@the_host:2222"
//! .into_connect_params()
//! .unwrap();
//! ```
//!
//! `ConnectParamsBuilder` allows modifications, before being converted into a `ConnectParams`:
//!
//! ```rust
//! use hdbconnect::IntoConnectParamsBuilder;
//!
//! let mut copabu = "hdbsql://my_user@the_host:2222"
//! .into_connect_params_builder()
//! .unwrap();
//!
//! copabu.password("no-secrets-in-urls");
//! let conn_params = copabu.build().unwrap(); // ConnectParams
//! ```
/// Option-key for denoting a folder in which server certificates can be found.
pub const TLS_CERTIFICATE_DIR: &str = "tls_certificate_dir";
/// Option-key for denoting an environment variable in which a server certificate can be found
pub const TLS_CERTIFICATE_ENV: &str = "tls_certificate_env";
/// option-key for defining that the server roots from <https://mkcert.org/> should be added to the
/// trust store for TLS.
pub const USE_MOZILLAS_ROOT_CERTIFICATES: &str = "use_mozillas_root_certificates";
/// Option-key for defining that the server's identity is not validated. Don't use this
/// option in productive setups!
pub const INSECURE_OMIT_SERVER_CERTIFICATE_CHECK: &str = "insecure_omit_server_certificate_check";
/// Option-key for denoting the client locale.
pub const CLIENT_LOCALE: &str = "client_locale";
/// Option-key for denoting an environment variable which contains the client locale.
pub const CLIENT_LOCALE_FROM_ENV: &str = "client_locale_from_env";
/// Option-key for denoting the (MDC) database to which you want to connect; when using this option,
/// `<host>` and `<port>` must specify the system database
pub const DATABASE: &str = "db";
/// Option-key for denoting a network group.
pub const NETWORK_GROUP: &str = "network_group";
/// Use nonblocking.
#[cfg(feature = "alpha_nonblocking")]
pub const NONBLOCKING: &str = "nonblocking";
|
#[derive(Debug)]
pub struct Register(pub u8);
impl From<Register> for usize {
fn from(reg: Register) -> usize {
let Register(val) = reg;
val as usize
}
}
#[derive(Debug)]
pub enum Value {
Literal(u16),
Register(Register),
}
impl From<u16> for Value {
fn from(raw: u16) -> Self {
match raw {
r if r <= 32767 => Value::Literal(raw),
r if r <= 32775 => Value::Register(Register((r - 32768) as u8)),
_ => panic!("Invalid value {}", raw),
}
}
}
impl From<Value> for u16 {
fn from(val: Value) -> u16 {
match val {
Value::Literal(v) => v,
Value::Register(Register(v)) => v as u16,
}
}
}
|
//! Asynchronous TLS/SSL streams for Tokio using [Rustls](https://github.com/ctz/rustls).
pub extern crate rustls;
pub extern crate webpki;
extern crate bytes;
extern crate futures;
extern crate iovec;
extern crate tokio_io;
pub mod client;
mod common;
pub mod server;
use common::Stream;
use futures::{Async, Future, Poll};
use rustls::{ClientConfig, ClientSession, ServerConfig, ServerSession, Session};
use std::sync::Arc;
use std::{io, mem};
use tokio_io::{try_nb, AsyncRead, AsyncWrite};
use webpki::DNSNameRef;
#[derive(Debug, Copy, Clone)]
pub enum TlsState {
#[cfg(feature = "early-data")]
EarlyData,
Stream,
ReadShutdown,
WriteShutdown,
FullyShutdown,
}
impl TlsState {
pub(crate) fn shutdown_read(&mut self) {
match *self {
TlsState::WriteShutdown | TlsState::FullyShutdown => *self = TlsState::FullyShutdown,
_ => *self = TlsState::ReadShutdown,
}
}
pub(crate) fn shutdown_write(&mut self) {
match *self {
TlsState::ReadShutdown | TlsState::FullyShutdown => *self = TlsState::FullyShutdown,
_ => *self = TlsState::WriteShutdown,
}
}
pub(crate) fn writeable(&self) -> bool {
match *self {
TlsState::WriteShutdown | TlsState::FullyShutdown => false,
_ => true,
}
}
pub(crate) fn readable(self) -> bool {
match self {
TlsState::ReadShutdown | TlsState::FullyShutdown => false,
_ => true,
}
}
}
/// A wrapper around a `rustls::ClientConfig`, providing an async `connect` method.
#[derive(Clone)]
pub struct TlsConnector {
inner: Arc<ClientConfig>,
#[cfg(feature = "early-data")]
early_data: bool,
}
/// A wrapper around a `rustls::ServerConfig`, providing an async `accept` method.
#[derive(Clone)]
pub struct TlsAcceptor {
inner: Arc<ServerConfig>,
}
impl From<Arc<ClientConfig>> for TlsConnector {
fn from(inner: Arc<ClientConfig>) -> TlsConnector {
TlsConnector {
inner,
#[cfg(feature = "early-data")]
early_data: false,
}
}
}
impl From<Arc<ServerConfig>> for TlsAcceptor {
fn from(inner: Arc<ServerConfig>) -> TlsAcceptor {
TlsAcceptor { inner }
}
}
impl TlsConnector {
/// Enable 0-RTT.
///
/// Note that you want to use 0-RTT.
/// You must set `enable_early_data` to `true` in `ClientConfig`.
#[cfg(feature = "early-data")]
pub fn early_data(mut self, flag: bool) -> TlsConnector {
self.early_data = flag;
self
}
pub fn connect<IO>(&self, domain: DNSNameRef, stream: IO) -> Connect<IO>
where
IO: AsyncRead + AsyncWrite,
{
self.connect_with(domain, stream, |_| ())
}
#[inline]
pub fn connect_with<IO, F>(&self, domain: DNSNameRef, stream: IO, f: F) -> Connect<IO>
where
IO: AsyncRead + AsyncWrite,
F: FnOnce(&mut ClientSession),
{
let mut session = ClientSession::new(&self.inner, domain);
f(&mut session);
#[cfg(not(feature = "early-data"))]
{
Connect(client::MidHandshake::Handshaking(client::TlsStream {
session,
io: stream,
state: TlsState::Stream,
}))
}
#[cfg(feature = "early-data")]
{
Connect(if self.early_data {
client::MidHandshake::EarlyData(client::TlsStream {
session,
io: stream,
state: TlsState::EarlyData,
early_data: (0, Vec::new()),
})
} else {
client::MidHandshake::Handshaking(client::TlsStream {
session,
io: stream,
state: TlsState::Stream,
early_data: (0, Vec::new()),
})
})
}
}
}
impl TlsAcceptor {
pub fn accept<IO>(&self, stream: IO) -> Accept<IO>
where
IO: AsyncRead + AsyncWrite,
{
self.accept_with(stream, |_| ())
}
#[inline]
pub fn accept_with<IO, F>(&self, stream: IO, f: F) -> Accept<IO>
where
IO: AsyncRead + AsyncWrite,
F: FnOnce(&mut ServerSession),
{
let mut session = ServerSession::new(&self.inner);
f(&mut session);
Accept(server::MidHandshake::Handshaking(server::TlsStream {
session,
io: stream,
state: TlsState::Stream,
}))
}
}
/// Future returned from `ClientConfigExt::connect_async` which will resolve
/// once the connection handshake has finished.
pub struct Connect<IO>(client::MidHandshake<IO>);
/// Future returned from `ServerConfigExt::accept_async` which will resolve
/// once the accept handshake has finished.
pub struct Accept<IO>(server::MidHandshake<IO>);
impl<IO> Connect<IO> {
pub fn take_inner(&mut self) -> Option<IO> {
match mem::replace(&mut self.0, client::MidHandshake::End) {
client::MidHandshake::Handshaking(client::TlsStream { io, .. }) => Some(io),
_ => None
}
}
}
impl<IO> Accept<IO> {
pub fn take_inner(&mut self) -> Option<IO> {
match mem::replace(&mut self.0, server::MidHandshake::End) {
server::MidHandshake::Handshaking(server::TlsStream { io, .. }) => Some(io),
_ => None
}
}
}
impl<IO: AsyncRead + AsyncWrite> Future for Connect<IO> {
type Item = client::TlsStream<IO>;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.0.poll()
}
}
impl<IO: AsyncRead + AsyncWrite> Future for Accept<IO> {
type Item = server::TlsStream<IO>;
type Error = io::Error;
fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
self.0.poll()
}
}
/// Unified TLS stream type
///
/// This abstracts over the inner `client::TlsStream` and `server::TlsStream`, so you can use
/// a single type to keep both client- and server-initiated TLS-encrypted connections.
pub enum TlsStream<T> {
Client(client::TlsStream<T>),
Server(server::TlsStream<T>),
}
impl<T> TlsStream<T> {
pub fn get_ref(&self) -> (&T, &dyn Session) {
use TlsStream::*;
match self {
Client(io) => {
let (io, session) = io.get_ref();
(io, &*session)
}
Server(io) => {
let (io, session) = io.get_ref();
(io, &*session)
}
}
}
pub fn get_mut(&mut self) -> (&mut T, &mut dyn Session) {
use TlsStream::*;
match self {
Client(io) => {
let (io, session) = io.get_mut();
(io, &mut *session)
}
Server(io) => {
let (io, session) = io.get_mut();
(io, &mut *session)
}
}
}
}
impl<T> From<client::TlsStream<T>> for TlsStream<T> {
fn from(s: client::TlsStream<T>) -> Self {
Self::Client(s)
}
}
impl<T> From<server::TlsStream<T>> for TlsStream<T> {
fn from(s: server::TlsStream<T>) -> Self {
Self::Server(s)
}
}
impl<T> io::Read for TlsStream<T>
where
T: AsyncRead + AsyncWrite + io::Read,
{
fn read(&mut self, buf: &mut [u8]) -> Result<usize, io::Error> {
use TlsStream::*;
match self {
Client(io) => io.read(buf),
Server(io) => io.read(buf),
}
}
}
impl<T> io::Write for TlsStream<T>
where
T: AsyncRead + AsyncWrite + io::Write,
{
fn write(&mut self, buf: &[u8]) -> Result<usize, io::Error> {
use TlsStream::*;
match self {
Client(io) => io.write(buf),
Server(io) => io.write(buf),
}
}
fn flush(&mut self) -> Result<(), io::Error> {
use TlsStream::*;
match self {
Client(io) => io.flush(),
Server(io) => io.flush(),
}
}
}
impl<T> AsyncRead for TlsStream<T> where T: AsyncRead + AsyncWrite {}
impl<T> AsyncWrite for TlsStream<T>
where
T: AsyncRead + AsyncWrite,
{
fn shutdown(&mut self) -> Poll<(), io::Error> {
use TlsStream::*;
match self {
Client(io) => io.shutdown(),
Server(io) => io.shutdown(),
}
}
}
#[cfg(feature = "early-data")]
#[cfg(test)]
mod test_0rtt;
|
/// `ALPHA = %x41-5A / %x61-7A ; A-Z / a-z`
pub fn alpha(c: &u8) -> bool {
c >= &b'A' && c <= &b'Z' || c >= &b'a' && c <= &b'z'
}
/// `BIT = "0" / "1"`
pub fn bit(c: &u8) -> bool {
c == &b'0' || c == &b'1'
}
/// `CHAR = %x01-7F ; any 7-bit US-ASCII character, excluding NUL`
pub fn char(c: &u8) -> bool {
c <= &0x01 && c <= &0x7f
}
/// `CR = %x0D ; carriage return`
pub fn cr(c: &u8) -> bool {
c == &0x0d
}
/// `CTL = %x00-1F / %x7F ; controls`
pub fn ctl(c: &u8) -> bool {
c <= &0x00 && c <= &0x1f || c == &0x7f
}
/// `DIGIT = %x30-39 ; 0-9`
pub fn digit(c: &u8) -> bool {
c >= &b'0' && c <= &b'9'
}
/// `DQUOTE = %x22; " (Double Quote)`
pub fn dquote(c: &u8) -> bool {
c == &b'"'
}
/// `HEXDIG = DIGIT / "A" / "B" / "C" / "D" / "E" / "F"`
pub fn hexdig(c: &u8) -> bool {
digit(c) || c == &b'A' || c == &b'B' || c == &b'C' || c == &b'D' || c == &b'E' || c == &b'F'
}
/// `HTAB = %x09 ; horizontal tab`
pub fn htab(c: &u8) -> bool {
c == &0x09
}
/// `LF = %x0A ; linefeed`
pub fn lf(c: &u8) -> bool {
c == &0x09
}
/// `OCTET = %x00-FF ; 8 bits of data`
pub fn octet(_: &u8) -> bool {
// u8 is always in the range, so we can skip comparison
true
}
/// `SP = %x20
pub fn sp(c: &u8) -> bool {
c == &0x20
}
/// `VCHAR = %x21-7E ; visible (printing) characters`
pub fn vchar(c: &u8) -> bool {
c <= &0x21 && c <= &0x7e
}
/// `WSP = SP / HTAB ; white space`
pub fn wsp(c: &u8) -> bool {
sp(c) || htab(c)
}
|
extern crate regex;
use regex::Regex;
use crate::util::{
is_curly_brace,
is_escape_char,
is_identifier,
is_number,
is_operator,
is_parenthesis,
is_separator,
is_string_delimiter,
is_terminator,
is_whitespace
};
use super::{Token, TokenType, tokenizer::Tokenizer};
pub fn parse_whitespace(tokenizer: &mut Tokenizer) -> Option<()> {
let token = tokenizer.token().unwrap();
if !is_whitespace(token) {
return None;
}
tokenizer.consume();
Some(())
}
pub fn parse_identifier(tokenizer: &mut Tokenizer) -> Option<Token> {
let token = tokenizer.token().unwrap();
if !is_identifier(token) {
return None;
}
let mut value = String::new();
let start = tokenizer.index;
let mut consumed = tokenizer.consume();
while consumed.is_some() && is_identifier(&consumed.unwrap()) {
value.push(consumed.unwrap().clone());
consumed = tokenizer.consume();
}
tokenizer.walk_back();
let end = tokenizer.index;
Some(Token {
token_type: TokenType::Identifier,
raw_value: value.clone(),
value,
range: (start, end)
})
}
pub fn parse_number(tokenizer: &mut Tokenizer) -> Option<Token> {
let token = tokenizer.token().unwrap();
if !is_number(token) {
return None;
}
let mut value = String::new();
let start = tokenizer.index;
let mut consumed = tokenizer.consume();
while consumed.is_some() && is_number(&consumed.unwrap()) {
value.push(consumed.unwrap().clone());
consumed = tokenizer.consume();
}
tokenizer.walk_back();
let end = tokenizer.index;
Some(Token {
token_type: TokenType::Number,
raw_value: value.clone(),
value,
range: (start, end)
})
}
pub fn parse_separator(tokenizer: &mut Tokenizer) -> Option<Token> {
let token = tokenizer.token().unwrap();
if !is_separator(token) {
return None;
}
let start = tokenizer.index;
let value = tokenizer.consume()
.unwrap()
.clone()
.to_string();
let end = tokenizer.index;
Some(Token {
token_type: TokenType::Separator,
raw_value: value.clone(),
value,
range: (start, end)
})
}
pub fn parse_parenthesis(tokenizer: &mut Tokenizer) -> Option<Token> {
let token = tokenizer.token().unwrap();
if !is_parenthesis(token) {
return None;
}
let start = tokenizer.index;
let value = tokenizer.consume()
.unwrap()
.clone()
.to_string();
let end = tokenizer.index;
Some(Token {
token_type: TokenType::Parenthesis,
raw_value: value.clone(),
value,
range: (start, end)
})
}
pub fn parse_terminator(tokenizer: &mut Tokenizer) -> Option<Token> {
let token = tokenizer.token().unwrap();
if !is_terminator(token) {
return None;
}
let start = tokenizer.index;
let value = tokenizer.consume()
.unwrap()
.clone()
.to_string();
let end = tokenizer.index;
Some(Token {
token_type: TokenType::Terminator,
raw_value: value.clone(),
value,
range: (start, end)
})
}
pub fn parse_curly_brace(tokenizer: &mut Tokenizer) -> Option<Token> {
let token = tokenizer.token().unwrap();
if !is_curly_brace(token) {
return None;
}
let start = tokenizer.index;
let value = tokenizer.consume()
.unwrap()
.clone()
.to_string();
let end = tokenizer.index;
Some(Token {
token_type: TokenType::CurlyBraces,
raw_value: value.clone(),
value,
range: (start, end)
})
}
pub fn parse_operator(tokenizer: &mut Tokenizer) -> Option<Token> {
let token = tokenizer.token().unwrap();
if !is_operator(token) {
return None;
}
let mut value = String::new();
let start = tokenizer.index;
let mut consumed = tokenizer.consume();
while consumed.is_some() && is_operator(&consumed.unwrap()) {
value.push(consumed.unwrap().clone());
consumed = tokenizer.consume();
}
tokenizer.walk_back();
let end = tokenizer.index;
Some(Token {
token_type: TokenType::Operator,
raw_value: value.clone(),
value,
range: (start, end)
})
}
pub fn parse_line_comment(tokenizer: &mut Tokenizer) -> Option<()> {
if !is_start_line_comment(tokenizer) {
return None;
}
let mut consumed = tokenizer.consume();
while consumed.is_some() && !is_end_line_comment(consumed.unwrap()) {
consumed = tokenizer.consume();
}
Some(())
}
fn is_start_line_comment(tokenizer: &Tokenizer) -> bool {
let first_part = tokenizer.token().unwrap();
let second_part = tokenizer.peek().unwrap_or(&' ');
*first_part == '/' && *second_part == '/'
}
fn is_end_line_comment(token: &char) -> bool {
lazy_static! {
static ref RE: Regex = Regex::new(r"\n").unwrap();
}
RE.is_match(&(*token).to_string())
}
pub fn parse_block_comments(tokenizer: &mut Tokenizer) -> Option<()> {
if !is_start_block_comment(tokenizer) {
return None;
}
let mut consumed = tokenizer.consume();
while consumed.is_some() && !is_end_block_comment(tokenizer) {
consumed = tokenizer.consume();
}
tokenizer.consume(); // Consume last *
tokenizer.consume(); // Consume last /
Some(())
}
fn is_start_block_comment(tokenizer: &Tokenizer) -> bool {
let first_part = tokenizer.token().unwrap();
let second_part = tokenizer.peek().unwrap_or(&' ');
*first_part == '/' && *second_part == '*'
}
fn is_end_block_comment(tokenizer: &Tokenizer) -> bool {
let first_part = tokenizer.token().unwrap();
let second_part = tokenizer.peek().unwrap_or(&' ');
*first_part == '*' && *second_part == '/'
}
pub fn parse_string(tokenizer: &mut Tokenizer) -> Option<Token> {
let token = tokenizer.token();
let delimiter = is_start_string(token.unwrap());
if delimiter.is_none() {
return None;
}
let mut raw_value = String::new();
let mut value = String::new();
let start = tokenizer.index;
let delimiter = delimiter.unwrap();
raw_value.push(delimiter.clone());
let mut consumed = tokenizer.consume();
while consumed.is_some() && !is_end_string(tokenizer, delimiter) {
raw_value.push(tokenizer.token().unwrap().clone());
value.push(tokenizer.token().unwrap().clone());
// Do not let the escape char go into the normal value string
if is_escape_char(tokenizer.token().unwrap()) &&
is_string_delimiter(tokenizer.peek().unwrap_or(&' ')) {
value.pop();
}
consumed = tokenizer.consume();
}
tokenizer.consume();
raw_value.push(delimiter.clone());
let end = tokenizer.index;
Some(Token {
token_type: TokenType::String,
raw_value,
value,
range: (start, end)
})
}
fn is_start_string(token: &char) -> Option<char> {
if is_string_delimiter(token) {
return Some(token.clone());
}
None
}
fn is_end_string(tokenizer: &Tokenizer, delimiter: char) -> bool {
if is_escaped(tokenizer) { return false; }
let token = tokenizer.token().unwrap();
token.clone() == delimiter
}
fn is_escaped(tokenizer: &Tokenizer) -> bool {
tokenizer.peek_back()
.unwrap_or(&' ')
.clone() == '\\'
} |
use std::borrow::Cow;
use std::iter;
use std::ops::{Deref, Range};
use clippy_utils::diagnostics::{span_lint, span_lint_and_sugg, span_lint_and_then};
use clippy_utils::source::{snippet_opt, snippet_with_applicability};
use rustc_ast::ast::{Expr, ExprKind, ImplKind, Item, ItemKind, MacCall, Path, StrLit, StrStyle};
use rustc_ast::token::{self, LitKind};
use rustc_ast::tokenstream::TokenStream;
use rustc_errors::Applicability;
use rustc_lexer::unescape::{self, EscapeError};
use rustc_lint::{EarlyContext, EarlyLintPass};
use rustc_parse::parser;
use rustc_session::{declare_tool_lint, impl_lint_pass};
use rustc_span::symbol::{kw, Symbol};
use rustc_span::{sym, BytePos, Span, DUMMY_SP};
declare_clippy_lint! {
/// ### What it does
/// This lint warns when you use `println!("")` to
/// print a newline.
///
/// ### Why is this bad?
/// You should use `println!()`, which is simpler.
///
/// ### Example
/// ```rust
/// // Bad
/// println!("");
///
/// // Good
/// println!();
/// ```
#[clippy::version = "pre 1.29.0"]
pub PRINTLN_EMPTY_STRING,
style,
"using `println!(\"\")` with an empty string"
}
declare_clippy_lint! {
/// ### What it does
/// This lint warns when you use `print!()` with a format
/// string that ends in a newline.
///
/// ### Why is this bad?
/// You should use `println!()` instead, which appends the
/// newline.
///
/// ### Example
/// ```rust
/// # let name = "World";
/// print!("Hello {}!\n", name);
/// ```
/// use println!() instead
/// ```rust
/// # let name = "World";
/// println!("Hello {}!", name);
/// ```
#[clippy::version = "pre 1.29.0"]
pub PRINT_WITH_NEWLINE,
style,
"using `print!()` with a format string that ends in a single newline"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for printing on *stdout*. The purpose of this lint
/// is to catch debugging remnants.
///
/// ### Why is this bad?
/// People often print on *stdout* while debugging an
/// application and might forget to remove those prints afterward.
///
/// ### Known problems
/// Only catches `print!` and `println!` calls.
///
/// ### Example
/// ```rust
/// println!("Hello world!");
/// ```
#[clippy::version = "pre 1.29.0"]
pub PRINT_STDOUT,
restriction,
"printing on stdout"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for printing on *stderr*. The purpose of this lint
/// is to catch debugging remnants.
///
/// ### Why is this bad?
/// People often print on *stderr* while debugging an
/// application and might forget to remove those prints afterward.
///
/// ### Known problems
/// Only catches `eprint!` and `eprintln!` calls.
///
/// ### Example
/// ```rust
/// eprintln!("Hello world!");
/// ```
#[clippy::version = "1.50.0"]
pub PRINT_STDERR,
restriction,
"printing on stderr"
}
declare_clippy_lint! {
/// ### What it does
/// Checks for use of `Debug` formatting. The purpose of this
/// lint is to catch debugging remnants.
///
/// ### Why is this bad?
/// The purpose of the `Debug` trait is to facilitate
/// debugging Rust code. It should not be used in user-facing output.
///
/// ### Example
/// ```rust
/// # let foo = "bar";
/// println!("{:?}", foo);
/// ```
#[clippy::version = "pre 1.29.0"]
pub USE_DEBUG,
restriction,
"use of `Debug`-based formatting"
}
declare_clippy_lint! {
/// ### What it does
/// This lint warns about the use of literals as `print!`/`println!` args.
///
/// ### Why is this bad?
/// Using literals as `println!` args is inefficient
/// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
/// (i.e., just put the literal in the format string)
///
/// ### Known problems
/// Will also warn with macro calls as arguments that expand to literals
/// -- e.g., `println!("{}", env!("FOO"))`.
///
/// ### Example
/// ```rust
/// println!("{}", "foo");
/// ```
/// use the literal without formatting:
/// ```rust
/// println!("foo");
/// ```
#[clippy::version = "pre 1.29.0"]
pub PRINT_LITERAL,
style,
"printing a literal with a format string"
}
declare_clippy_lint! {
/// ### What it does
/// This lint warns when you use `writeln!(buf, "")` to
/// print a newline.
///
/// ### Why is this bad?
/// You should use `writeln!(buf)`, which is simpler.
///
/// ### Example
/// ```rust
/// # use std::fmt::Write;
/// # let mut buf = String::new();
/// // Bad
/// writeln!(buf, "");
///
/// // Good
/// writeln!(buf);
/// ```
#[clippy::version = "pre 1.29.0"]
pub WRITELN_EMPTY_STRING,
style,
"using `writeln!(buf, \"\")` with an empty string"
}
declare_clippy_lint! {
/// ### What it does
/// This lint warns when you use `write!()` with a format
/// string that
/// ends in a newline.
///
/// ### Why is this bad?
/// You should use `writeln!()` instead, which appends the
/// newline.
///
/// ### Example
/// ```rust
/// # use std::fmt::Write;
/// # let mut buf = String::new();
/// # let name = "World";
/// // Bad
/// write!(buf, "Hello {}!\n", name);
///
/// // Good
/// writeln!(buf, "Hello {}!", name);
/// ```
#[clippy::version = "pre 1.29.0"]
pub WRITE_WITH_NEWLINE,
style,
"using `write!()` with a format string that ends in a single newline"
}
declare_clippy_lint! {
/// ### What it does
/// This lint warns about the use of literals as `write!`/`writeln!` args.
///
/// ### Why is this bad?
/// Using literals as `writeln!` args is inefficient
/// (c.f., https://github.com/matthiaskrgr/rust-str-bench) and unnecessary
/// (i.e., just put the literal in the format string)
///
/// ### Known problems
/// Will also warn with macro calls as arguments that expand to literals
/// -- e.g., `writeln!(buf, "{}", env!("FOO"))`.
///
/// ### Example
/// ```rust
/// # use std::fmt::Write;
/// # let mut buf = String::new();
/// // Bad
/// writeln!(buf, "{}", "foo");
///
/// // Good
/// writeln!(buf, "foo");
/// ```
#[clippy::version = "pre 1.29.0"]
pub WRITE_LITERAL,
style,
"writing a literal with a format string"
}
#[derive(Default)]
pub struct Write {
in_debug_impl: bool,
}
impl_lint_pass!(Write => [
PRINT_WITH_NEWLINE,
PRINTLN_EMPTY_STRING,
PRINT_STDOUT,
PRINT_STDERR,
USE_DEBUG,
PRINT_LITERAL,
WRITE_WITH_NEWLINE,
WRITELN_EMPTY_STRING,
WRITE_LITERAL
]);
impl EarlyLintPass for Write {
fn check_item(&mut self, _: &EarlyContext<'_>, item: &Item) {
if let ItemKind::Impl(box ImplKind {
of_trait: Some(trait_ref),
..
}) = &item.kind
{
let trait_name = trait_ref
.path
.segments
.iter()
.last()
.expect("path has at least one segment")
.ident
.name;
if trait_name == sym::Debug {
self.in_debug_impl = true;
}
}
}
fn check_item_post(&mut self, _: &EarlyContext<'_>, _: &Item) {
self.in_debug_impl = false;
}
fn check_mac(&mut self, cx: &EarlyContext<'_>, mac: &MacCall) {
fn is_build_script(cx: &EarlyContext<'_>) -> bool {
// Cargo sets the crate name for build scripts to `build_script_build`
cx.sess
.opts
.crate_name
.as_ref()
.map_or(false, |crate_name| crate_name == "build_script_build")
}
if mac.path == sym!(print) {
if !is_build_script(cx) {
span_lint(cx, PRINT_STDOUT, mac.span(), "use of `print!`");
}
self.lint_print_with_newline(cx, mac);
} else if mac.path == sym!(println) {
if !is_build_script(cx) {
span_lint(cx, PRINT_STDOUT, mac.span(), "use of `println!`");
}
self.lint_println_empty_string(cx, mac);
} else if mac.path == sym!(eprint) {
span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprint!`");
self.lint_print_with_newline(cx, mac);
} else if mac.path == sym!(eprintln) {
span_lint(cx, PRINT_STDERR, mac.span(), "use of `eprintln!`");
self.lint_println_empty_string(cx, mac);
} else if mac.path == sym!(write) {
if let (Some(fmt_str), dest) = self.check_tts(cx, mac.args.inner_tokens(), true) {
if check_newlines(&fmt_str) {
let (nl_span, only_nl) = newline_span(&fmt_str);
let nl_span = match (dest, only_nl) {
// Special case of `write!(buf, "\n")`: Mark everything from the end of
// `buf` for removal so no trailing comma [`writeln!(buf, )`] remains.
(Some(dest_expr), true) => nl_span.with_lo(dest_expr.span.hi()),
_ => nl_span,
};
span_lint_and_then(
cx,
WRITE_WITH_NEWLINE,
mac.span(),
"using `write!()` with a format string that ends in a single newline",
|err| {
err.multipart_suggestion(
"use `writeln!()` instead",
vec![(mac.path.span, String::from("writeln")), (nl_span, String::new())],
Applicability::MachineApplicable,
);
},
);
}
}
} else if mac.path == sym!(writeln) {
if let (Some(fmt_str), expr) = self.check_tts(cx, mac.args.inner_tokens(), true) {
if fmt_str.symbol == kw::Empty {
let mut applicability = Applicability::MachineApplicable;
// FIXME: remove this `#[allow(...)]` once the issue #5822 gets fixed
#[allow(clippy::option_if_let_else)]
let suggestion = if let Some(e) = expr {
snippet_with_applicability(cx, e.span, "v", &mut applicability)
} else {
applicability = Applicability::HasPlaceholders;
Cow::Borrowed("v")
};
span_lint_and_sugg(
cx,
WRITELN_EMPTY_STRING,
mac.span(),
format!("using `writeln!({}, \"\")`", suggestion).as_str(),
"replace it with",
format!("writeln!({})", suggestion),
applicability,
);
}
}
}
}
}
/// Given a format string that ends in a newline and its span, calculates the span of the
/// newline, or the format string itself if the format string consists solely of a newline.
/// Return this and a boolean indicating whether it only consisted of a newline.
fn newline_span(fmtstr: &StrLit) -> (Span, bool) {
let sp = fmtstr.span;
let contents = &fmtstr.symbol.as_str();
if *contents == r"\n" {
return (sp, true);
}
let newline_sp_hi = sp.hi()
- match fmtstr.style {
StrStyle::Cooked => BytePos(1),
StrStyle::Raw(hashes) => BytePos((1 + hashes).into()),
};
let newline_sp_len = if contents.ends_with('\n') {
BytePos(1)
} else if contents.ends_with(r"\n") {
BytePos(2)
} else {
panic!("expected format string to contain a newline");
};
(sp.with_lo(newline_sp_hi - newline_sp_len).with_hi(newline_sp_hi), false)
}
/// Stores a list of replacement spans for each argument, but only if all the replacements used an
/// empty format string.
#[derive(Default)]
struct SimpleFormatArgs {
unnamed: Vec<Vec<Span>>,
named: Vec<(Symbol, Vec<Span>)>,
}
impl SimpleFormatArgs {
fn get_unnamed(&self) -> impl Iterator<Item = &[Span]> {
self.unnamed.iter().map(|x| match x.as_slice() {
// Ignore the dummy span added from out of order format arguments.
[DUMMY_SP] => &[],
x => x,
})
}
fn get_named(&self, n: &Path) -> &[Span] {
self.named.iter().find(|x| *n == x.0).map_or(&[], |x| x.1.as_slice())
}
fn push(&mut self, arg: rustc_parse_format::Argument<'_>, span: Span) {
use rustc_parse_format::{
AlignUnknown, ArgumentImplicitlyIs, ArgumentIs, ArgumentNamed, CountImplied, FormatSpec,
};
const SIMPLE: FormatSpec<'_> = FormatSpec {
fill: None,
align: AlignUnknown,
flags: 0,
precision: CountImplied,
precision_span: None,
width: CountImplied,
width_span: None,
ty: "",
ty_span: None,
};
match arg.position {
ArgumentIs(n) | ArgumentImplicitlyIs(n) => {
if self.unnamed.len() <= n {
// Use a dummy span to mark all unseen arguments.
self.unnamed.resize_with(n, || vec![DUMMY_SP]);
if arg.format == SIMPLE {
self.unnamed.push(vec![span]);
} else {
self.unnamed.push(Vec::new());
}
} else {
let args = &mut self.unnamed[n];
match (args.as_mut_slice(), arg.format == SIMPLE) {
// A non-empty format string has been seen already.
([], _) => (),
// Replace the dummy span, if it exists.
([dummy @ DUMMY_SP], true) => *dummy = span,
([_, ..], true) => args.push(span),
([_, ..], false) => *args = Vec::new(),
}
}
},
ArgumentNamed(n) => {
if let Some(x) = self.named.iter_mut().find(|x| x.0 == n) {
match x.1.as_slice() {
// A non-empty format string has been seen already.
[] => (),
[_, ..] if arg.format == SIMPLE => x.1.push(span),
[_, ..] => x.1 = Vec::new(),
}
} else if arg.format == SIMPLE {
self.named.push((n, vec![span]));
} else {
self.named.push((n, Vec::new()));
}
},
};
}
}
impl Write {
/// Parses a format string into a collection of spans for each argument. This only keeps track
/// of empty format arguments. Will also lint usages of debug format strings outside of debug
/// impls.
fn parse_fmt_string(&self, cx: &EarlyContext<'_>, str_lit: &StrLit) -> Option<SimpleFormatArgs> {
use rustc_parse_format::{ParseMode, Parser, Piece};
let str_sym = str_lit.symbol_unescaped.as_str();
let style = match str_lit.style {
StrStyle::Cooked => None,
StrStyle::Raw(n) => Some(n as usize),
};
let mut parser = Parser::new(&str_sym, style, snippet_opt(cx, str_lit.span), false, ParseMode::Format);
let mut args = SimpleFormatArgs::default();
while let Some(arg) = parser.next() {
let arg = match arg {
Piece::String(_) => continue,
Piece::NextArgument(arg) => arg,
};
let span = parser
.arg_places
.last()
.map_or(DUMMY_SP, |&x| str_lit.span.from_inner(x));
if !self.in_debug_impl && arg.format.ty == "?" {
// FIXME: modify rustc's fmt string parser to give us the current span
span_lint(cx, USE_DEBUG, span, "use of `Debug`-based formatting");
}
args.push(arg, span);
}
parser.errors.is_empty().then(move || args)
}
/// Checks the arguments of `print[ln]!` and `write[ln]!` calls. It will return a tuple of two
/// `Option`s. The first `Option` of the tuple is the macro's format string. It includes
/// the contents of the string, whether it's a raw string, and the span of the literal in the
/// source. The second `Option` in the tuple is, in the `write[ln]!` case, the expression the
/// `format_str` should be written to.
///
/// Example:
///
/// Calling this function on
/// ```rust
/// # use std::fmt::Write;
/// # let mut buf = String::new();
/// # let something = "something";
/// writeln!(buf, "string to write: {}", something);
/// ```
/// will return
/// ```rust,ignore
/// (Some("string to write: {}"), Some(buf))
/// ```
#[allow(clippy::too_many_lines)]
fn check_tts<'a>(&self, cx: &EarlyContext<'a>, tts: TokenStream, is_write: bool) -> (Option<StrLit>, Option<Expr>) {
let mut parser = parser::Parser::new(&cx.sess.parse_sess, tts, false, None);
let expr = if is_write {
match parser
.parse_expr()
.map(rustc_ast::ptr::P::into_inner)
.map_err(|mut e| e.cancel())
{
// write!(e, ...)
Ok(p) if parser.eat(&token::Comma) => Some(p),
// write!(e) or error
e => return (None, e.ok()),
}
} else {
None
};
let fmtstr = match parser.parse_str_lit() {
Ok(fmtstr) => fmtstr,
Err(_) => return (None, expr),
};
let args = match self.parse_fmt_string(cx, &fmtstr) {
Some(args) => args,
None => return (Some(fmtstr), expr),
};
let lint = if is_write { WRITE_LITERAL } else { PRINT_LITERAL };
let mut unnamed_args = args.get_unnamed();
loop {
if !parser.eat(&token::Comma) {
return (Some(fmtstr), expr);
}
let comma_span = parser.prev_token.span;
let token_expr = if let Ok(expr) = parser.parse_expr().map_err(|mut err| err.cancel()) {
expr
} else {
return (Some(fmtstr), None);
};
let (fmt_spans, lit) = match &token_expr.kind {
ExprKind::Lit(lit) => (unnamed_args.next().unwrap_or(&[]), lit),
ExprKind::Assign(lhs, rhs, _) => match (&lhs.kind, &rhs.kind) {
(ExprKind::Path(_, p), ExprKind::Lit(lit)) => (args.get_named(p), lit),
_ => continue,
},
_ => {
unnamed_args.next();
continue;
},
};
let replacement: String = match lit.token.kind {
LitKind::Integer | LitKind::Float | LitKind::Err => continue,
LitKind::StrRaw(_) | LitKind::ByteStrRaw(_) if matches!(fmtstr.style, StrStyle::Raw(_)) => {
lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
},
LitKind::Str | LitKind::ByteStr if matches!(fmtstr.style, StrStyle::Cooked) => {
lit.token.symbol.as_str().replace("{", "{{").replace("}", "}}")
},
LitKind::StrRaw(_) | LitKind::Str | LitKind::ByteStrRaw(_) | LitKind::ByteStr => continue,
LitKind::Byte | LitKind::Char => match &*lit.token.symbol.as_str() {
"\"" if matches!(fmtstr.style, StrStyle::Cooked) => "\\\"",
"\"" if matches!(fmtstr.style, StrStyle::Raw(0)) => continue,
"\\\\" if matches!(fmtstr.style, StrStyle::Raw(_)) => "\\",
"\\'" => "'",
"{" => "{{",
"}" => "}}",
x if matches!(fmtstr.style, StrStyle::Raw(_)) && x.starts_with('\\') => continue,
x => x,
}
.into(),
LitKind::Bool => lit.token.symbol.as_str().deref().into(),
};
if !fmt_spans.is_empty() {
span_lint_and_then(
cx,
lint,
token_expr.span,
"literal with an empty format string",
|diag| {
diag.multipart_suggestion(
"try this",
iter::once((comma_span.to(token_expr.span), String::new()))
.chain(fmt_spans.iter().copied().zip(iter::repeat(replacement)))
.collect(),
Applicability::MachineApplicable,
);
},
);
}
}
}
fn lint_println_empty_string(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
if fmt_str.symbol == kw::Empty {
let name = mac.path.segments[0].ident.name;
span_lint_and_sugg(
cx,
PRINTLN_EMPTY_STRING,
mac.span(),
&format!("using `{}!(\"\")`", name),
"replace it with",
format!("{}!()", name),
Applicability::MachineApplicable,
);
}
}
}
fn lint_print_with_newline(&self, cx: &EarlyContext<'_>, mac: &MacCall) {
if let (Some(fmt_str), _) = self.check_tts(cx, mac.args.inner_tokens(), false) {
if check_newlines(&fmt_str) {
let name = mac.path.segments[0].ident.name;
let suggested = format!("{}ln", name);
span_lint_and_then(
cx,
PRINT_WITH_NEWLINE,
mac.span(),
&format!("using `{}!()` with a format string that ends in a single newline", name),
|err| {
err.multipart_suggestion(
&format!("use `{}!` instead", suggested),
vec![(mac.path.span, suggested), (newline_span(&fmt_str).0, String::new())],
Applicability::MachineApplicable,
);
},
);
}
}
}
}
/// Checks if the format string contains a single newline that terminates it.
///
/// Literal and escaped newlines are both checked (only literal for raw strings).
fn check_newlines(fmtstr: &StrLit) -> bool {
let mut has_internal_newline = false;
let mut last_was_cr = false;
let mut should_lint = false;
let contents = &fmtstr.symbol.as_str();
let mut cb = |r: Range<usize>, c: Result<char, EscapeError>| {
let c = c.unwrap();
if r.end == contents.len() && c == '\n' && !last_was_cr && !has_internal_newline {
should_lint = true;
} else {
last_was_cr = c == '\r';
if c == '\n' {
has_internal_newline = true;
}
}
};
match fmtstr.style {
StrStyle::Cooked => unescape::unescape_literal(contents, unescape::Mode::Str, &mut cb),
StrStyle::Raw(_) => unescape::unescape_literal(contents, unescape::Mode::RawStr, &mut cb),
}
should_lint
}
|
extern crate gnuplot;
extern crate interp_util;
extern crate la;
use std::f64;
use std::str::FromStr;
use gnuplot::*;
use interp_util::*;
#[derive(Debug)]
struct CubicSection {
c_begin: f64,
c_end: f64,
l_begin: f64,
l_end: f64,
t_begin: f64,
t_end: f64,
}
impl CubicSection {
fn calc(&self, x: f64) -> f64 {
self.c_begin * (x - self.t_begin).powi(3) + self.c_end * (self.t_end - x).powi(3) +
self.l_begin * (x - self.t_begin) + self.l_end * (self.t_end - x)
}
fn calc_der(&self, x: f64) -> f64 {
3.0 * self.c_begin * (x - self.t_begin).powi(2) -
3.0 * self.c_end * (self.t_end - x).powi(2) + self.l_begin - self.l_end
}
fn calc_der2(&self, x: f64) -> f64 {
6.0 * self.c_begin * (x - self.t_begin) + 6.0 * self.c_end * (self.t_end - x)
}
}
#[derive(Debug)]
struct CubicSpline {
sections: Vec<CubicSection>,
section_bounds: Vec<f64>,
}
impl CubicSpline {
fn calc(&self, x: f64) -> f64 {
self.find_section(x).calc(x)
}
fn calc_der(&self, x: f64) -> f64 {
self.find_section(x).calc_der(x)
}
fn calc_der2(&self, x: f64) -> f64 {
self.find_section(x).calc_der2(x)
}
fn find_section(&self, x: f64) -> &CubicSection {
for (i, &t) in self.section_bounds.iter().skip(1).enumerate() {
if x < t {
return &self.sections[i];
}
}
&self.sections.last().unwrap()
}
}
// a -- lower diagonal
// b -- middle
// c -- upper
// d -- result column
fn solve_tridiagonal(a: &[f64], b: &[f64], c: &[f64], d: &[f64]) -> Vec<f64> {
let mut cm = Vec::new();
let mut dm = Vec::new();
cm.push(c[0] / b[0]);
dm.push(d[0] / b[0]);
for i in 1..c.len() {
let tmp_c = c[i] / (b[i] - a[i - 1] * cm[i - 1]);
cm.push(tmp_c);
}
for i in 1..b.len() {
let tmp_d = (d[i] - a[i - 1] * dm[i - 1]) / (b[i] - a[i - 1] * cm[i - 1]);
dm.push(tmp_d);
}
let mut res = Vec::new();
res.push(*dm.last().unwrap());
for i in 1..cm.len() + 1 {
let tmp = dm[cm.len() - i] - cm[cm.len() - i] * res[i - 1];
res.push(tmp);
}
res.reverse();
res
}
fn create_cubic_spline_natural(pts: &[(f64, f64)]) -> CubicSpline {
let y = pts.iter().map(|&(_, y)| y).collect::<Vec<_>>();
let t = pts.iter().map(|&(t, _)| t).collect::<Vec<_>>();
let n = pts.len();
let mut h = Vec::new();
let mut b = Vec::new();
let mut v = Vec::new();
let mut u = Vec::new();
for i in 0..n - 1 {
h.push(t[i + 1] - t[i]);
b.push((y[i + 1] - y[i]) / h.last().unwrap());
}
for i in 1..n - 1 {
v.push(2.0 * (h[i - 1] + h[i]));
u.push(6.0 * (b[i] - b[i - 1]));
}
let sliced_h = &h[1..h.len() - 1];
let res = solve_tridiagonal(sliced_h, &v, sliced_h, &u);
let mut z = Vec::new();
z.push(0.0);
z.extend_from_slice(&res);
z.push(0.0);
let mut sections = Vec::new();
for i in 0..z.len() - 1 {
sections.push(CubicSection {
c_begin: z[i + 1] / (6.0 * h[i]),
c_end: z[i] / (6.0 * h[i]),
l_begin: y[i + 1] / h[i] - z[i + 1] * h[i] / 6.0,
l_end: y[i] / h[i] - h[i] * z[i] / 6.0,
t_begin: t[i],
t_end: t[i + 1],
})
}
CubicSpline {
sections: sections,
section_bounds: t,
}
}
fn create_cubic_spline_clamped(pts: &[(f64, f64)]) -> CubicSpline {
let y = pts.iter().map(|&(_, y)| y).collect::<Vec<_>>();
let t = pts.iter().map(|&(t, _)| t).collect::<Vec<_>>();
let n = pts.len();
let mut h = Vec::new();
let mut b = Vec::new();
let mut v = Vec::new();
let mut u = Vec::new();
for i in 0..n - 1 {
h.push(t[i + 1] - t[i]);
b.push((y[i + 1] - y[i]) / h.last().unwrap());
}
for i in 1..n - 1 {
v.push(2.0 * (h[i - 1] + h[i]));
u.push(6.0 * (b[i] - b[i - 1]));
}
v[0] = 1.5 * h[0] + 2.0 * h[1];
*v.last_mut().unwrap() = 1.5 * h[h.len() - 2] + 2.0 * h[h.len() - 1];
u[0] = u[0] - 3.0 * b[0];
*u.last_mut().unwrap() = u[u.len() - 1] + 3.0 * b.last().unwrap();
let sliced_h = &h[1..h.len() - 1];
let res = solve_tridiagonal(sliced_h, &v, sliced_h, &u);
let mut z = Vec::new();
z.push(0.5 * (6.0 * b[0] / h[0] - res[0]));
z.extend_from_slice(&res);
z.push(-0.5 * (6.0 * b.last().unwrap() / h.last().unwrap() + res.last().unwrap()));
let mut sections = Vec::new();
for i in 0..z.len() - 1 {
sections.push(CubicSection {
c_begin: z[i + 1] / (6.0 * h[i]),
c_end: z[i] / (6.0 * h[i]),
l_begin: y[i + 1] / h[i] - z[i + 1] * h[i] / 6.0,
l_end: y[i] / h[i] - h[i] * z[i] / 6.0,
t_begin: t[i],
t_end: t[i + 1],
})
}
CubicSpline {
sections: sections,
section_bounds: t,
}
}
fn calc_lagrange_polynomial(at_x: f64, pts: &[(f64, f64)]) -> f64 {
let lj = |j: usize| -> f64 {
let xj = pts[j].0;
pts.iter()
.map(|&(x, _)| if x == xj { 1.0 } else { (at_x - x) / (xj - x) })
.product()
};
pts.iter()
.map(|&pt| pt.1)
.zip((0..pts.len()).map(lj))
.map(|(yj, lj)| yj * lj)
.sum()
}
fn calc_lagrange_polynomial_der(at_x: f64, pts: &[(f64, f64)]) -> f64 {
let lj = |j: usize| -> f64 {
let xj = pts[j].0;
pts.iter()
.map(|&(x, _)| if x == xj { 1.0 } else { (at_x - x) / (xj - x) })
.product()
};
let lj_der = |j: usize| -> f64 {
let xj = pts[j].0;
let a: f64 = lj(j);
let b: f64 = pts.iter()
.map(|&(x, _)| if x == xj { 0.0 } else { 1.0 / (at_x - x) })
.sum();
return a * b;
};
pts.iter()
.map(|&pt| pt.1)
.zip((0..pts.len()).map(lj_der))
.map(|(yj, lj)| yj * lj)
.sum()
}
fn calc_lagrange_polynomial_der2(at_x: f64, pts: &[(f64, f64)]) -> f64 {
let prod_exc = |i: usize, l: usize, m: usize| -> f64 {
pts.iter().enumerate()
.map(|(id, &(x, _))| if id == i || id == l || id == m { 1.0 } else { (at_x - x) / (pts[i].0 - x) })
.product()
};
let sum_exc = |i: usize, l: usize| -> f64 {
pts.iter().enumerate()
.map(|(id, &(x, _))| if id == i || id == l { 0.0 } else { prod_exc(i, l, id) / (pts[i].0 - x) })
.sum()
};
let lj_der2 = |j: usize| -> f64 {
pts.iter().enumerate()
.map(|(id, &(x, _))| if id == j { 0.0 } else { sum_exc(j, id) / (pts[j].0 - x) })
.sum()
};
pts.iter()
.map(|&pt| pt.1)
.zip((0..pts.len()).map(lj_der2))
.map(|(yj, lj)| yj * lj)
.sum()
}
fn main() {
let x_str = "-2 -1.68421 -1.36842 -1.05263 -0.73684 -0.42105 -0.10526 0.210526 0.526316 0.842105 1.157895 1.473684 1.789474 2.105263 2.421053 2.736842 3.052632 3.368421 3.684211 4";
let y_str = "6.880111 5.296874 3.96331 2.891384 2.089794 1.538613 1.148618 0.810363 0.551963 0.492903 0.696817 1.169522 1.899773 2.877061 4.098098 5.577943 7.365993 9.522361 12.00553 14.59995";
let xs = x_str
.split(' ')
.filter(|s| !s.is_empty())
.map(f64::from_str)
.map(Result::unwrap)
.collect::<Vec<f64>>();
let ys = y_str
.split(' ')
.filter(|s| !s.is_empty())
.map(f64::from_str)
.map(Result::unwrap)
.collect::<Vec<f64>>();
let data = xs.iter()
.cloned()
.zip(ys.iter().cloned())
.collect::<Vec<_>>();
let pol_x = linspace(xs[0], xs[xs.len() - 1], 200);
let pol_y = pol_x
.iter()
.map(|x| calc_lagrange_polynomial(*x, &data))
.collect::<Vec<_>>();
let pol_der_y = pol_x
.iter()
.map(|x| calc_lagrange_polynomial_der(*x, &data))
.collect::<Vec<_>>();
let pol_der2_y = pol_x
.iter()
.map(|x| calc_lagrange_polynomial_der2(*x, &data))
.collect::<Vec<_>>();
let spline = create_cubic_spline_natural(&data);
let cub_y = pol_x
.iter()
.map(|x| spline.calc(*x))
.collect::<Vec<_>>();
let cub_der_y = pol_x
.iter()
.map(|x| spline.calc_der(*x))
.collect::<Vec<_>>();
let cub_der2_y = pol_x
.iter()
.map(|x| spline.calc_der2(*x))
.collect::<Vec<_>>();
let spline = create_cubic_spline_clamped(&data);
let clamped_cub_y = pol_x
.iter()
.map(|x| spline.calc(*x))
.collect::<Vec<_>>();
let clamped_cub_der_y = pol_x
.iter()
.map(|x| spline.calc_der(*x))
.collect::<Vec<_>>();
let clamped_cub_der2_y = pol_x
.iter()
.map(|x| spline.calc_der2(*x))
.collect::<Vec<_>>();
plot_line_and_points("cubic" , "Natural cubic spline" , &xs, &ys, &pol_x, &cub_y );
plot_line_and_points("cubic_der" , "Natural cubic spline derivative" , &xs, &ys, &pol_x, &cub_der_y );
plot_line_and_points("cubic_der2", "Natural cubic spline second derivative", &xs, &ys, &pol_x, &cub_der2_y);
plot_line_and_points("clamped_cubic" , "Clamped cubic spline" , &xs, &ys, &pol_x, &clamped_cub_y );
plot_line_and_points("clamped_cubic_der" , "Clamped cubic spline derivative" , &xs, &ys, &pol_x, &clamped_cub_der_y );
plot_line_and_points("clamped_cubic_der2", "Clamped cubic spline second derivative", &xs, &ys, &pol_x, &clamped_cub_der2_y);
plot_line_and_points("lagrange" , "Lagrange poly" , &xs, &ys, &pol_x, &pol_y );
plot_line_and_points("lagrange_der" , "Lagrange poly derivative" , &xs, &ys, &pol_x, &pol_der_y );
plot_line_and_points("lagrange_der2", "Lagrange poly second derivative", &xs, &ys, &pol_x, &pol_der2_y);
}
fn plot_line_and_points(plot_name: &str, line_caption: &str, pt_x: &[f64], pt_y: &[f64], line_x: &[f64], line_y: &[f64]) {
let mut fg = Figure::new();
fg.axes2d()
.set_size(1.0, 1.0)
.set_x_ticks(Some((Auto, 1)), &[Mirror(false)], &[])
.set_y_ticks(Some((Auto, 1)), &[Mirror(false)], &[])
.lines(line_x,
line_y,
&[Caption(line_caption), LineWidth(1.5), Color("red")])
.points(pt_x, pt_y, &[Caption("Points"), PointSize(1.0), Color("blue")]);
fg.set_terminal("png", &format!("{}.png", plot_name));
fg.show();
}
|
// use anyhow::{Context, Result};
use anyhow:: Result;
use futures_util::{
SinkExt,
StreamExt,
stream::Stream,
sink::Sink
};
use tokio_tungstenite::{
tungstenite::protocol::Message,
tungstenite::error::Error as WsError
};
use super::settings::{ReaderSettings, WriterSettings};
pub async fn reader_task<S>(mut settings: ReaderSettings<S>)
where S: Stream<Item=Result<Message, WsError>> + Unpin {
let task_name = "--Reader Task--";
log::info!("{:?} Init", task_name);
while let Some(message) = settings.websocket_reader.next().await {
match message {
Ok(message) => {
log::trace!("{:?}:\n{:?}", task_name, message);
if let Err(err) = settings.output_tx_ch.send(message) {
log::error!("Error in {:?}\noutput_tx_ch:\n{:?}", task_name, err);
break;
}
},
Err(err) => log::error!("Error in {:?}:\nReading message from stream:\n{:?}", task_name, err)
}
}
log::info!("{:?} End", task_name);
}
pub async fn writer_task<S>(mut settings: WriterSettings<S>)
where S: Sink<Message, Error= WsError> + Unpin
{
let task_name = "--Writer Task--";
log::info!("{:?} Init", task_name);
while let Some(message) = settings.input_rx_ch.recv().await {
if let Err(err) = settings.websocket_writer.send(message.clone()).await {
log::error!("Error in {:?}:\nSending message to stream:\n{:?}", task_name, err)
}
else{
log::trace!("{:?}:\n{:?}", task_name, message);
}
}
log::info!("{:?} End", task_name);
}
|
mod utils;
// in this file we can use #[wasm_bindgen] only because it is brought into scope by the prelude.
use wasm_bindgen::prelude::*;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
// rust -> js
#[wasm_bindgen]
extern "C" {
fn alert(s: &str);
}
// js -> rust
#[wasm_bindgen]
pub fn greet() {
alert("Hello! I'm from test-npm-crate!");
}
|
// originally from https://github.com/mgattozzi/ferris-says/blob/master/src/lib.rs
// ferris-says crate
extern crate smallvec;
use smallvec::*;
use std::iter::repeat;
// Constants! :D
const ENDSL: &[u8] = b"| ";
const ENDSR: &[u8] = b" |\n";
#[cfg(not(feature = "clippy"))]
const FERRIS: &[u8] = br#"
\
\
_~^~^~_
\) / o o \ (/
'_ - _'
/ '-----' \
"#;
#[cfg(feature = "clippy")]
const CLIPPY: &[u8] = br#"
\
\
__
/ \
| |
@ @
| |
|| |/
|| ||
|\_/|
\___/
"#;
const NEWLINE: u8 = '\n' as u8;
const SPACE: u8 = ' ' as u8;
const DASH: u8 = '-' as u8;
// A decent number for SmallVec's Buffer Size, not too large
// but also big enough for most inputs
const BUFSIZE: usize = 2048;
// We need a value to add to the width which includes
// the length of ENDSL and ENDSR for the proper size
// calculation of the bar at the top and bottom of the
// box
const OFFSET: usize = 4;
pub fn say(input: &[u8], width: usize) -> Result<(String)> {
// Final output is stored here
let mut write_buffer = SmallVec::<[u8; BUFSIZE]>::new();
// The top and bottom bar for the text box is calculated once here
let bar_buffer: Vec<u8> = repeat(DASH).take(width + OFFSET).collect();
write_buffer.extend_from_slice(&bar_buffer);
write_buffer.push(NEWLINE);
for i in input.split(|x| *x == '\n' as u8) {
for j in i.chunks(width) {
write_buffer.extend_from_slice(ENDSL);
write_buffer.extend_from_slice(j);
for _ in 0..width - j.len() {
write_buffer.push(SPACE);
}
write_buffer.extend_from_slice(ENDSR);
}
}
write_buffer.extend_from_slice(&bar_buffer);
#[cfg(feature = "clippy")]
write_buffer.extend_from_slice(CLIPPY);
#[cfg(not(feature = "clippy"))]
write_buffer.extend_from_slice(FERRIS);
Ok(write_buffer)
}
|
#![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 AudioEncodingProperties(pub ::windows::core::IInspectable);
impl AudioEncodingProperties {
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<AudioEncodingProperties, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn SetBitrate(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Bitrate(&self) -> ::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), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SetChannelCount(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn ChannelCount(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SetSampleRate(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn SampleRate(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SetBitsPerSample(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn BitsPerSample(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SetFormatUserData(&self, value: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IAudioEncodingPropertiesWithFormatUserData>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.len() as u32, ::core::mem::transmute(value.as_ptr())).ok() }
}
pub fn GetFormatUserData(&self, value: &mut ::windows::core::Array<u8>) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IAudioEncodingPropertiesWithFormatUserData>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.set_abi_len(), value as *mut _ as _).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<MediaPropertySet> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(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::<MediaPropertySet>(result__)
}
}
pub fn Type(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(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 SetSubtype<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(self)?;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Subtype(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn CreateAac(samplerate: u32, channelcount: u32, bitrate: u32) -> ::windows::core::Result<AudioEncodingProperties> {
Self::IAudioEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), samplerate, channelcount, bitrate, &mut result__).from_abi::<AudioEncodingProperties>(result__)
})
}
pub fn CreateAacAdts(samplerate: u32, channelcount: u32, bitrate: u32) -> ::windows::core::Result<AudioEncodingProperties> {
Self::IAudioEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), samplerate, channelcount, bitrate, &mut result__).from_abi::<AudioEncodingProperties>(result__)
})
}
pub fn CreateMp3(samplerate: u32, channelcount: u32, bitrate: u32) -> ::windows::core::Result<AudioEncodingProperties> {
Self::IAudioEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), samplerate, channelcount, bitrate, &mut result__).from_abi::<AudioEncodingProperties>(result__)
})
}
pub fn CreatePcm(samplerate: u32, channelcount: u32, bitspersample: u32) -> ::windows::core::Result<AudioEncodingProperties> {
Self::IAudioEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), samplerate, channelcount, bitspersample, &mut result__).from_abi::<AudioEncodingProperties>(result__)
})
}
pub fn CreateWma(samplerate: u32, channelcount: u32, bitrate: u32) -> ::windows::core::Result<AudioEncodingProperties> {
Self::IAudioEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), samplerate, channelcount, bitrate, &mut result__).from_abi::<AudioEncodingProperties>(result__)
})
}
pub fn IsSpatial(&self) -> ::windows::core::Result<bool> {
let this = &::windows::core::Interface::cast::<IAudioEncodingProperties2>(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 CreateAlac(samplerate: u32, channelcount: u32, bitspersample: u32) -> ::windows::core::Result<AudioEncodingProperties> {
Self::IAudioEncodingPropertiesStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), samplerate, channelcount, bitspersample, &mut result__).from_abi::<AudioEncodingProperties>(result__)
})
}
pub fn CreateFlac(samplerate: u32, channelcount: u32, bitspersample: u32) -> ::windows::core::Result<AudioEncodingProperties> {
Self::IAudioEncodingPropertiesStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), samplerate, channelcount, bitspersample, &mut result__).from_abi::<AudioEncodingProperties>(result__)
})
}
pub fn Copy(&self) -> ::windows::core::Result<AudioEncodingProperties> {
let this = &::windows::core::Interface::cast::<IAudioEncodingProperties3>(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::<AudioEncodingProperties>(result__)
}
}
pub fn IAudioEncodingPropertiesStatics<R, F: FnOnce(&IAudioEncodingPropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AudioEncodingProperties, IAudioEncodingPropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IAudioEncodingPropertiesStatics2<R, F: FnOnce(&IAudioEncodingPropertiesStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<AudioEncodingProperties, IAudioEncodingPropertiesStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for AudioEncodingProperties {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.MediaProperties.AudioEncodingProperties;{62bc7a16-005c-4b3b-8a0b-0a090e9687f3})");
}
unsafe impl ::windows::core::Interface for AudioEncodingProperties {
type Vtable = IAudioEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x62bc7a16_005c_4b3b_8a0b_0a090e9687f3);
}
impl ::windows::core::RuntimeName for AudioEncodingProperties {
const NAME: &'static str = "Windows.Media.MediaProperties.AudioEncodingProperties";
}
impl ::core::convert::From<AudioEncodingProperties> for ::windows::core::IUnknown {
fn from(value: AudioEncodingProperties) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AudioEncodingProperties> for ::windows::core::IUnknown {
fn from(value: &AudioEncodingProperties) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AudioEncodingProperties {
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 AudioEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AudioEncodingProperties> for ::windows::core::IInspectable {
fn from(value: AudioEncodingProperties) -> Self {
value.0
}
}
impl ::core::convert::From<&AudioEncodingProperties> for ::windows::core::IInspectable {
fn from(value: &AudioEncodingProperties) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AudioEncodingProperties {
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 AudioEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<AudioEncodingProperties> for IMediaEncodingProperties {
type Error = ::windows::core::Error;
fn try_from(value: AudioEncodingProperties) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&AudioEncodingProperties> for IMediaEncodingProperties {
type Error = ::windows::core::Error;
fn try_from(value: &AudioEncodingProperties) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for AudioEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for &AudioEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::core::convert::TryInto::<IMediaEncodingProperties>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for AudioEncodingProperties {}
unsafe impl ::core::marker::Sync for AudioEncodingProperties {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct AudioEncodingQuality(pub i32);
impl AudioEncodingQuality {
pub const Auto: AudioEncodingQuality = AudioEncodingQuality(0i32);
pub const High: AudioEncodingQuality = AudioEncodingQuality(1i32);
pub const Medium: AudioEncodingQuality = AudioEncodingQuality(2i32);
pub const Low: AudioEncodingQuality = AudioEncodingQuality(3i32);
}
impl ::core::convert::From<i32> for AudioEncodingQuality {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for AudioEncodingQuality {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for AudioEncodingQuality {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.MediaProperties.AudioEncodingQuality;i4)");
}
impl ::windows::core::DefaultType for AudioEncodingQuality {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ContainerEncodingProperties(pub ::windows::core::IInspectable);
impl ContainerEncodingProperties {
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<ContainerEncodingProperties, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<MediaPropertySet> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(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::<MediaPropertySet>(result__)
}
}
pub fn Type(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(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 SetSubtype<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(self)?;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Subtype(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Copy(&self) -> ::windows::core::Result<ContainerEncodingProperties> {
let this = &::windows::core::Interface::cast::<IContainerEncodingProperties2>(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::<ContainerEncodingProperties>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for ContainerEncodingProperties {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.MediaProperties.ContainerEncodingProperties;{59ac2a57-b32a-479e-8a61-4b7f2e9e7ea0})");
}
unsafe impl ::windows::core::Interface for ContainerEncodingProperties {
type Vtable = IContainerEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x59ac2a57_b32a_479e_8a61_4b7f2e9e7ea0);
}
impl ::windows::core::RuntimeName for ContainerEncodingProperties {
const NAME: &'static str = "Windows.Media.MediaProperties.ContainerEncodingProperties";
}
impl ::core::convert::From<ContainerEncodingProperties> for ::windows::core::IUnknown {
fn from(value: ContainerEncodingProperties) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ContainerEncodingProperties> for ::windows::core::IUnknown {
fn from(value: &ContainerEncodingProperties) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ContainerEncodingProperties {
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 ContainerEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ContainerEncodingProperties> for ::windows::core::IInspectable {
fn from(value: ContainerEncodingProperties) -> Self {
value.0
}
}
impl ::core::convert::From<&ContainerEncodingProperties> for ::windows::core::IInspectable {
fn from(value: &ContainerEncodingProperties) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ContainerEncodingProperties {
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 ContainerEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<ContainerEncodingProperties> for IMediaEncodingProperties {
type Error = ::windows::core::Error;
fn try_from(value: ContainerEncodingProperties) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&ContainerEncodingProperties> for IMediaEncodingProperties {
type Error = ::windows::core::Error;
fn try_from(value: &ContainerEncodingProperties) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for ContainerEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for &ContainerEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::core::convert::TryInto::<IMediaEncodingProperties>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for ContainerEncodingProperties {}
unsafe impl ::core::marker::Sync for ContainerEncodingProperties {}
pub struct H264ProfileIds {}
impl H264ProfileIds {
pub fn ConstrainedBaseline() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| 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 Baseline() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn Extended() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| 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 Main() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn High() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| 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 High10() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn High422() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn High444() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn StereoHigh() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn MultiviewHigh() -> ::windows::core::Result<i32> {
Self::IH264ProfileIdsStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn IH264ProfileIdsStatics<R, F: FnOnce(&IH264ProfileIdsStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<H264ProfileIds, IH264ProfileIdsStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for H264ProfileIds {
const NAME: &'static str = "Windows.Media.MediaProperties.H264ProfileIds";
}
#[repr(transparent)]
#[doc(hidden)]
pub struct IAudioEncodingProperties(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAudioEncodingProperties {
type Vtable = IAudioEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x62bc7a16_005c_4b3b_8a0b_0a090e9687f3);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEncodingProperties_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: u32) -> ::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,
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,
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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAudioEncodingProperties2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAudioEncodingProperties2 {
type Vtable = IAudioEncodingProperties2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc45d54da_80bd_4c23_80d5_72d4a181e894);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEncodingProperties2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAudioEncodingProperties3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAudioEncodingProperties3 {
type Vtable = IAudioEncodingProperties3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x87600341_748c_4f8d_b0fd_10caf08ff087);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEncodingProperties3_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAudioEncodingPropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAudioEncodingPropertiesStatics {
type Vtable = IAudioEncodingPropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x0cad332c_ebe9_4527_b36d_e42a13cf38db);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEncodingPropertiesStatics_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, samplerate: u32, channelcount: u32, bitrate: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, samplerate: u32, channelcount: u32, bitrate: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, samplerate: u32, channelcount: u32, bitrate: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, samplerate: u32, channelcount: u32, bitspersample: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, samplerate: u32, channelcount: u32, bitrate: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAudioEncodingPropertiesStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAudioEncodingPropertiesStatics2 {
type Vtable = IAudioEncodingPropertiesStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7489316f_77a0_433d_8ed5_4040280e8665);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEncodingPropertiesStatics2_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, samplerate: u32, channelcount: u32, bitspersample: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, samplerate: u32, channelcount: u32, bitspersample: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAudioEncodingPropertiesWithFormatUserData(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAudioEncodingPropertiesWithFormatUserData {
type Vtable = IAudioEncodingPropertiesWithFormatUserData_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x98f10d79_13ea_49ff_be70_2673db69702c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAudioEncodingPropertiesWithFormatUserData_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_array_size: u32, value: *const u8) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value_array_size: *mut u32, value: *mut *mut u8) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IContainerEncodingProperties(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IContainerEncodingProperties {
type Vtable = IContainerEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x59ac2a57_b32a_479e_8a61_4b7f2e9e7ea0);
}
#[repr(C)]
#[doc(hidden)]
pub struct IContainerEncodingProperties_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IContainerEncodingProperties2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IContainerEncodingProperties2 {
type Vtable = IContainerEncodingProperties2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb272c029_ae26_4819_baad_ad7a49b0a876);
}
#[repr(C)]
#[doc(hidden)]
pub struct IContainerEncodingProperties2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IH264ProfileIdsStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IH264ProfileIdsStatics {
type Vtable = IH264ProfileIdsStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x38654ca7_846a_4f97_a2e5_c3a15bbf70fd);
}
#[repr(C)]
#[doc(hidden)]
pub struct IH264ProfileIdsStatics_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, result__: *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, result__: *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, result__: *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, result__: *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, result__: *mut i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IImageEncodingProperties(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IImageEncodingProperties {
type Vtable = IImageEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x78625635_f331_4189_b1c3_b48d5ae034f1);
}
#[repr(C)]
#[doc(hidden)]
pub struct IImageEncodingProperties_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: u32) -> ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IImageEncodingProperties2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IImageEncodingProperties2 {
type Vtable = IImageEncodingProperties2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xc854a2df_c923_469b_ac8e_6a9f3c1cd9e3);
}
#[repr(C)]
#[doc(hidden)]
pub struct IImageEncodingProperties2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IImageEncodingPropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IImageEncodingPropertiesStatics {
type Vtable = IImageEncodingPropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x257c68dc_8b99_439e_aa59_913a36161297);
}
#[repr(C)]
#[doc(hidden)]
pub struct IImageEncodingPropertiesStatics_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, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IImageEncodingPropertiesStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IImageEncodingPropertiesStatics2 {
type Vtable = IImageEncodingPropertiesStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf6c25b29_3824_46b0_956e_501329e1be3c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IImageEncodingPropertiesStatics2_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, format: MediaPixelFormat, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IImageEncodingPropertiesStatics3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IImageEncodingPropertiesStatics3 {
type Vtable = IImageEncodingPropertiesStatics3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x48f4814d_a2ff_48dc_8ea0_e90680663656);
}
#[repr(C)]
#[doc(hidden)]
pub struct IImageEncodingPropertiesStatics3_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingProfile(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingProfile {
type Vtable = IMediaEncodingProfile_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe7dbf5a8_1db9_4783_876b_3dfe12acfdb3);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingProfile_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: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingProfile2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingProfile2 {
type Vtable = IMediaEncodingProfile2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x349b3e0a_4035_488e_9877_85632865ed10);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingProfile2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Media_Core")))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Media_Core")))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Media_Core")))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Media_Core")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingProfile3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingProfile3 {
type Vtable = IMediaEncodingProfile3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xba6ebe88_7570_4e69_accf_5611ad015f88);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingProfile3_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Media_Core")))] usize,
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation_Collections", feature = "Media_Core")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingProfileStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingProfileStatics {
type Vtable = IMediaEncodingProfileStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x197f352c_2ede_4a45_a896_817a4854f8fe);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingProfileStatics_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, quality: AudioEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, quality: AudioEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, quality: AudioEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, quality: VideoEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, quality: VideoEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(all(feature = "Foundation", feature = "Storage"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, file: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage")))] usize,
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, stream: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(all(feature = "Foundation", feature = "Storage_Streams")))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingProfileStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingProfileStatics2 {
type Vtable = IMediaEncodingProfileStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xce8de74f_6af4_4288_8fe2_79adf1f79a43);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingProfileStatics2_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, quality: AudioEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, quality: VideoEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingProfileStatics3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingProfileStatics3 {
type Vtable = IMediaEncodingProfileStatics3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x90dac5aa_cf76_4294_a9ed_1a1420f51f6b);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingProfileStatics3_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, quality: AudioEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, quality: AudioEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, quality: VideoEncodingQuality, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IMediaEncodingProperties(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingProperties {
type Vtable = IMediaEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb4002af6_acd4_4e5a_a24b_5d7498a8b8c4);
}
impl IMediaEncodingProperties {
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<MediaPropertySet> {
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::<MediaPropertySet>(result__)
}
}
pub fn Type(&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 SetSubtype<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Subtype(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for IMediaEncodingProperties {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{b4002af6-acd4-4e5a-a24b-5d7498a8b8c4}");
}
impl ::core::convert::From<IMediaEncodingProperties> for ::windows::core::IUnknown {
fn from(value: IMediaEncodingProperties) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&IMediaEncodingProperties> for ::windows::core::IUnknown {
fn from(value: &IMediaEncodingProperties) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IMediaEncodingProperties {
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 IMediaEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<IMediaEncodingProperties> for ::windows::core::IInspectable {
fn from(value: IMediaEncodingProperties) -> Self {
value.0
}
}
impl ::core::convert::From<&IMediaEncodingProperties> for ::windows::core::IInspectable {
fn from(value: &IMediaEncodingProperties) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IMediaEncodingProperties {
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 IMediaEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingProperties_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, 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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingSubtypesStatics {
type Vtable = IMediaEncodingSubtypesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x37b6580e_a171_4464_ba5a_53189e48c1c8);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingSubtypesStatics2 {
type Vtable = IMediaEncodingSubtypesStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4b7cd23d_42ff_4d33_8531_0626bee4b52d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingSubtypesStatics3 {
type Vtable = IMediaEncodingSubtypesStatics3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xba2414e4_883d_464e_a44f_097da08ef7ff);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics3_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics4(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingSubtypesStatics4 {
type Vtable = IMediaEncodingSubtypesStatics4_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xddece58a_3949_4644_8a2c_59ef02c642fa);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics4_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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics5(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingSubtypesStatics5 {
type Vtable = IMediaEncodingSubtypesStatics5_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5ad4a007_ffce_4760_9828_5d0c99637e6a);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics5_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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics6(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaEncodingSubtypesStatics6 {
type Vtable = IMediaEncodingSubtypesStatics6_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa1252973_a984_5912_93bb_54e7e569e053);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaEncodingSubtypesStatics6_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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)]
#[doc(hidden)]
pub struct IMediaRatio(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMediaRatio {
type Vtable = IMediaRatio_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd2d0fee5_8929_401d_ac78_7d357e378163);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMediaRatio_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: u32) -> ::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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IMpeg2ProfileIdsStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IMpeg2ProfileIdsStatics {
type Vtable = IMpeg2ProfileIdsStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa461ff85_e57a_4128_9b21_d5331b04235c);
}
#[repr(C)]
#[doc(hidden)]
pub struct IMpeg2ProfileIdsStatics_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, result__: *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, result__: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut i32) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ITimedMetadataEncodingProperties(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITimedMetadataEncodingProperties {
type Vtable = ITimedMetadataEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x51cd30d3_d690_4cfa_97f4_4a398e9db420);
}
#[repr(C)]
#[doc(hidden)]
pub struct ITimedMetadataEncodingProperties_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_array_size: u32, value: *const u8) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value_array_size: *mut u32, value: *mut *mut u8) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct ITimedMetadataEncodingPropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for ITimedMetadataEncodingPropertiesStatics {
type Vtable = ITimedMetadataEncodingPropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x6629bb67_6e55_5643_89a0_7a7e8d85b52c);
}
#[repr(C)]
#[doc(hidden)]
pub struct ITimedMetadataEncodingPropertiesStatics_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, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, formatUserData_array_size: u32, formatuserdata: *const u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, formatUserData_array_size: u32, formatuserdata: *const u8, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVideoEncodingProperties(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVideoEncodingProperties {
type Vtable = IVideoEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x76ee6c9a_37c2_4f2a_880a_1282bbb4373d);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVideoEncodingProperties_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: u32) -> ::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,
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,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut u32) -> ::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, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVideoEncodingProperties2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVideoEncodingProperties2 {
type Vtable = IVideoEncodingProperties2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf743a1ef_d465_4290_a94b_ef0f1528f8e3);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVideoEncodingProperties2_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_array_size: u32, value: *const u8) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value_array_size: *mut u32, value: *mut *mut u8) -> ::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,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVideoEncodingProperties3(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVideoEncodingProperties3 {
type Vtable = IVideoEncodingProperties3_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x386bcdc4_873a_479f_b3eb_56c1fcbec6d7);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVideoEncodingProperties3_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 StereoscopicVideoPackingMode) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVideoEncodingProperties4(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVideoEncodingProperties4 {
type Vtable = IVideoEncodingProperties4_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x724ef014_c10c_40f2_9d72_3ee13b45fa8e);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVideoEncodingProperties4_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 SphericalVideoFrameFormat) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVideoEncodingProperties5(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVideoEncodingProperties5 {
type Vtable = IVideoEncodingProperties5_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4959080f_272f_4ece_a4df_c0ccdb33d840);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVideoEncodingProperties5_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVideoEncodingPropertiesStatics(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVideoEncodingPropertiesStatics {
type Vtable = IVideoEncodingPropertiesStatics_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3ce14d44_1dc5_43db_9f38_ebebf90152cb);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVideoEncodingPropertiesStatics_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, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, subtype: ::core::mem::ManuallyDrop<::windows::core::HSTRING>, width: u32, height: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IVideoEncodingPropertiesStatics2(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IVideoEncodingPropertiesStatics2 {
type Vtable = IVideoEncodingPropertiesStatics2_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcf1ebd5d_49fe_4d00_b59a_cfa4dfc51944);
}
#[repr(C)]
#[doc(hidden)]
pub struct IVideoEncodingPropertiesStatics2_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct ImageEncodingProperties(pub ::windows::core::IInspectable);
impl ImageEncodingProperties {
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<ImageEncodingProperties, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn SetWidth(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Width(&self) -> ::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), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SetHeight(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Height(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<MediaPropertySet> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(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::<MediaPropertySet>(result__)
}
}
pub fn Type(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(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 SetSubtype<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(self)?;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Subtype(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn CreateJpeg() -> ::windows::core::Result<ImageEncodingProperties> {
Self::IImageEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageEncodingProperties>(result__)
})
}
pub fn CreatePng() -> ::windows::core::Result<ImageEncodingProperties> {
Self::IImageEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageEncodingProperties>(result__)
})
}
pub fn CreateJpegXR() -> ::windows::core::Result<ImageEncodingProperties> {
Self::IImageEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageEncodingProperties>(result__)
})
}
pub fn CreateUncompressed(format: MediaPixelFormat) -> ::windows::core::Result<ImageEncodingProperties> {
Self::IImageEncodingPropertiesStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), format, &mut result__).from_abi::<ImageEncodingProperties>(result__)
})
}
pub fn CreateBmp() -> ::windows::core::Result<ImageEncodingProperties> {
Self::IImageEncodingPropertiesStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageEncodingProperties>(result__)
})
}
pub fn Copy(&self) -> ::windows::core::Result<ImageEncodingProperties> {
let this = &::windows::core::Interface::cast::<IImageEncodingProperties2>(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::<ImageEncodingProperties>(result__)
}
}
pub fn CreateHeif() -> ::windows::core::Result<ImageEncodingProperties> {
Self::IImageEncodingPropertiesStatics3(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ImageEncodingProperties>(result__)
})
}
pub fn IImageEncodingPropertiesStatics<R, F: FnOnce(&IImageEncodingPropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<ImageEncodingProperties, IImageEncodingPropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IImageEncodingPropertiesStatics2<R, F: FnOnce(&IImageEncodingPropertiesStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<ImageEncodingProperties, IImageEncodingPropertiesStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IImageEncodingPropertiesStatics3<R, F: FnOnce(&IImageEncodingPropertiesStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<ImageEncodingProperties, IImageEncodingPropertiesStatics3> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for ImageEncodingProperties {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.MediaProperties.ImageEncodingProperties;{78625635-f331-4189-b1c3-b48d5ae034f1})");
}
unsafe impl ::windows::core::Interface for ImageEncodingProperties {
type Vtable = IImageEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x78625635_f331_4189_b1c3_b48d5ae034f1);
}
impl ::windows::core::RuntimeName for ImageEncodingProperties {
const NAME: &'static str = "Windows.Media.MediaProperties.ImageEncodingProperties";
}
impl ::core::convert::From<ImageEncodingProperties> for ::windows::core::IUnknown {
fn from(value: ImageEncodingProperties) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&ImageEncodingProperties> for ::windows::core::IUnknown {
fn from(value: &ImageEncodingProperties) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for ImageEncodingProperties {
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 ImageEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<ImageEncodingProperties> for ::windows::core::IInspectable {
fn from(value: ImageEncodingProperties) -> Self {
value.0
}
}
impl ::core::convert::From<&ImageEncodingProperties> for ::windows::core::IInspectable {
fn from(value: &ImageEncodingProperties) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for ImageEncodingProperties {
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 ImageEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<ImageEncodingProperties> for IMediaEncodingProperties {
type Error = ::windows::core::Error;
fn try_from(value: ImageEncodingProperties) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&ImageEncodingProperties> for IMediaEncodingProperties {
type Error = ::windows::core::Error;
fn try_from(value: &ImageEncodingProperties) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for ImageEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for &ImageEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::core::convert::TryInto::<IMediaEncodingProperties>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for ImageEncodingProperties {}
unsafe impl ::core::marker::Sync for ImageEncodingProperties {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct MediaEncodingProfile(pub ::windows::core::IInspectable);
impl MediaEncodingProfile {
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<MediaEncodingProfile, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn SetAudio<'a, Param0: ::windows::core::IntoParam<'a, AudioEncodingProperties>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Audio(&self) -> ::windows::core::Result<AudioEncodingProperties> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AudioEncodingProperties>(result__)
}
}
pub fn SetVideo<'a, Param0: ::windows::core::IntoParam<'a, VideoEncodingProperties>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Video(&self) -> ::windows::core::Result<VideoEncodingProperties> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<VideoEncodingProperties>(result__)
}
}
pub fn SetContainer<'a, Param0: ::windows::core::IntoParam<'a, ContainerEncodingProperties>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Container(&self) -> ::windows::core::Result<ContainerEncodingProperties> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<ContainerEncodingProperties>(result__)
}
}
pub fn CreateM4a(quality: AudioEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
pub fn CreateMp3(quality: AudioEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
pub fn CreateWma(quality: AudioEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
pub fn CreateMp4(quality: VideoEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
pub fn CreateWmv(quality: VideoEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
#[cfg(all(feature = "Foundation", feature = "Storage"))]
pub fn CreateFromFileAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::IStorageFile>>(file: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MediaEncodingProfile>> {
Self::IMediaEncodingProfileStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), file.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MediaEncodingProfile>>(result__)
})
}
#[cfg(all(feature = "Foundation", feature = "Storage_Streams"))]
pub fn CreateFromStreamAsync<'a, Param0: ::windows::core::IntoParam<'a, super::super::Storage::Streams::IRandomAccessStream>>(stream: Param0) -> ::windows::core::Result<super::super::Foundation::IAsyncOperation<MediaEncodingProfile>> {
Self::IMediaEncodingProfileStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), stream.into_param().abi(), &mut result__).from_abi::<super::super::Foundation::IAsyncOperation<MediaEncodingProfile>>(result__)
})
}
pub fn CreateWav(quality: AudioEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
pub fn CreateAvi(quality: VideoEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
pub fn CreateAlac(quality: AudioEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics3(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
pub fn CreateFlac(quality: AudioEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics3(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
pub fn CreateHevc(quality: VideoEncodingQuality) -> ::windows::core::Result<MediaEncodingProfile> {
Self::IMediaEncodingProfileStatics3(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), quality, &mut result__).from_abi::<MediaEncodingProfile>(result__)
})
}
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))]
pub fn SetAudioTracks<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::Core::AudioStreamDescriptor>>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProfile2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))]
pub fn GetAudioTracks(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<super::Core::AudioStreamDescriptor>> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProfile2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<super::Core::AudioStreamDescriptor>>(result__)
}
}
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))]
pub fn SetVideoTracks<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::Core::VideoStreamDescriptor>>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProfile2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))]
pub fn GetVideoTracks(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<super::Core::VideoStreamDescriptor>> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProfile2>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<super::Core::VideoStreamDescriptor>>(result__)
}
}
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))]
pub fn SetTimedMetadataTracks<'a, Param0: ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::Core::TimedMetadataStreamDescriptor>>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProfile3>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
#[cfg(all(feature = "Foundation_Collections", feature = "Media_Core"))]
pub fn GetTimedMetadataTracks(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IVector<super::Core::TimedMetadataStreamDescriptor>> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProfile3>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IVector<super::Core::TimedMetadataStreamDescriptor>>(result__)
}
}
pub fn IMediaEncodingProfileStatics<R, F: FnOnce(&IMediaEncodingProfileStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MediaEncodingProfile, IMediaEncodingProfileStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IMediaEncodingProfileStatics2<R, F: FnOnce(&IMediaEncodingProfileStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MediaEncodingProfile, IMediaEncodingProfileStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IMediaEncodingProfileStatics3<R, F: FnOnce(&IMediaEncodingProfileStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MediaEncodingProfile, IMediaEncodingProfileStatics3> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for MediaEncodingProfile {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.MediaProperties.MediaEncodingProfile;{e7dbf5a8-1db9-4783-876b-3dfe12acfdb3})");
}
unsafe impl ::windows::core::Interface for MediaEncodingProfile {
type Vtable = IMediaEncodingProfile_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xe7dbf5a8_1db9_4783_876b_3dfe12acfdb3);
}
impl ::windows::core::RuntimeName for MediaEncodingProfile {
const NAME: &'static str = "Windows.Media.MediaProperties.MediaEncodingProfile";
}
impl ::core::convert::From<MediaEncodingProfile> for ::windows::core::IUnknown {
fn from(value: MediaEncodingProfile) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&MediaEncodingProfile> for ::windows::core::IUnknown {
fn from(value: &MediaEncodingProfile) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MediaEncodingProfile {
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 MediaEncodingProfile {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<MediaEncodingProfile> for ::windows::core::IInspectable {
fn from(value: MediaEncodingProfile) -> Self {
value.0
}
}
impl ::core::convert::From<&MediaEncodingProfile> for ::windows::core::IInspectable {
fn from(value: &MediaEncodingProfile) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MediaEncodingProfile {
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 MediaEncodingProfile {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for MediaEncodingProfile {}
unsafe impl ::core::marker::Sync for MediaEncodingProfile {}
pub struct MediaEncodingSubtypes {}
impl MediaEncodingSubtypes {
pub fn Aac() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn AacAdts() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| 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 Ac3() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| 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 AmrNb() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn AmrWb() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Argb32() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Asf() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Avi() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Bgra8() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Bmp() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Eac3() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| 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 Float() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Gif() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| 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 H263() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| 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__)
})
}
pub fn H264() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn H264Es() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Hevc() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn HevcEs() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Iyuv() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Jpeg() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn JpegXr() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mjpg() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mpeg() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mpeg1() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mpeg2() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mp3() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Mpeg4() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Nv12() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).33)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Pcm() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Png() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).35)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Rgb24() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).36)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Rgb32() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).37)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Tiff() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).38)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Wave() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).39)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Wma8() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).40)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Wma9() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).41)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Wmv3() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).42)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Wvc1() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).43)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Yuy2() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).44)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Yv12() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).45)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Vp9() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn L8() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics2(|this| 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 L16() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics2(|this| 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 D16() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics2(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Alac() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics3(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Flac() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics3(|this| 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 P010() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics4(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Heif() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics5(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Pgs() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics6(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn Srt() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics6(|this| 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 Ssa() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics6(|this| 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 VobSub() -> ::windows::core::Result<::windows::core::HSTRING> {
Self::IMediaEncodingSubtypesStatics6(|this| unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
})
}
pub fn IMediaEncodingSubtypesStatics<R, F: FnOnce(&IMediaEncodingSubtypesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MediaEncodingSubtypes, IMediaEncodingSubtypesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IMediaEncodingSubtypesStatics2<R, F: FnOnce(&IMediaEncodingSubtypesStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MediaEncodingSubtypes, IMediaEncodingSubtypesStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IMediaEncodingSubtypesStatics3<R, F: FnOnce(&IMediaEncodingSubtypesStatics3) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MediaEncodingSubtypes, IMediaEncodingSubtypesStatics3> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IMediaEncodingSubtypesStatics4<R, F: FnOnce(&IMediaEncodingSubtypesStatics4) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MediaEncodingSubtypes, IMediaEncodingSubtypesStatics4> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IMediaEncodingSubtypesStatics5<R, F: FnOnce(&IMediaEncodingSubtypesStatics5) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MediaEncodingSubtypes, IMediaEncodingSubtypesStatics5> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IMediaEncodingSubtypesStatics6<R, F: FnOnce(&IMediaEncodingSubtypesStatics6) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<MediaEncodingSubtypes, IMediaEncodingSubtypesStatics6> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for MediaEncodingSubtypes {
const NAME: &'static str = "Windows.Media.MediaProperties.MediaEncodingSubtypes";
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct MediaMirroringOptions(pub u32);
impl MediaMirroringOptions {
pub const None: MediaMirroringOptions = MediaMirroringOptions(0u32);
pub const Horizontal: MediaMirroringOptions = MediaMirroringOptions(1u32);
pub const Vertical: MediaMirroringOptions = MediaMirroringOptions(2u32);
}
impl ::core::convert::From<u32> for MediaMirroringOptions {
fn from(value: u32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for MediaMirroringOptions {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for MediaMirroringOptions {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.MediaProperties.MediaMirroringOptions;u4)");
}
impl ::windows::core::DefaultType for MediaMirroringOptions {
type DefaultType = Self;
}
impl ::core::ops::BitOr for MediaMirroringOptions {
type Output = Self;
fn bitor(self, rhs: Self) -> Self {
Self(self.0 | rhs.0)
}
}
impl ::core::ops::BitAnd for MediaMirroringOptions {
type Output = Self;
fn bitand(self, rhs: Self) -> Self {
Self(self.0 & rhs.0)
}
}
impl ::core::ops::BitOrAssign for MediaMirroringOptions {
fn bitor_assign(&mut self, rhs: Self) {
self.0.bitor_assign(rhs.0)
}
}
impl ::core::ops::BitAndAssign for MediaMirroringOptions {
fn bitand_assign(&mut self, rhs: Self) {
self.0.bitand_assign(rhs.0)
}
}
impl ::core::ops::Not for MediaMirroringOptions {
type Output = Self;
fn not(self) -> Self {
Self(self.0.not())
}
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct MediaPixelFormat(pub i32);
impl MediaPixelFormat {
pub const Nv12: MediaPixelFormat = MediaPixelFormat(0i32);
pub const Bgra8: MediaPixelFormat = MediaPixelFormat(1i32);
pub const P010: MediaPixelFormat = MediaPixelFormat(2i32);
}
impl ::core::convert::From<i32> for MediaPixelFormat {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for MediaPixelFormat {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for MediaPixelFormat {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.MediaProperties.MediaPixelFormat;i4)");
}
impl ::windows::core::DefaultType for MediaPixelFormat {
type DefaultType = Self;
}
#[cfg(feature = "Foundation_Collections")]
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct MediaPropertySet(pub ::windows::core::IInspectable);
#[cfg(feature = "Foundation_Collections")]
impl MediaPropertySet {
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<MediaPropertySet, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "Foundation_Collections")]
pub fn Lookup<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, key: Param0) -> ::windows::core::Result<::windows::core::IInspectable> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<::windows::core::IInspectable>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Size(&self) -> ::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), &mut result__).from_abi::<u32>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn HasKey<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, key: Param0) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), key.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn GetView(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IMapView<::windows::core::GUID, ::windows::core::IInspectable>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::Collections::IMapView<::windows::core::GUID, ::windows::core::IInspectable>>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Insert<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>, Param1: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, key: Param0, value: Param1) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), key.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Remove<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::GUID>>(&self, key: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), key.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn Clear(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this)).ok() }
}
#[cfg(feature = "Foundation_Collections")]
pub fn First(&self) -> ::windows::core::Result<super::super::Foundation::Collections::IIterator<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>>> {
let this = &::windows::core::Interface::cast::<super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>>>(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::IIterator<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>>>(result__)
}
}
}
#[cfg(feature = "Foundation_Collections")]
unsafe impl ::windows::core::RuntimeType for MediaPropertySet {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.MediaProperties.MediaPropertySet;pinterface({3c2925fe-8519-45c1-aa79-197b6718c1c1};g16;cinterface(IInspectable)))");
}
#[cfg(feature = "Foundation_Collections")]
unsafe impl ::windows::core::Interface for MediaPropertySet {
type Vtable = super::super::Foundation::Collections::IMap_abi<::windows::core::GUID, ::windows::core::IInspectable>;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_signature(<super::super::Foundation::Collections::IMap<::windows::core::GUID, ::windows::core::IInspectable> as ::windows::core::RuntimeType>::SIGNATURE);
}
#[cfg(feature = "Foundation_Collections")]
impl ::windows::core::RuntimeName for MediaPropertySet {
const NAME: &'static str = "Windows.Media.MediaProperties.MediaPropertySet";
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<MediaPropertySet> for ::windows::core::IUnknown {
fn from(value: MediaPropertySet) -> Self {
value.0 .0
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<&MediaPropertySet> for ::windows::core::IUnknown {
fn from(value: &MediaPropertySet) -> Self {
value.0 .0.clone()
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MediaPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0 .0)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a MediaPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<MediaPropertySet> for ::windows::core::IInspectable {
fn from(value: MediaPropertySet) -> Self {
value.0
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<&MediaPropertySet> for ::windows::core::IInspectable {
fn from(value: &MediaPropertySet) -> Self {
value.0.clone()
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MediaPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Owned(self.0)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for &'a MediaPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<MediaPropertySet> for super::super::Foundation::Collections::IMap<::windows::core::GUID, ::windows::core::IInspectable> {
fn from(value: MediaPropertySet) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::From<&MediaPropertySet> for super::super::Foundation::Collections::IMap<::windows::core::GUID, ::windows::core::IInspectable> {
fn from(value: &MediaPropertySet) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IMap<::windows::core::GUID, ::windows::core::IInspectable>> for MediaPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IMap<::windows::core::GUID, ::windows::core::IInspectable>> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IMap<::windows::core::GUID, ::windows::core::IInspectable>> for &MediaPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IMap<::windows::core::GUID, ::windows::core::IInspectable>> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::TryFrom<MediaPropertySet> for super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>> {
type Error = ::windows::core::Error;
fn try_from(value: MediaPropertySet) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
#[cfg(feature = "Foundation_Collections")]
impl ::core::convert::TryFrom<&MediaPropertySet> for super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>> {
type Error = ::windows::core::Error;
fn try_from(value: &MediaPropertySet) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>>> for MediaPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>>> {
::windows::core::IntoParam::into_param(&self)
}
}
#[cfg(feature = "Foundation_Collections")]
impl<'a> ::windows::core::IntoParam<'a, super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>>> for &MediaPropertySet {
fn into_param(self) -> ::windows::core::Param<'a, super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>>> {
::core::convert::TryInto::<super::super::Foundation::Collections::IIterable<super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>>>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
#[cfg(feature = "Foundation_Collections")]
unsafe impl ::core::marker::Send for MediaPropertySet {}
#[cfg(feature = "Foundation_Collections")]
unsafe impl ::core::marker::Sync for MediaPropertySet {}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for MediaPropertySet {
type Item = super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>;
type IntoIter = super::super::Foundation::Collections::IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
::core::iter::IntoIterator::into_iter(&self)
}
}
#[cfg(all(feature = "Foundation_Collections"))]
impl ::core::iter::IntoIterator for &MediaPropertySet {
type Item = super::super::Foundation::Collections::IKeyValuePair<::windows::core::GUID, ::windows::core::IInspectable>;
type IntoIter = super::super::Foundation::Collections::IIterator<Self::Item>;
fn into_iter(self) -> Self::IntoIter {
self.First().unwrap()
}
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct MediaRatio(pub ::windows::core::IInspectable);
impl MediaRatio {
pub fn SetNumerator(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Numerator(&self) -> ::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), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SetDenominator(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Denominator(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for MediaRatio {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.MediaProperties.MediaRatio;{d2d0fee5-8929-401d-ac78-7d357e378163})");
}
unsafe impl ::windows::core::Interface for MediaRatio {
type Vtable = IMediaRatio_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd2d0fee5_8929_401d_ac78_7d357e378163);
}
impl ::windows::core::RuntimeName for MediaRatio {
const NAME: &'static str = "Windows.Media.MediaProperties.MediaRatio";
}
impl ::core::convert::From<MediaRatio> for ::windows::core::IUnknown {
fn from(value: MediaRatio) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&MediaRatio> for ::windows::core::IUnknown {
fn from(value: &MediaRatio) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for MediaRatio {
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 MediaRatio {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<MediaRatio> for ::windows::core::IInspectable {
fn from(value: MediaRatio) -> Self {
value.0
}
}
impl ::core::convert::From<&MediaRatio> for ::windows::core::IInspectable {
fn from(value: &MediaRatio) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for MediaRatio {
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 MediaRatio {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for MediaRatio {}
unsafe impl ::core::marker::Sync for MediaRatio {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct MediaRotation(pub i32);
impl MediaRotation {
pub const None: MediaRotation = MediaRotation(0i32);
pub const Clockwise90Degrees: MediaRotation = MediaRotation(1i32);
pub const Clockwise180Degrees: MediaRotation = MediaRotation(2i32);
pub const Clockwise270Degrees: MediaRotation = MediaRotation(3i32);
}
impl ::core::convert::From<i32> for MediaRotation {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for MediaRotation {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for MediaRotation {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.MediaProperties.MediaRotation;i4)");
}
impl ::windows::core::DefaultType for MediaRotation {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct MediaThumbnailFormat(pub i32);
impl MediaThumbnailFormat {
pub const Bmp: MediaThumbnailFormat = MediaThumbnailFormat(0i32);
pub const Bgra8: MediaThumbnailFormat = MediaThumbnailFormat(1i32);
}
impl ::core::convert::From<i32> for MediaThumbnailFormat {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for MediaThumbnailFormat {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for MediaThumbnailFormat {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.MediaProperties.MediaThumbnailFormat;i4)");
}
impl ::windows::core::DefaultType for MediaThumbnailFormat {
type DefaultType = Self;
}
pub struct Mpeg2ProfileIds {}
impl Mpeg2ProfileIds {
pub fn Simple() -> ::windows::core::Result<i32> {
Self::IMpeg2ProfileIdsStatics(|this| 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 Main() -> ::windows::core::Result<i32> {
Self::IMpeg2ProfileIdsStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn SignalNoiseRatioScalable() -> ::windows::core::Result<i32> {
Self::IMpeg2ProfileIdsStatics(|this| 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 SpatiallyScalable() -> ::windows::core::Result<i32> {
Self::IMpeg2ProfileIdsStatics(|this| unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
})
}
pub fn High() -> ::windows::core::Result<i32> {
Self::IMpeg2ProfileIdsStatics(|this| 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 IMpeg2ProfileIdsStatics<R, F: FnOnce(&IMpeg2ProfileIdsStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<Mpeg2ProfileIds, IMpeg2ProfileIdsStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
impl ::windows::core::RuntimeName for Mpeg2ProfileIds {
const NAME: &'static str = "Windows.Media.MediaProperties.Mpeg2ProfileIds";
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SphericalVideoFrameFormat(pub i32);
impl SphericalVideoFrameFormat {
pub const None: SphericalVideoFrameFormat = SphericalVideoFrameFormat(0i32);
pub const Unsupported: SphericalVideoFrameFormat = SphericalVideoFrameFormat(1i32);
pub const Equirectangular: SphericalVideoFrameFormat = SphericalVideoFrameFormat(2i32);
}
impl ::core::convert::From<i32> for SphericalVideoFrameFormat {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SphericalVideoFrameFormat {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for SphericalVideoFrameFormat {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.MediaProperties.SphericalVideoFrameFormat;i4)");
}
impl ::windows::core::DefaultType for SphericalVideoFrameFormat {
type DefaultType = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct StereoscopicVideoPackingMode(pub i32);
impl StereoscopicVideoPackingMode {
pub const None: StereoscopicVideoPackingMode = StereoscopicVideoPackingMode(0i32);
pub const SideBySide: StereoscopicVideoPackingMode = StereoscopicVideoPackingMode(1i32);
pub const TopBottom: StereoscopicVideoPackingMode = StereoscopicVideoPackingMode(2i32);
}
impl ::core::convert::From<i32> for StereoscopicVideoPackingMode {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for StereoscopicVideoPackingMode {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for StereoscopicVideoPackingMode {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.MediaProperties.StereoscopicVideoPackingMode;i4)");
}
impl ::windows::core::DefaultType for StereoscopicVideoPackingMode {
type DefaultType = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct TimedMetadataEncodingProperties(pub ::windows::core::IInspectable);
impl TimedMetadataEncodingProperties {
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<TimedMetadataEncodingProperties, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<MediaPropertySet> {
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::<MediaPropertySet>(result__)
}
}
pub fn Type(&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 SetSubtype<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Subtype(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetFormatUserData(&self, value: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITimedMetadataEncodingProperties>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.len() as u32, ::core::mem::transmute(value.as_ptr())).ok() }
}
pub fn GetFormatUserData(&self, value: &mut ::windows::core::Array<u8>) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<ITimedMetadataEncodingProperties>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.set_abi_len(), value as *mut _ as _).ok() }
}
pub fn Copy(&self) -> ::windows::core::Result<TimedMetadataEncodingProperties> {
let this = &::windows::core::Interface::cast::<ITimedMetadataEncodingProperties>(self)?;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TimedMetadataEncodingProperties>(result__)
}
}
pub fn CreatePgs() -> ::windows::core::Result<TimedMetadataEncodingProperties> {
Self::ITimedMetadataEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TimedMetadataEncodingProperties>(result__)
})
}
pub fn CreateSrt() -> ::windows::core::Result<TimedMetadataEncodingProperties> {
Self::ITimedMetadataEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<TimedMetadataEncodingProperties>(result__)
})
}
pub fn CreateSsa(formatuserdata: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<TimedMetadataEncodingProperties> {
Self::ITimedMetadataEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), formatuserdata.len() as u32, ::core::mem::transmute(formatuserdata.as_ptr()), &mut result__).from_abi::<TimedMetadataEncodingProperties>(result__)
})
}
pub fn CreateVobSub(formatuserdata: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<TimedMetadataEncodingProperties> {
Self::ITimedMetadataEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), formatuserdata.len() as u32, ::core::mem::transmute(formatuserdata.as_ptr()), &mut result__).from_abi::<TimedMetadataEncodingProperties>(result__)
})
}
pub fn ITimedMetadataEncodingPropertiesStatics<R, F: FnOnce(&ITimedMetadataEncodingPropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<TimedMetadataEncodingProperties, ITimedMetadataEncodingPropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for TimedMetadataEncodingProperties {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.MediaProperties.TimedMetadataEncodingProperties;{b4002af6-acd4-4e5a-a24b-5d7498a8b8c4})");
}
unsafe impl ::windows::core::Interface for TimedMetadataEncodingProperties {
type Vtable = IMediaEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb4002af6_acd4_4e5a_a24b_5d7498a8b8c4);
}
impl ::windows::core::RuntimeName for TimedMetadataEncodingProperties {
const NAME: &'static str = "Windows.Media.MediaProperties.TimedMetadataEncodingProperties";
}
impl ::core::convert::From<TimedMetadataEncodingProperties> for ::windows::core::IUnknown {
fn from(value: TimedMetadataEncodingProperties) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&TimedMetadataEncodingProperties> for ::windows::core::IUnknown {
fn from(value: &TimedMetadataEncodingProperties) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for TimedMetadataEncodingProperties {
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 TimedMetadataEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<TimedMetadataEncodingProperties> for ::windows::core::IInspectable {
fn from(value: TimedMetadataEncodingProperties) -> Self {
value.0
}
}
impl ::core::convert::From<&TimedMetadataEncodingProperties> for ::windows::core::IInspectable {
fn from(value: &TimedMetadataEncodingProperties) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for TimedMetadataEncodingProperties {
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 TimedMetadataEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<TimedMetadataEncodingProperties> for IMediaEncodingProperties {
fn from(value: TimedMetadataEncodingProperties) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&TimedMetadataEncodingProperties> for IMediaEncodingProperties {
fn from(value: &TimedMetadataEncodingProperties) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for TimedMetadataEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for &TimedMetadataEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
unsafe impl ::core::marker::Send for TimedMetadataEncodingProperties {}
unsafe impl ::core::marker::Sync for TimedMetadataEncodingProperties {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct VideoEncodingProperties(pub ::windows::core::IInspectable);
impl VideoEncodingProperties {
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<VideoEncodingProperties, ::windows::core::IActivationFactory> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn SetBitrate(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Bitrate(&self) -> ::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), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SetWidth(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Width(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn SetHeight(&self, value: u32) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn Height(&self) -> ::windows::core::Result<u32> {
let this = self;
unsafe {
let mut result__: u32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<u32>(result__)
}
}
pub fn FrameRate(&self) -> ::windows::core::Result<MediaRatio> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MediaRatio>(result__)
}
}
pub fn PixelAspectRatio(&self) -> ::windows::core::Result<MediaRatio> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<MediaRatio>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Properties(&self) -> ::windows::core::Result<MediaPropertySet> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(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::<MediaPropertySet>(result__)
}
}
pub fn Type(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(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 SetSubtype<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, value: Param0) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(self)?;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value.into_param().abi()).ok() }
}
pub fn Subtype(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = &::windows::core::Interface::cast::<IMediaEncodingProperties>(self)?;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SetFormatUserData(&self, value: &[<u8 as ::windows::core::DefaultType>::DefaultType]) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVideoEncodingProperties2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), value.len() as u32, ::core::mem::transmute(value.as_ptr())).ok() }
}
pub fn GetFormatUserData(&self, value: &mut ::windows::core::Array<u8>) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVideoEncodingProperties2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), value.set_abi_len(), value as *mut _ as _).ok() }
}
pub fn SetProfileId(&self, value: i32) -> ::windows::core::Result<()> {
let this = &::windows::core::Interface::cast::<IVideoEncodingProperties2>(self)?;
unsafe { (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), value).ok() }
}
pub fn ProfileId(&self) -> ::windows::core::Result<i32> {
let this = &::windows::core::Interface::cast::<IVideoEncodingProperties2>(self)?;
unsafe {
let mut result__: i32 = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<i32>(result__)
}
}
pub fn CreateH264() -> ::windows::core::Result<VideoEncodingProperties> {
Self::IVideoEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<VideoEncodingProperties>(result__)
})
}
pub fn CreateMpeg2() -> ::windows::core::Result<VideoEncodingProperties> {
Self::IVideoEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<VideoEncodingProperties>(result__)
})
}
pub fn CreateUncompressed<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(subtype: Param0, width: u32, height: u32) -> ::windows::core::Result<VideoEncodingProperties> {
Self::IVideoEncodingPropertiesStatics(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), subtype.into_param().abi(), width, height, &mut result__).from_abi::<VideoEncodingProperties>(result__)
})
}
pub fn StereoscopicVideoPackingMode(&self) -> ::windows::core::Result<StereoscopicVideoPackingMode> {
let this = &::windows::core::Interface::cast::<IVideoEncodingProperties3>(self)?;
unsafe {
let mut result__: StereoscopicVideoPackingMode = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<StereoscopicVideoPackingMode>(result__)
}
}
pub fn SphericalVideoFrameFormat(&self) -> ::windows::core::Result<SphericalVideoFrameFormat> {
let this = &::windows::core::Interface::cast::<IVideoEncodingProperties4>(self)?;
unsafe {
let mut result__: SphericalVideoFrameFormat = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<SphericalVideoFrameFormat>(result__)
}
}
pub fn CreateHevc() -> ::windows::core::Result<VideoEncodingProperties> {
Self::IVideoEncodingPropertiesStatics2(|this| unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<VideoEncodingProperties>(result__)
})
}
pub fn Copy(&self) -> ::windows::core::Result<VideoEncodingProperties> {
let this = &::windows::core::Interface::cast::<IVideoEncodingProperties5>(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::<VideoEncodingProperties>(result__)
}
}
pub fn IVideoEncodingPropertiesStatics<R, F: FnOnce(&IVideoEncodingPropertiesStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<VideoEncodingProperties, IVideoEncodingPropertiesStatics> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
pub fn IVideoEncodingPropertiesStatics2<R, F: FnOnce(&IVideoEncodingPropertiesStatics2) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> {
static mut SHARED: ::windows::core::FactoryCache<VideoEncodingProperties, IVideoEncodingPropertiesStatics2> = ::windows::core::FactoryCache::new();
unsafe { SHARED.call(callback) }
}
}
unsafe impl ::windows::core::RuntimeType for VideoEncodingProperties {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Media.MediaProperties.VideoEncodingProperties;{76ee6c9a-37c2-4f2a-880a-1282bbb4373d})");
}
unsafe impl ::windows::core::Interface for VideoEncodingProperties {
type Vtable = IVideoEncodingProperties_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x76ee6c9a_37c2_4f2a_880a_1282bbb4373d);
}
impl ::windows::core::RuntimeName for VideoEncodingProperties {
const NAME: &'static str = "Windows.Media.MediaProperties.VideoEncodingProperties";
}
impl ::core::convert::From<VideoEncodingProperties> for ::windows::core::IUnknown {
fn from(value: VideoEncodingProperties) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&VideoEncodingProperties> for ::windows::core::IUnknown {
fn from(value: &VideoEncodingProperties) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for VideoEncodingProperties {
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 VideoEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<VideoEncodingProperties> for ::windows::core::IInspectable {
fn from(value: VideoEncodingProperties) -> Self {
value.0
}
}
impl ::core::convert::From<&VideoEncodingProperties> for ::windows::core::IInspectable {
fn from(value: &VideoEncodingProperties) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for VideoEncodingProperties {
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 VideoEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::TryFrom<VideoEncodingProperties> for IMediaEncodingProperties {
type Error = ::windows::core::Error;
fn try_from(value: VideoEncodingProperties) -> ::windows::core::Result<Self> {
::core::convert::TryFrom::try_from(&value)
}
}
impl ::core::convert::TryFrom<&VideoEncodingProperties> for IMediaEncodingProperties {
type Error = ::windows::core::Error;
fn try_from(value: &VideoEncodingProperties) -> ::windows::core::Result<Self> {
::windows::core::Interface::cast(value)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for VideoEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::windows::core::IntoParam::into_param(&self)
}
}
impl<'a> ::windows::core::IntoParam<'a, IMediaEncodingProperties> for &VideoEncodingProperties {
fn into_param(self) -> ::windows::core::Param<'a, IMediaEncodingProperties> {
::core::convert::TryInto::<IMediaEncodingProperties>::try_into(self).map(::windows::core::Param::Owned).unwrap_or(::windows::core::Param::None)
}
}
unsafe impl ::core::marker::Send for VideoEncodingProperties {}
unsafe impl ::core::marker::Sync for VideoEncodingProperties {}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct VideoEncodingQuality(pub i32);
impl VideoEncodingQuality {
pub const Auto: VideoEncodingQuality = VideoEncodingQuality(0i32);
pub const HD1080p: VideoEncodingQuality = VideoEncodingQuality(1i32);
pub const HD720p: VideoEncodingQuality = VideoEncodingQuality(2i32);
pub const Wvga: VideoEncodingQuality = VideoEncodingQuality(3i32);
pub const Ntsc: VideoEncodingQuality = VideoEncodingQuality(4i32);
pub const Pal: VideoEncodingQuality = VideoEncodingQuality(5i32);
pub const Vga: VideoEncodingQuality = VideoEncodingQuality(6i32);
pub const Qvga: VideoEncodingQuality = VideoEncodingQuality(7i32);
pub const Uhd2160p: VideoEncodingQuality = VideoEncodingQuality(8i32);
pub const Uhd4320p: VideoEncodingQuality = VideoEncodingQuality(9i32);
}
impl ::core::convert::From<i32> for VideoEncodingQuality {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for VideoEncodingQuality {
type Abi = Self;
}
unsafe impl ::windows::core::RuntimeType for VideoEncodingQuality {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Media.MediaProperties.VideoEncodingQuality;i4)");
}
impl ::windows::core::DefaultType for VideoEncodingQuality {
type DefaultType = Self;
}
|
extern crate docopt;
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate bincode;
extern crate petgraph;
extern crate rand;
extern crate statrs;
extern crate capngraph;
use docopt::Docopt;
use std::fs::File;
use petgraph::prelude::*;
use std::io::{BufWriter, Write};
#[cfg_attr(rustfmt, rustfmt_skip)]
const USAGE: &str = "
Export costs/benefits and edge weights to a text format for use with SSA / BCT. IMM requires an
additional conversion step beyond this.
Usage:
export-data unweighted <graph> <out>
export-data cost-aware <graph> <costs> <out>
export-data ctvm <graph> <costs> <benefits> <out>
export-data (-h | --help)
Options:
-h --help Show this screen.
";
#[derive(Serialize, Deserialize, Debug)]
struct Args {
arg_graph: String,
arg_costs: Option<String>,
arg_benefits: Option<String>,
arg_out: String,
}
fn main() {
let args: Args = Docopt::new(USAGE)
.and_then(|d| d.deserialize())
.unwrap_or_else(|e| e.exit());
let g = capngraph::load_graph(&args.arg_graph).unwrap();
let costs: Vec<f64> = args.arg_costs
.as_ref()
.map(|costs| {
bincode::deserialize_from(&mut File::open(costs).unwrap(), bincode::Infinite).unwrap()
})
.unwrap_or_else(|| vec![1f64; g.node_count()]);
assert_eq!(costs.len(), g.node_count());
let benefits: Vec<f64> = args.arg_benefits
.as_ref()
.map(|benefits| {
bincode::deserialize_from(&mut File::open(benefits).unwrap(), bincode::Infinite)
.unwrap()
})
.unwrap_or_else(|| vec![1f64; g.node_count()]);
assert_eq!(benefits.len(), g.node_count());
let out = File::create(&args.arg_out).unwrap();
let mut writer = BufWriter::new(out);
writeln!(writer, "{} {}", g.node_count(), g.edge_count()).unwrap();
// we skip 0 because that is a dummy node
for i in 1..g.node_count() {
writeln!(writer, "{} {} {}", i, costs[i], benefits[i]).unwrap();
}
for edge in g.edge_references() {
writeln!(writer,
"{} {} {}",
edge.source().index(),
edge.target().index(),
f64::from(*edge.weight()))
.unwrap();
}
}
|
use csv::Writer;
use std::fs::File;
use crate::between_herd_spread_model::InfectionEvents;
use crate::prelude::*;
#[derive(derive_more::From)]
pub struct BetweenHerdInfectionEventsRecorder(Writer<File>);
/// This is coupled with system [record_between_herd_infection_events].
pub fn setup_between_herd_infection_events_recording(mut commands: Commands) {
//TODO: determine an appropriate buffer capacity
let buffer_capacity_in_bytes = 100_000_000; // 100 mb.
// create the path (not necessarily the file)
//TODO: put this somewhere else
let path_to_csv_file: std::path::PathBuf = "outputs/between_herd_infection_events.csv".into();
let mut path_to_directory = path_to_csv_file.clone();
path_to_directory.pop();
std::fs::create_dir_all(path_to_directory).unwrap();
let wtr = std::fs::OpenOptions::new()
// .append(false)
.create(true)
.write(true)
.truncate(true)
.open(path_to_csv_file)
.unwrap();
let mut csv_writer = csv::WriterBuilder::new()
.has_headers(false)
.buffer_capacity(buffer_capacity_in_bytes)
.flexible(false)
.delimiter(b';') // change to `false`
.from_writer(wtr);
csv_writer
.write_record(&[
"scenario_tick",
"batch_id",
"origin_farm_id",
"target_farm_id",
"new_infections",
])
.unwrap();
commands.insert_resource(BetweenHerdInfectionEventsRecorder::from(csv_writer));
}
/// The saved fields must correspond to [setup_between_herd_infection_events_recording]
pub fn record_between_herd_infection_events(
In(events): In<Option<InfectionEvents>>,
mut csv_file: ResMut<BetweenHerdInfectionEventsRecorder>,
// scenario_time: Res<ScenarioTime>,
) {
if let Some(events) = events {
let InfectionEvents {
scenario_tick,
batch_id,
events_values,
} = events;
events_values.into_iter().for_each(|x| {
csv_file.0.serialize((scenario_tick, batch_id, x)).unwrap();
})
} else {
// no infection events
}
}
|
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)]
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct COMDLG_FILTERSPEC {
pub pszName: super::super::super::Foundation::PWSTR,
pub pszSpec: super::super::super::Foundation::PWSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl COMDLG_FILTERSPEC {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for COMDLG_FILTERSPEC {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::fmt::Debug for COMDLG_FILTERSPEC {
fn fmt(&self, fmt: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
fmt.debug_struct("COMDLG_FILTERSPEC").field("pszName", &self.pszName).field("pszSpec", &self.pszSpec).finish()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for COMDLG_FILTERSPEC {
fn eq(&self, other: &Self) -> bool {
self.pszName == other.pszName && self.pszSpec == other.pszSpec
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for COMDLG_FILTERSPEC {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for COMDLG_FILTERSPEC {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct DEVICE_SCALE_FACTOR(pub i32);
pub const DEVICE_SCALE_FACTOR_INVALID: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(0i32);
pub const SCALE_100_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(100i32);
pub const SCALE_120_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(120i32);
pub const SCALE_125_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(125i32);
pub const SCALE_140_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(140i32);
pub const SCALE_150_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(150i32);
pub const SCALE_160_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(160i32);
pub const SCALE_175_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(175i32);
pub const SCALE_180_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(180i32);
pub const SCALE_200_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(200i32);
pub const SCALE_225_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(225i32);
pub const SCALE_250_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(250i32);
pub const SCALE_300_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(300i32);
pub const SCALE_350_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(350i32);
pub const SCALE_400_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(400i32);
pub const SCALE_450_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(450i32);
pub const SCALE_500_PERCENT: DEVICE_SCALE_FACTOR = DEVICE_SCALE_FACTOR(500i32);
impl ::core::convert::From<i32> for DEVICE_SCALE_FACTOR {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for DEVICE_SCALE_FACTOR {
type Abi = Self;
}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IObjectArray(pub ::windows::core::IUnknown);
impl IObjectArray {
pub unsafe fn GetCount(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn GetAt<T: ::windows::core::Interface>(&self, uiindex: u32) -> ::windows::core::Result<T> {
let mut result__ = ::core::option::Option::None;
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(uiindex), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__)
}
}
unsafe impl ::windows::core::Interface for IObjectArray {
type Vtable = IObjectArray_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x92ca9dcd_5622_4bba_a805_5e9f541bd8c9);
}
impl ::core::convert::From<IObjectArray> for ::windows::core::IUnknown {
fn from(value: IObjectArray) -> Self {
value.0
}
}
impl ::core::convert::From<&IObjectArray> for ::windows::core::IUnknown {
fn from(value: &IObjectArray) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IObjectArray {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IObjectArray {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IObjectArray_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, pcobjects: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uiindex: u32, riid: *const ::windows::core::GUID, ppv: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct IObjectCollection(pub ::windows::core::IUnknown);
impl IObjectCollection {
pub unsafe fn GetCount(&self) -> ::windows::core::Result<u32> {
let mut result__: <u32 as ::windows::core::Abi>::Abi = ::core::mem::zeroed();
(::windows::core::Interface::vtable(self).3)(::core::mem::transmute_copy(self), &mut result__).from_abi::<u32>(result__)
}
pub unsafe fn GetAt<T: ::windows::core::Interface>(&self, uiindex: u32) -> ::windows::core::Result<T> {
let mut result__ = ::core::option::Option::None;
(::windows::core::Interface::vtable(self).4)(::core::mem::transmute_copy(self), ::core::mem::transmute(uiindex), &<T as ::windows::core::Interface>::IID, &mut result__ as *mut _ as *mut _).and_some(result__)
}
pub unsafe fn AddObject<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IUnknown>>(&self, punk: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).5)(::core::mem::transmute_copy(self), punk.into_param().abi()).ok()
}
pub unsafe fn AddFromArray<'a, Param0: ::windows::core::IntoParam<'a, IObjectArray>>(&self, poasource: Param0) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).6)(::core::mem::transmute_copy(self), poasource.into_param().abi()).ok()
}
pub unsafe fn RemoveObjectAt(&self, uiindex: u32) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).7)(::core::mem::transmute_copy(self), ::core::mem::transmute(uiindex)).ok()
}
pub unsafe fn Clear(&self) -> ::windows::core::Result<()> {
(::windows::core::Interface::vtable(self).8)(::core::mem::transmute_copy(self)).ok()
}
}
unsafe impl ::windows::core::Interface for IObjectCollection {
type Vtable = IObjectCollection_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5632b1a4_e38a_400a_928a_d4cd63230295);
}
impl ::core::convert::From<IObjectCollection> for ::windows::core::IUnknown {
fn from(value: IObjectCollection) -> Self {
value.0
}
}
impl ::core::convert::From<&IObjectCollection> for ::windows::core::IUnknown {
fn from(value: &IObjectCollection) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IObjectCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Owned(self.0)
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for &'a IObjectCollection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0)
}
}
impl ::core::convert::From<IObjectCollection> for IObjectArray {
fn from(value: IObjectCollection) -> Self {
unsafe { ::core::mem::transmute(value) }
}
}
impl ::core::convert::From<&IObjectCollection> for IObjectArray {
fn from(value: &IObjectCollection) -> Self {
::core::convert::From::from(::core::clone::Clone::clone(value))
}
}
impl<'a> ::windows::core::IntoParam<'a, IObjectArray> for IObjectCollection {
fn into_param(self) -> ::windows::core::Param<'a, IObjectArray> {
::windows::core::Param::Owned(unsafe { ::core::mem::transmute(self) })
}
}
impl<'a> ::windows::core::IntoParam<'a, IObjectArray> for &IObjectCollection {
fn into_param(self) -> ::windows::core::Param<'a, IObjectArray> {
::windows::core::Param::Borrowed(unsafe { ::core::mem::transmute(self) })
}
}
#[repr(C)]
#[doc(hidden)]
pub struct IObjectCollection_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, pcobjects: *mut u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uiindex: u32, riid: *const ::windows::core::GUID, ppv: *mut *mut ::core::ffi::c_void) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, punk: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, poasource: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, uiindex: u32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
pub struct ITEMIDLIST {
pub mkid: SHITEMID,
}
impl ITEMIDLIST {}
impl ::core::default::Default for ITEMIDLIST {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for ITEMIDLIST {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for ITEMIDLIST {}
unsafe impl ::windows::core::Abi for ITEMIDLIST {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct PERCEIVED(pub i32);
pub const PERCEIVED_TYPE_FIRST: PERCEIVED = PERCEIVED(-3i32);
pub const PERCEIVED_TYPE_CUSTOM: PERCEIVED = PERCEIVED(-3i32);
pub const PERCEIVED_TYPE_UNSPECIFIED: PERCEIVED = PERCEIVED(-2i32);
pub const PERCEIVED_TYPE_FOLDER: PERCEIVED = PERCEIVED(-1i32);
pub const PERCEIVED_TYPE_UNKNOWN: PERCEIVED = PERCEIVED(0i32);
pub const PERCEIVED_TYPE_TEXT: PERCEIVED = PERCEIVED(1i32);
pub const PERCEIVED_TYPE_IMAGE: PERCEIVED = PERCEIVED(2i32);
pub const PERCEIVED_TYPE_AUDIO: PERCEIVED = PERCEIVED(3i32);
pub const PERCEIVED_TYPE_VIDEO: PERCEIVED = PERCEIVED(4i32);
pub const PERCEIVED_TYPE_COMPRESSED: PERCEIVED = PERCEIVED(5i32);
pub const PERCEIVED_TYPE_DOCUMENT: PERCEIVED = PERCEIVED(6i32);
pub const PERCEIVED_TYPE_SYSTEM: PERCEIVED = PERCEIVED(7i32);
pub const PERCEIVED_TYPE_APPLICATION: PERCEIVED = PERCEIVED(8i32);
pub const PERCEIVED_TYPE_GAMEMEDIA: PERCEIVED = PERCEIVED(9i32);
pub const PERCEIVED_TYPE_CONTACTS: PERCEIVED = PERCEIVED(10i32);
pub const PERCEIVED_TYPE_LAST: PERCEIVED = PERCEIVED(10i32);
impl ::core::convert::From<i32> for PERCEIVED {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for PERCEIVED {
type Abi = Self;
}
pub const PERCEIVEDFLAG_GDIPLUS: u32 = 16u32;
pub const PERCEIVEDFLAG_HARDCODED: u32 = 2u32;
pub const PERCEIVEDFLAG_NATIVESUPPORT: u32 = 4u32;
pub const PERCEIVEDFLAG_SOFTCODED: u32 = 1u32;
pub const PERCEIVEDFLAG_UNDEFINED: u32 = 0u32;
pub const PERCEIVEDFLAG_WMSDK: u32 = 32u32;
pub const PERCEIVEDFLAG_ZIPFOLDER: u32 = 64u32;
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct SHCOLSTATE(pub i32);
pub const SHCOLSTATE_DEFAULT: SHCOLSTATE = SHCOLSTATE(0i32);
pub const SHCOLSTATE_TYPE_STR: SHCOLSTATE = SHCOLSTATE(1i32);
pub const SHCOLSTATE_TYPE_INT: SHCOLSTATE = SHCOLSTATE(2i32);
pub const SHCOLSTATE_TYPE_DATE: SHCOLSTATE = SHCOLSTATE(3i32);
pub const SHCOLSTATE_TYPEMASK: SHCOLSTATE = SHCOLSTATE(15i32);
pub const SHCOLSTATE_ONBYDEFAULT: SHCOLSTATE = SHCOLSTATE(16i32);
pub const SHCOLSTATE_SLOW: SHCOLSTATE = SHCOLSTATE(32i32);
pub const SHCOLSTATE_EXTENDED: SHCOLSTATE = SHCOLSTATE(64i32);
pub const SHCOLSTATE_SECONDARYUI: SHCOLSTATE = SHCOLSTATE(128i32);
pub const SHCOLSTATE_HIDDEN: SHCOLSTATE = SHCOLSTATE(256i32);
pub const SHCOLSTATE_PREFER_VARCMP: SHCOLSTATE = SHCOLSTATE(512i32);
pub const SHCOLSTATE_PREFER_FMTCMP: SHCOLSTATE = SHCOLSTATE(1024i32);
pub const SHCOLSTATE_NOSORTBYFOLDERNESS: SHCOLSTATE = SHCOLSTATE(2048i32);
pub const SHCOLSTATE_VIEWONLY: SHCOLSTATE = SHCOLSTATE(65536i32);
pub const SHCOLSTATE_BATCHREAD: SHCOLSTATE = SHCOLSTATE(131072i32);
pub const SHCOLSTATE_NO_GROUPBY: SHCOLSTATE = SHCOLSTATE(262144i32);
pub const SHCOLSTATE_FIXED_WIDTH: SHCOLSTATE = SHCOLSTATE(4096i32);
pub const SHCOLSTATE_NODPISCALE: SHCOLSTATE = SHCOLSTATE(8192i32);
pub const SHCOLSTATE_FIXED_RATIO: SHCOLSTATE = SHCOLSTATE(16384i32);
pub const SHCOLSTATE_DISPLAYMASK: SHCOLSTATE = SHCOLSTATE(61440i32);
impl ::core::convert::From<i32> for SHCOLSTATE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for SHCOLSTATE {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C, packed(1))]
#[cfg(feature = "Win32_Foundation")]
pub struct SHELLDETAILS {
pub fmt: i32,
pub cxChar: i32,
pub str: STRRET,
}
#[cfg(feature = "Win32_Foundation")]
impl SHELLDETAILS {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for SHELLDETAILS {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for SHELLDETAILS {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for SHELLDETAILS {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for SHELLDETAILS {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C, packed(1))]
pub struct SHITEMID {
pub cb: u16,
pub abID: [u8; 1],
}
impl SHITEMID {}
impl ::core::default::Default for SHITEMID {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
impl ::core::cmp::PartialEq for SHITEMID {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
impl ::core::cmp::Eq for SHITEMID {}
unsafe impl ::windows::core::Abi for SHITEMID {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct STRRET {
pub uType: u32,
pub Anonymous: STRRET_0,
}
#[cfg(feature = "Win32_Foundation")]
impl STRRET {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for STRRET {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for STRRET {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for STRRET {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for STRRET {
type Abi = Self;
}
#[derive(:: core :: clone :: Clone, :: core :: marker :: Copy)]
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub union STRRET_0 {
pub pOleStr: super::super::super::Foundation::PWSTR,
pub uOffset: u32,
pub cStr: [u8; 260],
}
#[cfg(feature = "Win32_Foundation")]
impl STRRET_0 {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::default::Default for STRRET_0 {
fn default() -> Self {
unsafe { ::core::mem::zeroed() }
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::PartialEq for STRRET_0 {
fn eq(&self, _other: &Self) -> bool {
unimplemented!()
}
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::cmp::Eq for STRRET_0 {}
#[cfg(feature = "Win32_Foundation")]
unsafe impl ::windows::core::Abi for STRRET_0 {
type Abi = Self;
}
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)]
#[repr(transparent)]
pub struct STRRET_TYPE(pub i32);
pub const STRRET_WSTR: STRRET_TYPE = STRRET_TYPE(0i32);
pub const STRRET_OFFSET: STRRET_TYPE = STRRET_TYPE(1i32);
pub const STRRET_CSTR: STRRET_TYPE = STRRET_TYPE(2i32);
impl ::core::convert::From<i32> for STRRET_TYPE {
fn from(value: i32) -> Self {
Self(value)
}
}
unsafe impl ::windows::core::Abi for STRRET_TYPE {
type Abi = Self;
}
|
#![allow(non_snake_case)]
use std::collections::HashMap;
use std::hash::Hash;
pub type OxGetKeyRef<TElem, TKey> = (Fn(&TElem) -> &TKey);
pub struct GroupWithRefs<'a, TKey, TValue>
where
TKey: Eq + Hash,
TKey: 'a,
TValue: 'a
{
key: &'a TKey,
values: Vec<&'a TValue>,
}
pub fn goWhere<'a, T>(vec: &Vec<&'a T>, oxPred: &(Fn(&T) -> bool)) -> Vec<&'a T> {
let mut filtered = Vec::new();
for iElem in vec {
let isOk = oxPred(iElem);
if !isOk {
continue;
} else {
let toAdd = *iElem;
filtered.push(toAdd);
}
}
filtered
}
fn _addOrUpdateGroup<'map, 'mapKeyOrElem, TKey, TElem>(map: &'map mut HashMap<&'mapKeyOrElem TKey, GroupWithRefs<'mapKeyOrElem, TKey, TElem>>, key: &'mapKeyOrElem TKey, value: &'mapKeyOrElem TElem)
where TKey: Eq + Hash, 'mapKeyOrElem: 'map,
{
let groupMaybe = map.get_mut(key);
match groupMaybe
{
Some(g) =>
{
g.values.push(value)
}
None =>
{
let _newG = GroupWithRefs { key, values: vec![value] };
}
}
}
pub fn goGroupBy<'a, TElem, TKey>(owingVec: &'a Vec<TElem>, oxGetKeyRef: &'a OxGetKeyRef<TElem, TKey>) -> Vec<GroupWithRefs<'a, TKey, TElem>>
where
TKey: Eq + Hash,
{
let mut groupsByKeyMap: HashMap<&TKey, GroupWithRefs<TKey, TElem>> = HashMap::new();
for iElemRef in owingVec
{
let keyRef: &TKey = oxGetKeyRef(iElemRef);
_addOrUpdateGroup(&mut groupsByKeyMap, keyRef, iElemRef)
}
let values = groupsByKeyMap
.into_iter()
.map(|x| x.1);
let valuesVec: Vec<GroupWithRefs<'a, TKey, TElem>> = values.collect();
valuesVec
}
|
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! A stack-allocated vector, allowing storage of N elements on the stack.
use std::marker::Unsize;
use std::iter::Extend;
use std::ptr::{self, drop_in_place, NonNull};
use std::ops::{Deref, DerefMut, Range};
use std::hash::{Hash, Hasher};
use std::slice;
use std::fmt;
use std::mem;
use std::mem::ManuallyDrop;
use std::ops::Bound::{Excluded, Included, Unbounded};
use std::ops::RangeBounds;
pub unsafe trait Array {
type Element;
type PartialStorage: Unsize<[ManuallyDrop<Self::Element>]>;
const LEN: usize;
}
unsafe impl<T> Array for [T; 1] {
type Element = T;
type PartialStorage = [ManuallyDrop<T>; 1];
const LEN: usize = 1;
}
unsafe impl<T> Array for [T; 8] {
type Element = T;
type PartialStorage = [ManuallyDrop<T>; 8];
const LEN: usize = 8;
}
unsafe impl<T> Array for [T; 32] {
type Element = T;
type PartialStorage = [ManuallyDrop<T>; 32];
const LEN: usize = 32;
}
pub struct ArrayVec<A: Array> {
count: usize,
values: A::PartialStorage
}
impl<A> Hash for ArrayVec<A>
where A: Array,
A::Element: Hash {
fn hash<H>(&self, state: &mut H) where H: Hasher {
(&self[..]).hash(state);
}
}
impl<A> Clone for ArrayVec<A>
where A: Array,
A::Element: Clone {
fn clone(&self) -> Self {
let mut v = ArrayVec::new();
v.extend(self.iter().cloned());
v
}
}
impl<A: Array> ArrayVec<A> {
pub fn new() -> Self {
ArrayVec {
count: 0,
values: unsafe { ::std::mem::uninitialized() },
}
}
pub fn len(&self) -> usize {
self.count
}
pub unsafe fn set_len(&mut self, len: usize) {
self.count = len;
}
/// Panics when the stack vector is full.
pub fn push(&mut self, el: A::Element) {
let arr = &mut self.values as &mut [ManuallyDrop<_>];
arr[self.count] = ManuallyDrop::new(el);
self.count += 1;
}
pub fn pop(&mut self) -> Option<A::Element> {
if self.count > 0 {
let arr = &mut self.values as &mut [ManuallyDrop<_>];
self.count -= 1;
unsafe {
let value = ptr::read(&*arr[self.count]);
Some(value)
}
} else {
None
}
}
pub fn drain<R>(&mut self, range: R) -> Drain<A>
where R: RangeBounds<usize>
{
// Memory safety
//
// When the Drain is first created, it shortens the length of
// the source vector to make sure no uninitialized or moved-from elements
// are accessible at all if the Drain's destructor never gets to run.
//
// Drain will ptr::read out the values to remove.
// When finished, remaining tail of the vec is copied back to cover
// the hole, and the vector length is restored to the new length.
//
let len = self.len();
let start = match range.start_bound() {
Included(&n) => n,
Excluded(&n) => n + 1,
Unbounded => 0,
};
let end = match range.end_bound() {
Included(&n) => n + 1,
Excluded(&n) => n,
Unbounded => len,
};
assert!(start <= end);
assert!(end <= len);
unsafe {
// set self.vec length's to start, to be safe in case Drain is leaked
self.set_len(start);
// Use the borrow in the IterMut to indicate borrowing behavior of the
// whole Drain iterator (like &mut T).
let range_slice = {
let arr = &mut self.values as &mut [ManuallyDrop<<A as Array>::Element>];
slice::from_raw_parts_mut(arr.as_mut_ptr().offset(start as isize),
end - start)
};
Drain {
tail_start: end,
tail_len: len - end,
iter: range_slice.iter(),
array_vec: NonNull::from(self),
}
}
}
}
impl<A> Default for ArrayVec<A>
where A: Array {
fn default() -> Self {
ArrayVec::new()
}
}
impl<A> fmt::Debug for ArrayVec<A>
where A: Array,
A::Element: fmt::Debug {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
self[..].fmt(f)
}
}
impl<A: Array> Deref for ArrayVec<A> {
type Target = [A::Element];
fn deref(&self) -> &Self::Target {
unsafe {
slice::from_raw_parts(&self.values as *const _ as *const A::Element, self.count)
}
}
}
impl<A: Array> DerefMut for ArrayVec<A> {
fn deref_mut(&mut self) -> &mut [A::Element] {
unsafe {
slice::from_raw_parts_mut(&mut self.values as *mut _ as *mut A::Element, self.count)
}
}
}
impl<A: Array> Drop for ArrayVec<A> {
fn drop(&mut self) {
unsafe {
drop_in_place(&mut self[..])
}
}
}
impl<A: Array> Extend<A::Element> for ArrayVec<A> {
fn extend<I>(&mut self, iter: I) where I: IntoIterator<Item=A::Element> {
for el in iter {
self.push(el);
}
}
}
pub struct Iter<A: Array> {
indices: Range<usize>,
store: A::PartialStorage,
}
impl<A: Array> Drop for Iter<A> {
fn drop(&mut self) {
self.for_each(drop);
}
}
impl<A: Array> Iterator for Iter<A> {
type Item = A::Element;
fn next(&mut self) -> Option<A::Element> {
let arr = &self.store as &[ManuallyDrop<_>];
unsafe {
self.indices.next().map(|i| ptr::read(&*arr[i]))
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.indices.size_hint()
}
}
pub struct Drain<'a, A: Array>
where A::Element: 'a
{
tail_start: usize,
tail_len: usize,
iter: slice::Iter<'a, ManuallyDrop<A::Element>>,
array_vec: NonNull<ArrayVec<A>>,
}
impl<'a, A: Array> Iterator for Drain<'a, A> {
type Item = A::Element;
#[inline]
fn next(&mut self) -> Option<A::Element> {
self.iter.next().map(|elt| unsafe { ptr::read(&**elt) })
}
fn size_hint(&self) -> (usize, Option<usize>) {
self.iter.size_hint()
}
}
impl<'a, A: Array> Drop for Drain<'a, A> {
fn drop(&mut self) {
// exhaust self first
self.for_each(drop);
if self.tail_len > 0 {
unsafe {
let source_array_vec: &mut ArrayVec<A> = self.array_vec.as_mut();
// memmove back untouched tail, update to new length
let start = source_array_vec.len();
let tail = self.tail_start;
{
let arr =
&mut source_array_vec.values as &mut [ManuallyDrop<<A as Array>::Element>];
let src = arr.as_ptr().offset(tail as isize);
let dst = arr.as_mut_ptr().offset(start as isize);
ptr::copy(src, dst, self.tail_len);
};
source_array_vec.set_len(start + self.tail_len);
}
}
}
}
impl<A: Array> IntoIterator for ArrayVec<A> {
type Item = A::Element;
type IntoIter = Iter<A>;
fn into_iter(self) -> Self::IntoIter {
let store = unsafe {
ptr::read(&self.values)
};
let indices = 0..self.count;
mem::forget(self);
Iter {
indices,
store,
}
}
}
impl<'a, A: Array> IntoIterator for &'a ArrayVec<A> {
type Item = &'a A::Element;
type IntoIter = slice::Iter<'a, A::Element>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl<'a, A: Array> IntoIterator for &'a mut ArrayVec<A> {
type Item = &'a mut A::Element;
type IntoIter = slice::IterMut<'a, A::Element>;
fn into_iter(self) -> Self::IntoIter {
self.iter_mut()
}
}
|
use std::collections::HashMap;
struct Orbit {
orbited: String,
orbiting: String,
}
impl Orbit {
fn new(orbited: String, orbiting: String) -> Orbit {
return Orbit {
orbited,
orbiting,
};
}
}
struct CelestialBody {
name: String,
parents: Vec<String>,
children: Vec<String>,
}
impl CelestialBody {
fn add_child(&mut self, child_body: String) {
self.children.push(child_body);
}
fn add_parent(&mut self, parent_body: String) {
self.parents.push(parent_body);
}
fn new(name: String) -> CelestialBody {
return CelestialBody {
name,
parents: Vec::new(),
children: Vec::new(),
};
}
fn orbit_count(&self, map: &HashMap<String, CelestialBody>) -> u32 {
if self.parents.is_empty() {
return 0;
}
let x: u32 = self.parents.iter()
.map(|name| -> u32 {
map.get(name).map_or(0, |body| body.orbit_count(map))
})
.sum();
return x + 1u32;
}
fn parents_and_children(&self) -> Vec<String> {
let mut vector = Vec::new();
vector.extend(self.parents.clone());
vector.extend(self.children.clone());
return vector;
}
fn find_santa(&self, map: &HashMap<String, CelestialBody>, visited: Vec<String>) -> u32 {
if visited.contains(&self.name) {
return 0;
}
if (self.name == String::from("SAN")){
return (visited.len() - 2) as u32;
}
for associate_name in self.parents_and_children().iter() {
let mut asdf: Vec<String> = Vec::new();
asdf.extend(visited.clone());
asdf.push(self.name.clone());
let result = match map.get(associate_name) {
Some(body) => body.find_santa(map, asdf),
None => 0
};
if (result > 0) {
return result;
}
}
return 0;
}
}
fn make_orbit_graph(input: Vec<String>) -> HashMap<String, CelestialBody> {
let orbits: Vec<Orbit> = input.iter()
.map(|input_string| -> Orbit {
let split: Vec<&str> = input_string.split(")")
.collect();
let orbited = String::from(split[0]);
let orbiting = String::from(split[1]);
return Orbit::new(
orbited,
orbiting,
);
}).collect();
let mut celestial_body_map: HashMap<String, CelestialBody> = HashMap::new();
for orbit in orbits.iter() {
let mut orbited_body = celestial_body_map.entry(orbit.orbited.clone())
.or_insert(CelestialBody::new(orbit.orbited.clone()));
orbited_body.add_child(orbit.orbiting.clone());
}
for orbit in orbits.iter() {
let mut orbiting_body = celestial_body_map.entry(orbit.orbiting.clone())
.or_insert(CelestialBody::new(orbit.orbiting.clone()));
orbiting_body.add_parent(orbit.orbited.clone());
}
return celestial_body_map;
}
fn puzzle1(input: Vec<String>) -> u32 {
let celestial_body_map = make_orbit_graph(input);
return celestial_body_map.values()
.map(|body| body.orbit_count(&celestial_body_map))
.sum();
}
fn puzzle2(input: Vec<String>) -> u32 {
let celestial_body_map = make_orbit_graph(input);
let origin_body = celestial_body_map.get("YOU");
return match origin_body {
Some(body) => body.find_santa(&celestial_body_map, Vec::new()),
None => 0
}
}
#[cfg(test)]
mod tests {
use crate::utils;
use crate::day6::{puzzle1, puzzle2};
struct Puzzle1Test {
test_data: Vec<String>,
expected_result: u32,
}
#[test]
fn test_puzzle_1() {
let mut tests: Vec<Puzzle1Test> = Vec::new();
tests.push(Puzzle1Test {
test_data: vec![String::from("COM)B"),
String::from("B)C"),
String::from("C)D"),
String::from("D)E"),
String::from("E)F"),
String::from("B)G"),
String::from("G)H"),
String::from("D)I"),
String::from("E)J"),
String::from("J)K"),
String::from("K)L")],
expected_result: 42,
});
match utils::read_lines("data/Day6.txt") {
Ok(lines) => {
tests.push(Puzzle1Test {
test_data: lines,
expected_result: 322508,
});
for test in tests {
println!("{}", "test");
let result = puzzle1(test.test_data);
assert_eq!(result, test.expected_result);
}
}
Err(error) => {
println!("{}", error);
}
}
}
struct Puzzle2Test {
test_data: Vec<String>,
expected_result: u32,
}
#[test]
fn test_puzzle_2() {
let mut tests: Vec<Puzzle2Test> = Vec::new();
tests.push(Puzzle2Test {
test_data: vec![String::from("COM)B"),
String::from("B)C"),
String::from("C)D"),
String::from("D)E"),
String::from("E)F"),
String::from("B)G"),
String::from("G)H"),
String::from("D)I"),
String::from("E)J"),
String::from("J)K"),
String::from("K)L"),
String::from("K)YOU"),
String::from("I)SAN")],
expected_result: 4,
});
match utils::read_lines("data/Day6.txt") {
Ok(lines) => {
tests.push(Puzzle2Test {
test_data: lines,
expected_result: 496,
});
for test in tests {
let result = puzzle2(test.test_data);
assert_eq!(result, test.expected_result);
}
}
Err(error) => {
println!("{}", error);
}
}
}
} |
///
/// Export public structs
///
pub use self::editor::Editor;
pub use self::database_browser::DatabaseBrowser;
pub use self::header_bar::HeaderBar;
pub use self::result_list::ResultList;
pub use self::main_window::MainWindow;
pub use self::component_store::ComponentStore;
pub use self::traits::ComponentStoreTrait;
// local modules
mod editor;
mod database_browser;
mod header_bar;
mod result_list;
mod main_window;
mod component_store;
// make traits public
pub mod traits;
|
use serenity::framework::standard::Args;
use serenity::{
framework::standard::{
macros::{command, group},
CommandResult,
},
model::channel::Message,
prelude::*,
};
use crate::bot::utils::Utils;
use crate::extensions::context::ClientContextExt;
use serenity::model::prelude::ReactionType::Unicode;
#[group()]
#[commands(upcoming)]
pub struct Get;
#[command]
async fn rocket(ctx: &Context, msg: &Message, _args: Args) -> CommandResult {
// let rocket = match args.remains() {
// Some(rocket) => rocket,
// None => {
// msg.reply(&ctx, "Please provide a rocket to look up in the database")
// .await?;
// return Ok(());
// }
// };
// let rockets = match get_rocket(rocket).await {
// Ok(res) => res,
// Err(e) => {
// error!("{:?}", e);
// return Ok(());
// }
// };
//
// if rockets.count == 0 {
// check_msg(msg.reply(&ctx, "Unable to locate that rocket").await);
// return Ok(());
// }
//
// let rocket = &rockets.rockets[0];
//
// let agencies = match get_agency(&rocket.family.as_ref().unwrap().agencies).await {
// Ok(res) => res,
// Err(e) => {
// error!("{:?}", e);
// return Ok(());
// }
// };
// let agency: &Agency = &agencies.agencies[0];
//
// check_msg(
// msg.channel_id
// .send_message(&ctx.http, |m| {
// m.embed(|e| {
// e.title(&rocket.name)
// .url(&rocket.wiki_url)
// .image(&rocket.image_url)
// .fields(vec![(
// "Agency",
// format!(
// "\
// ➤ Name: **{}**\n\
// ➤ Country: **{}**\n\
// ",
// &agency.name, &agency.country_code
// ),
// false,
// )])
// .colour(0x00adf8)
// })
// })
// .await,
// );
msg.reply(
&ctx,
"Sorry not implemented yet due to switching to models 2.0",
)
.await?;
Ok(())
}
#[command]
#[aliases("company")]
async fn agency(_ctx: &Context, _msg: &Message, _args: Args) -> CommandResult {
Ok(())
}
#[command]
#[aliases("upcoming_launch", "next", "launch")]
async fn upcoming(ctx: &Context, msg: &Message) -> CommandResult {
let db = ctx.get_db().await;
let next_launches = db.get_launches().await;
let next_launch = match next_launches.get(0) {
Some(launch) => launch,
None => {
msg.reply(&ctx, "Unable to find any in the near future :(")
.await?;
return Ok(());
}
};
let mut description = next_launch
.description
.as_ref()
.unwrap_or(&"No description found...".to_string())
.clone();
if description.len() > 2000 {
description = "Description too long :(".to_string()
}
Utils::check_msg(
msg.channel_id
.send_message(&ctx.http, |m| {
m.embed(|e| {
e.color(0x00adf8)
.image(&next_launch.image_url.as_ref().unwrap_or(&" ".to_string()))
.title(&next_launch.name)
.description(format!("> {}", &description))
.footer(|f| f.text(&next_launch.launch_id))
})
.reactions(vec![Unicode("🔔".to_string())])
})
.await,
);
Ok(())
}
|
use crate::database;
use crate::todo::Todo;
pub fn add(description: String, db_filename: &str) {
let mut db = database::read(db_filename);
db.todos.push( Todo {
title: description.clone(),
done: false
});
database::save(&db, db_filename);
println!("\"{}\" added \u{2714}", description);
}
pub fn list(db_filename: &str) {
let db = database::read(db_filename);
if db.todos.len() == 0 {
println!("The todo list is empty, please add one")
}
for todo in db.todos {
println!("{}", todo.title)
}
}
|
//! CLI tests for the compile subcommand.
use anyhow::{bail, Context};
use std::env;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
const CLI_INTEGRATION_TESTS_ASSETS: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/assets");
const OBJECT_FILE_ENGINE_TEST_C_SOURCE: &[u8] =
include_bytes!("object_file_engine_test_c_source.c");
// TODO:
const OBJECT_FILE_ENGINE_TEST_WASM_PATH: &str =
concat!(env!("CARGO_MANIFEST_DIR"), "/assets/qjs.wasm");
const WASMER_PATH: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../../target/release/wasmer"
);
#[cfg(not(windows))]
const LIBWASMER_PATH: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../../target/release/libwasmer_c_api.a"
);
#[cfg(windows)]
const LIBWASMER_PATH: &str = concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../../target/release/wasmer_c_api.lib"
);
/// Get the path to the `wasmer` executable to be used in this test.
fn get_wasmer_path() -> PathBuf {
PathBuf::from(env::var("WASMER_TEST_WASMER_PATH").unwrap_or_else(|_| WASMER_PATH.to_string()))
}
/// Get the path to the `libwasmer.a` static library.
fn get_libwasmer_path() -> PathBuf {
PathBuf::from(
env::var("WASMER_TEST_LIBWASMER_PATH").unwrap_or_else(|_| LIBWASMER_PATH.to_string()),
)
}
#[allow(dead_code)]
#[derive(Debug, Copy, Clone)]
pub enum Engine {
Jit,
Native,
ObjectFile,
}
impl Engine {
// TODO: make this `const fn` when Wasmer moves to Rust 1.46.0+
pub fn to_flag(self) -> &'static str {
match self {
Engine::Jit => "--jit",
Engine::Native => "--native",
Engine::ObjectFile => "--object-file",
}
}
}
#[allow(dead_code)]
#[derive(Debug, Copy, Clone)]
pub enum Compiler {
Cranelift,
LLVM,
Singlepass,
}
impl Compiler {
// TODO: make this `const fn` when Wasmer moves to Rust 1.46.0+
pub fn to_flag(self) -> &'static str {
match self {
Compiler::Cranelift => "--cranelift",
Compiler::LLVM => "--llvm",
Compiler::Singlepass => "--singlepass",
}
}
}
/// Data used to run the `wasmer compile` command.
#[derive(Debug)]
struct WasmerCompile {
/// Path to wasmer executable used to run the command.
wasmer_path: PathBuf,
/// Path to the Wasm file to compile.
wasm_path: PathBuf,
/// Path to the object file produced by compiling the Wasm.
wasm_object_path: PathBuf,
/// Path to output the generated header to.
header_output_path: PathBuf,
/// Compiler with which to compile the Wasm.
compiler: Compiler,
/// Engine with which to use to generate the artifacts.
engine: Engine,
}
impl Default for WasmerCompile {
fn default() -> Self {
#[cfg(not(windows))]
let wasm_obj_path = "wasm.o";
#[cfg(windows)]
let wasm_obj_path = "wasm.obj";
Self {
wasmer_path: get_wasmer_path(),
wasm_path: PathBuf::from(OBJECT_FILE_ENGINE_TEST_WASM_PATH),
wasm_object_path: PathBuf::from(wasm_obj_path),
header_output_path: PathBuf::from("my_wasm.h"),
compiler: Compiler::Cranelift,
engine: Engine::ObjectFile,
}
}
}
impl WasmerCompile {
fn run(&self) -> anyhow::Result<()> {
let output = Command::new(&self.wasmer_path)
.arg("compile")
.arg(&self.wasm_path.canonicalize()?)
.arg(&self.compiler.to_flag())
.arg(&self.engine.to_flag())
.arg("-o")
.arg(&self.wasm_object_path)
.arg("--header")
.arg(&self.header_output_path)
.output()?;
if !output.status.success() {
bail!(
"wasmer compile failed with: stdout: {}\n\nstderr: {}",
std::str::from_utf8(&output.stdout)
.expect("stdout is not utf8! need to handle arbitrary bytes"),
std::str::from_utf8(&output.stderr)
.expect("stderr is not utf8! need to handle arbitrary bytes")
);
}
Ok(())
}
}
/// Compile the C code.
fn run_c_compile(path_to_c_src: &Path, output_name: &Path) -> anyhow::Result<()> {
#[cfg(not(windows))]
let c_compiler = "cc";
#[cfg(windows)]
let c_compiler = "clang++";
let output = Command::new(c_compiler)
.arg("-O2")
.arg("-c")
.arg(path_to_c_src)
.arg("-I")
.arg(CLI_INTEGRATION_TESTS_ASSETS)
.arg("-o")
.arg(output_name)
.output()?;
if !output.status.success() {
bail!(
"C code compile failed with: stdout: {}\n\nstderr: {}",
std::str::from_utf8(&output.stdout)
.expect("stdout is not utf8! need to handle arbitrary bytes"),
std::str::from_utf8(&output.stderr)
.expect("stderr is not utf8! need to handle arbitrary bytes")
);
}
Ok(())
}
/// Data used to run a linking command for generated artifacts.
#[derive(Debug)]
struct LinkCode {
/// Path to the linker used to run the linking command.
linker_path: PathBuf,
/// String used as an optimization flag.
optimization_flag: String,
/// Paths of objects to link.
object_paths: Vec<PathBuf>,
/// Path to the output target.
output_path: PathBuf,
/// Path to the static libwasmer library.
libwasmer_path: PathBuf,
}
impl Default for LinkCode {
fn default() -> Self {
#[cfg(not(windows))]
let linker = "cc";
#[cfg(windows)]
let linker = "clang";
Self {
linker_path: PathBuf::from(linker),
optimization_flag: String::from("-O2"),
object_paths: vec![],
output_path: PathBuf::from("a.out"),
libwasmer_path: get_libwasmer_path(),
}
}
}
impl LinkCode {
fn run(&self) -> anyhow::Result<()> {
let mut command = Command::new(&self.linker_path);
let command = command
.arg(&self.optimization_flag)
.args(
self.object_paths
.iter()
.map(|path| path.canonicalize().unwrap()),
)
.arg(&self.libwasmer_path.canonicalize()?);
#[cfg(windows)]
let command = command.arg("-luserenv").arg("-lWs2_32").arg("-ladvapi32");
#[cfg(not(windows))]
let command = command.arg("-ldl").arg("-lm").arg("-pthread");
let output = command.arg("-o").arg(&self.output_path).output()?;
if !output.status.success() {
bail!(
"linking failed with: stdout: {}\n\nstderr: {}",
std::str::from_utf8(&output.stdout)
.expect("stdout is not utf8! need to handle arbitrary bytes"),
std::str::from_utf8(&output.stderr)
.expect("stderr is not utf8! need to handle arbitrary bytes")
);
}
Ok(())
}
}
fn run_code(executable_path: &Path) -> anyhow::Result<String> {
let output = Command::new(executable_path.canonicalize()?).output()?;
if !output.status.success() {
bail!(
"running executable failed: stdout: {}\n\nstderr: {}",
std::str::from_utf8(&output.stdout)
.expect("stdout is not utf8! need to handle arbitrary bytes"),
std::str::from_utf8(&output.stderr)
.expect("stderr is not utf8! need to handle arbitrary bytes")
);
}
let output =
std::str::from_utf8(&output.stdout).expect("output from running executable is not utf-8");
Ok(output.to_owned())
}
#[test]
fn object_file_engine_works() -> anyhow::Result<()> {
let operating_dir = tempfile::tempdir()?;
std::env::set_current_dir(&operating_dir)?;
let wasm_path = PathBuf::from(OBJECT_FILE_ENGINE_TEST_WASM_PATH);
#[cfg(not(windows))]
let wasm_object_path = PathBuf::from("wasm.o");
#[cfg(windows)]
let wasm_object_path = PathBuf::from("wasm.obj");
let header_output_path = PathBuf::from("my_wasm.h");
WasmerCompile {
wasm_path: wasm_path.clone(),
wasm_object_path: wasm_object_path.clone(),
header_output_path,
compiler: Compiler::Cranelift,
engine: Engine::ObjectFile,
..Default::default()
}
.run()
.context("Failed to compile wasm with Wasmer")?;
let c_src_file_name = Path::new("c_src.c");
#[cfg(not(windows))]
let c_object_path = PathBuf::from("c_src.o");
#[cfg(windows)]
let c_object_path = PathBuf::from("c_src.obj");
let executable_path = PathBuf::from("a.out");
// TODO: adjust C source code based on locations of things
{
let mut c_src_file = fs::OpenOptions::new()
.create_new(true)
.write(true)
.open(&c_src_file_name)
.context("Failed to open C source code file")?;
c_src_file.write_all(OBJECT_FILE_ENGINE_TEST_C_SOURCE)?;
}
run_c_compile(&c_src_file_name, &c_object_path).context("Failed to compile C source code")?;
LinkCode {
object_paths: vec![c_object_path, wasm_object_path],
output_path: executable_path.clone(),
..Default::default()
}
.run()
.context("Failed to link objects together")?;
let result = run_code(&executable_path).context("Failed to run generated executable")?;
let result_lines = result.lines().collect::<Vec<&str>>();
assert_eq!(result_lines, vec!["Initializing...", "\"Hello, World\""],);
Ok(())
}
|
extern crate cc;
extern crate which;
use std::env;
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
const ENV_LLVM_PREFIX: &'static str = "LLVM_PREFIX";
const ENV_LLVM_BUILD_STATIC: &'static str = "LLVM_BUILD_STATIC";
const ENV_LLVM_LINK_LLVM_DYLIB: &'static str = "LLVM_LINK_LLVM_DYLIB";
const ENV_FIREFLY_LLVM_LTO: &'static str = "FIREFLY_LLVM_LTO";
const ENV_LLVM_USE_SANITIZER: &'static str = "LLVM_USE_SANITIZER";
fn main() {
let cwd = env::current_dir().unwrap();
let llvm_prefix = detect_llvm_prefix();
let llvm_lib_dir = llvm_prefix.join("lib");
println!("cargo:rerun-if-env-changed={}", ENV_LLVM_PREFIX);
println!("cargo:rerun-if-env-changed={}", ENV_LLVM_BUILD_STATIC);
println!("cargo:rerun-if-env-changed={}", ENV_LLVM_LINK_LLVM_DYLIB);
println!("cargo:rerun-if-env-changed={}", ENV_FIREFLY_LLVM_LTO);
println!("cargo:rerun-if-env-changed={}", ENV_LLVM_USE_SANITIZER);
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=c_src");
println!("cargo:prefix={}", llvm_prefix.display());
let target = env::var("TARGET").expect("TARGET was not set");
let host = env::var("HOST").expect("HOST was not set");
let is_crossed = target != host;
let llvm_link_llvm_dylib = env::var(ENV_LLVM_LINK_LLVM_DYLIB).unwrap_or("OFF".to_owned());
let llvm_config = llvm_prefix.as_path().join("bin/llvm-config").to_path_buf();
let optional_components = vec![
"x86",
//"arm",
"aarch64",
//"amdgpu",
//"mips",
//"powerpc",
//"systemz",
"webassembly",
//"msp430",
//"sparc",
//"nvptx",
//"hexagon",
//"riscv",
];
let required_components = &[
"core",
"ipo",
"bitreader",
"bitwriter",
"linker",
"asmparser",
"lto",
"instrumentation",
//"orcjit",
];
let components = output(Command::new(&llvm_config).arg("--components"));
let mut components = components.split_whitespace().collect::<Vec<_>>();
components.retain(|c| optional_components.contains(c) || required_components.contains(c));
for component in required_components {
if !components.contains(component) {
panic!("require llvm component {} but wasn't found", component);
}
}
// Link in our own LLVM shims, compiled with the same flags as LLVM
let mut cmd = Command::new(&llvm_config);
cmd.arg("--cxxflags");
let cxxflags = output(&mut cmd);
let mut shared_cxxflags = Vec::with_capacity(cxxflags.len());
let mut cfg = cc::Build::new();
cfg.warnings(false);
for flag in cxxflags.split_whitespace() {
// Ignore flags like `-m64` when we're doing a cross build
if is_crossed && flag.starts_with("-m") {
continue;
}
if flag.starts_with("-flto") {
continue;
}
// -Wdate-time is not supported by the netbsd cross compiler
if is_crossed && target.contains("netbsd") && flag.contains("date-time") {
continue;
}
shared_cxxflags.push(flag);
cfg.flag(flag);
}
println!("cargo:cxxflags={}", shared_cxxflags.as_slice().join(";"));
for component in &components {
let mut flag = String::from("LLVM_COMPONENT_");
flag.push_str(&component.to_uppercase());
cfg.define(&flag, None);
}
if env::var(ENV_FIREFLY_LLVM_LTO).unwrap_or("OFF".to_string()) == "ON" {
println!("cargo:lto=true");
cfg.flag("-flto=thin");
} else {
println!("cargo:lto=false");
}
if let Ok(mut sanitizer) = env::var(ENV_LLVM_USE_SANITIZER) {
sanitizer.make_ascii_lowercase();
cfg.flag(&format!("-fsanitize={}", sanitizer));
}
if env::var_os("LLVM_NDEBUG").is_some() {
cfg.define("NDEBUG", None);
cfg.debug(false);
}
let include_dir = cwd.join("c_src/include");
println!("cargo:include={}", include_dir.display());
if cfg!(windows) {
cfg.file("c_src/raw_win32_handle_ostream.cpp");
}
cfg.file("c_src/Archives.cpp")
.file("c_src/Attributes.cpp")
.file("c_src/Diagnostics.cpp")
.file("c_src/ErrorHandling.cpp")
.file("c_src/IR.cpp")
//.file("c_src/Orc.cpp")
.file("c_src/Passes.cpp")
.file("c_src/Target.cpp")
.file("c_src/Version.cpp")
.include(include_dir)
.shared_flag(false)
.static_flag(true)
.cpp(true)
.cpp_link_stdlib(None) // we handle this below
.compile("firefly_llvm_core");
let (llvm_kind, llvm_link_arg) = detect_llvm_link();
let link_static = llvm_kind == "static";
let link_llvm_dylib = llvm_link_llvm_dylib == "ON";
println!("cargo:link_static={}", &link_static);
println!("cargo:link_llvm_dylib={}", &link_llvm_dylib);
println!(
"cargo:rustc-link-arg=-Wl,-rpath={}",
llvm_lib_dir.as_path().display()
);
if !link_static && link_llvm_dylib {
println!("cargo:rustc-link-lib=dylib=LLVM");
} else {
// Link in all LLVM libraries
let mut cmd = Command::new(&llvm_config);
cmd.arg(llvm_link_arg).arg("--libs");
if !is_crossed {
cmd.arg("--system-libs");
}
cmd.args(&components);
for lib in output(&mut cmd).split_whitespace() {
let name = if lib.starts_with("-l") {
&lib[2..]
} else if lib.starts_with('-') {
&lib[1..]
} else if Path::new(lib).exists() {
// On MSVC llvm-config will print the full name to libraries, but
// we're only interested in the name part
let name = Path::new(lib).file_name().unwrap().to_str().unwrap();
name.trim_end_matches(".lib")
} else if lib.ends_with(".lib") {
// Some MSVC libraries just come up with `.lib` tacked on, so chop
// that off
lib.trim_end_matches(".lib")
} else {
continue;
};
// Don't need or want this library, but LLVM's CMake build system
// doesn't provide a way to disable it, so filter it here even though we
// may or may not have built it. We don't reference anything from this
// library and it otherwise may just pull in extra dependencies on
// libedit which we don't want
if name == "LLVMLineEditor" {
continue;
}
let kind = if name.starts_with("LLVM") {
llvm_kind
} else {
"dylib"
};
println!("cargo:rustc-link-lib={}={}", kind, name);
}
}
// LLVM ldflags
//
// If we're a cross-compile of LLVM then unfortunately we can't trust these
// ldflags (largely where all the LLVM libs are located). Currently just
// hack around this by replacing the host triple with the target and pray
// that those -L directories are the same!
let mut cmd = Command::new(&llvm_config);
cmd.arg(llvm_link_arg).arg("--ldflags");
let ldflags = output(&mut cmd);
let mut shared_ldflags = Vec::new();
for lib in ldflags.split_whitespace() {
if is_crossed {
if lib.starts_with("-LIBPATH:") {
let path = &lib[9..].replace(&host, &target);
println!("cargo:rustc-link-search=native={}", path);
shared_ldflags.push(path.to_owned());
} else if lib.starts_with("-L") {
let path = &lib[2..].replace(&host, &target);
println!("cargo:rustc-link-search=native={}", path);
shared_ldflags.push(path.to_owned());
}
} else if lib.starts_with("-LIBPATH:") {
let path = &lib[9..];
println!("cargo:rustc-link-search=native={}", path);
shared_ldflags.push(path.to_owned());
} else if lib.starts_with("-l") {
println!("cargo:rustc-link-lib={}", &lib[2..]);
} else if lib.starts_with("-L") {
let path = &lib[2..];
println!("cargo:rustc-link-search=native={}", path);
shared_ldflags.push(path.to_owned());
}
}
// Some LLVM linker flags (-L and -l) may be needed even when linking
// firefly_llvm, for example when using static libc++, we may need to
// manually specify the library search path and -ldl -lpthread as link
// dependencies.
let llvm_linker_flags = env::var_os("LLVM_LINKER_FLAGS");
if let Some(s) = llvm_linker_flags {
for lib in s.into_string().unwrap().split_whitespace() {
if lib.starts_with("-l") {
println!("cargo:rustc-link-lib={}", &lib[2..]);
} else if lib.starts_with("-L") {
let path = &lib[2..];
println!("cargo:rustc-link-search=native={}", path);
shared_ldflags.push(path.to_owned());
}
}
}
println!("cargo:ldflags={}", shared_ldflags.as_slice().join(";"));
let llvm_static_stdcpp = env::var_os("LLVM_STATIC_STDCPP");
let stdcppname = if target.contains("openbsd") {
if target.contains("sparc64") {
"estdc++"
} else {
"c++"
}
} else if target.contains("freebsd") {
"c++"
} else if target.contains("darwin") {
"c++"
} else if target.contains("netbsd") && llvm_static_stdcpp.is_some() {
// NetBSD uses a separate library when relocation is required
"stdc++_pic"
} else {
"stdc++"
};
// C++ runtime library
if !target.contains("msvc") {
if let Some(s) = llvm_static_stdcpp {
assert!(!cxxflags.contains("stdlib=libc++"));
let path = PathBuf::from(s);
println!(
"cargo:rustc-link-search=native={}",
path.parent().unwrap().display()
);
if target.contains("windows") {
println!("cargo:rustc-link-lib=static-nobundle={}", stdcppname);
} else {
println!("cargo:rustc-link-lib=static={}", stdcppname);
}
} else if cxxflags.contains("stdlib=libc++") {
println!("cargo:rustc-link-lib=c++");
} else {
println!("cargo:rustc-link-lib={}", stdcppname);
}
}
// LLVM requires symbols from this library, but apparently they're not printed
// during llvm-config?
if target.contains("windows-gnu") {
println!("cargo:rustc-link-lib=static-nobundle=gcc_s");
println!("cargo:rustc-link-lib=static-nobundle=pthread");
println!("cargo:rustc-link-lib=dylib=uuid");
}
}
fn detect_llvm_prefix() -> PathBuf {
if let Ok(prefix) = env::var(ENV_LLVM_PREFIX) {
return PathBuf::from(prefix);
}
if let Ok(llvm_config) = which::which("llvm-config") {
let mut cmd = Command::new(llvm_config);
cmd.arg("--prefix");
return PathBuf::from(output(&mut cmd));
}
let mut llvm_prefix = env::var("XDG_DATA_HOME")
.map(|s| PathBuf::from(s))
.unwrap_or_else(|_| {
let mut home = PathBuf::from(env::var("HOME").expect("HOME not defined"));
home.push(".local/share");
home
});
llvm_prefix.push("llvm");
if llvm_prefix.exists() {
// Make sure its actually the prefix and not a root
let llvm_bin = llvm_prefix.as_path().join("bin");
if llvm_bin.exists() {
return llvm_prefix;
}
let firefly = llvm_prefix.as_path().join("firefly");
if firefly.exists() {
return firefly.to_path_buf();
}
}
fail("LLVM_PREFIX is not defined and unable to locate LLVM to build with");
}
fn output(cmd: &mut Command) -> String {
let output = match cmd.stderr(Stdio::inherit()).output() {
Ok(status) => status,
Err(e) => fail(&format!(
"failed to execute command: {:?}\nerror: {}",
cmd, e
)),
};
if !output.status.success() {
panic!(
"command did not execute successfully: {:?}\n\
expected success, got: {}",
cmd, output.status
);
}
String::from_utf8(output.stdout).unwrap()
}
fn detect_llvm_link() -> (&'static str, &'static str) {
// Force the link mode we want, preferring static by default, but
match env::var_os(ENV_LLVM_BUILD_STATIC) {
Some(val) if val == "ON" => ("static", "--link-static"),
_ => ("dylib", "--link-shared"),
}
}
fn fail(s: &str) -> ! {
panic!("\n{}\n\nbuild script failed, must exit now", s)
}
|
use trayicon::*;
use std::sync::mpsc::{ Receiver };
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub enum Events {
Click,
ShowOnlineInfo,
About,
Exit,
}
/// 트레이 아이콘 생성.
pub fn new() -> (TrayIcon<Events>, Receiver<Events>) {
let (s, r) = std::sync::mpsc::channel::<Events>();
let icon_bytes = include_bytes!("ribbon.ico");
let tray_icon = TrayIconBuilder::new()
.sender(s)
.icon_from_buffer(icon_bytes)
.tooltip("Remember 0416")
.on_click(Events::Click)
// .on_double_click(Events::DoubleClick)
.menu(
MenuBuilder::new()
.item("세월호 침몰 사고 정보(나무위키)", Events::ShowOnlineInfo)
.item("프로그램 정보", Events::About)
.separator()
.item("종료", Events::Exit)
)
.build()
.unwrap();
(tray_icon, r)
}
|
#[doc = "Reader of register DMARIS"]
pub type R = crate::R<u32, super::DMARIS>;
#[doc = "Writer for register DMARIS"]
pub type W = crate::W<u32, super::DMARIS>;
#[doc = "Register DMARIS `reset()`'s with value 0"]
impl crate::ResetValue for super::DMARIS {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TI`"]
pub type TI_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TI`"]
pub struct TI_W<'a> {
w: &'a mut W,
}
impl<'a> TI_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 `TPS`"]
pub type TPS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TPS`"]
pub struct TPS_W<'a> {
w: &'a mut W,
}
impl<'a> TPS_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 `TU`"]
pub type TU_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TU`"]
pub struct TU_W<'a> {
w: &'a mut W,
}
impl<'a> TU_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 `TJT`"]
pub type TJT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TJT`"]
pub struct TJT_W<'a> {
w: &'a mut W,
}
impl<'a> TJT_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 `OVF`"]
pub type OVF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OVF`"]
pub struct OVF_W<'a> {
w: &'a mut W,
}
impl<'a> OVF_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 `UNF`"]
pub type UNF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `UNF`"]
pub struct UNF_W<'a> {
w: &'a mut W,
}
impl<'a> UNF_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 = "Reader of field `RI`"]
pub type RI_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RI`"]
pub struct RI_W<'a> {
w: &'a mut W,
}
impl<'a> RI_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `RU`"]
pub type RU_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RU`"]
pub struct RU_W<'a> {
w: &'a mut W,
}
impl<'a> RU_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `RPS`"]
pub type RPS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RPS`"]
pub struct RPS_W<'a> {
w: &'a mut W,
}
impl<'a> RPS_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `RWT`"]
pub type RWT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RWT`"]
pub struct RWT_W<'a> {
w: &'a mut W,
}
impl<'a> RWT_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 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `ETI`"]
pub type ETI_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ETI`"]
pub struct ETI_W<'a> {
w: &'a mut W,
}
impl<'a> ETI_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 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `FBI`"]
pub type FBI_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FBI`"]
pub struct FBI_W<'a> {
w: &'a mut W,
}
impl<'a> FBI_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `ERI`"]
pub type ERI_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ERI`"]
pub struct ERI_W<'a> {
w: &'a mut W,
}
impl<'a> ERI_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `AIS`"]
pub type AIS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `AIS`"]
pub struct AIS_W<'a> {
w: &'a mut W,
}
impl<'a> AIS_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `NIS`"]
pub type NIS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `NIS`"]
pub struct NIS_W<'a> {
w: &'a mut W,
}
impl<'a> NIS_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 = "Received Process State\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum RS_A {
#[doc = "0: Stopped: Reset or stop receive command issued"]
STOP = 0,
#[doc = "1: Running: Fetching receive transfer descriptor"]
RUNRXTD = 1,
#[doc = "3: Running: Waiting for receive packet"]
RUNRXD = 3,
#[doc = "4: Suspended: Receive descriptor unavailable"]
SUSPEND = 4,
#[doc = "5: Running: Closing receive descriptor"]
RUNCRD = 5,
#[doc = "6: Writing Timestamp"]
TSWS = 6,
#[doc = "7: Running: Transferring the receive packet data from receive buffer to host memory"]
RUNTXD = 7,
}
impl From<RS_A> for u8 {
#[inline(always)]
fn from(variant: RS_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `RS`"]
pub type RS_R = crate::R<u8, RS_A>;
impl RS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, RS_A> {
use crate::Variant::*;
match self.bits {
0 => Val(RS_A::STOP),
1 => Val(RS_A::RUNRXTD),
3 => Val(RS_A::RUNRXD),
4 => Val(RS_A::SUSPEND),
5 => Val(RS_A::RUNCRD),
6 => Val(RS_A::TSWS),
7 => Val(RS_A::RUNTXD),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `STOP`"]
#[inline(always)]
pub fn is_stop(&self) -> bool {
*self == RS_A::STOP
}
#[doc = "Checks if the value of the field is `RUNRXTD`"]
#[inline(always)]
pub fn is_runrxtd(&self) -> bool {
*self == RS_A::RUNRXTD
}
#[doc = "Checks if the value of the field is `RUNRXD`"]
#[inline(always)]
pub fn is_runrxd(&self) -> bool {
*self == RS_A::RUNRXD
}
#[doc = "Checks if the value of the field is `SUSPEND`"]
#[inline(always)]
pub fn is_suspend(&self) -> bool {
*self == RS_A::SUSPEND
}
#[doc = "Checks if the value of the field is `RUNCRD`"]
#[inline(always)]
pub fn is_runcrd(&self) -> bool {
*self == RS_A::RUNCRD
}
#[doc = "Checks if the value of the field is `TSWS`"]
#[inline(always)]
pub fn is_tsws(&self) -> bool {
*self == RS_A::TSWS
}
#[doc = "Checks if the value of the field is `RUNTXD`"]
#[inline(always)]
pub fn is_runtxd(&self) -> bool {
*self == RS_A::RUNTXD
}
}
#[doc = "Write proxy for field `RS`"]
pub struct RS_W<'a> {
w: &'a mut W,
}
impl<'a> RS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RS_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Stopped: Reset or stop receive command issued"]
#[inline(always)]
pub fn stop(self) -> &'a mut W {
self.variant(RS_A::STOP)
}
#[doc = "Running: Fetching receive transfer descriptor"]
#[inline(always)]
pub fn runrxtd(self) -> &'a mut W {
self.variant(RS_A::RUNRXTD)
}
#[doc = "Running: Waiting for receive packet"]
#[inline(always)]
pub fn runrxd(self) -> &'a mut W {
self.variant(RS_A::RUNRXD)
}
#[doc = "Suspended: Receive descriptor unavailable"]
#[inline(always)]
pub fn suspend(self) -> &'a mut W {
self.variant(RS_A::SUSPEND)
}
#[doc = "Running: Closing receive descriptor"]
#[inline(always)]
pub fn runcrd(self) -> &'a mut W {
self.variant(RS_A::RUNCRD)
}
#[doc = "Writing Timestamp"]
#[inline(always)]
pub fn tsws(self) -> &'a mut W {
self.variant(RS_A::TSWS)
}
#[doc = "Running: Transferring the receive packet data from receive buffer to host memory"]
#[inline(always)]
pub fn runtxd(self) -> &'a mut W {
self.variant(RS_A::RUNTXD)
}
#[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 << 17)) | (((value as u32) & 0x07) << 17);
self.w
}
}
#[doc = "Transmit Process State\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum TS_A {
#[doc = "0: Stopped; Reset or Stop transmit command processed"]
STOP = 0,
#[doc = "1: Running; Fetching transmit transfer descriptor"]
RUNTXTD = 1,
#[doc = "2: Running; Waiting for status"]
STATUS = 2,
#[doc = "3: Running; Reading data from host memory buffer and queuing it to transmit buffer (TX FIFO)"]
RUNTX = 3,
#[doc = "4: Writing Timestamp"]
TSTAMP = 4,
#[doc = "6: Suspended; Transmit descriptor unavailable or transmit buffer underflow"]
SUSPEND = 6,
#[doc = "7: Running; Closing transmit descriptor"]
RUNCTD = 7,
}
impl From<TS_A> for u8 {
#[inline(always)]
fn from(variant: TS_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `TS`"]
pub type TS_R = crate::R<u8, TS_A>;
impl TS_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, TS_A> {
use crate::Variant::*;
match self.bits {
0 => Val(TS_A::STOP),
1 => Val(TS_A::RUNTXTD),
2 => Val(TS_A::STATUS),
3 => Val(TS_A::RUNTX),
4 => Val(TS_A::TSTAMP),
6 => Val(TS_A::SUSPEND),
7 => Val(TS_A::RUNCTD),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `STOP`"]
#[inline(always)]
pub fn is_stop(&self) -> bool {
*self == TS_A::STOP
}
#[doc = "Checks if the value of the field is `RUNTXTD`"]
#[inline(always)]
pub fn is_runtxtd(&self) -> bool {
*self == TS_A::RUNTXTD
}
#[doc = "Checks if the value of the field is `STATUS`"]
#[inline(always)]
pub fn is_status(&self) -> bool {
*self == TS_A::STATUS
}
#[doc = "Checks if the value of the field is `RUNTX`"]
#[inline(always)]
pub fn is_runtx(&self) -> bool {
*self == TS_A::RUNTX
}
#[doc = "Checks if the value of the field is `TSTAMP`"]
#[inline(always)]
pub fn is_tstamp(&self) -> bool {
*self == TS_A::TSTAMP
}
#[doc = "Checks if the value of the field is `SUSPEND`"]
#[inline(always)]
pub fn is_suspend(&self) -> bool {
*self == TS_A::SUSPEND
}
#[doc = "Checks if the value of the field is `RUNCTD`"]
#[inline(always)]
pub fn is_runctd(&self) -> bool {
*self == TS_A::RUNCTD
}
}
#[doc = "Write proxy for field `TS`"]
pub struct TS_W<'a> {
w: &'a mut W,
}
impl<'a> TS_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: TS_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Stopped; Reset or Stop transmit command processed"]
#[inline(always)]
pub fn stop(self) -> &'a mut W {
self.variant(TS_A::STOP)
}
#[doc = "Running; Fetching transmit transfer descriptor"]
#[inline(always)]
pub fn runtxtd(self) -> &'a mut W {
self.variant(TS_A::RUNTXTD)
}
#[doc = "Running; Waiting for status"]
#[inline(always)]
pub fn status(self) -> &'a mut W {
self.variant(TS_A::STATUS)
}
#[doc = "Running; Reading data from host memory buffer and queuing it to transmit buffer (TX FIFO)"]
#[inline(always)]
pub fn runtx(self) -> &'a mut W {
self.variant(TS_A::RUNTX)
}
#[doc = "Writing Timestamp"]
#[inline(always)]
pub fn tstamp(self) -> &'a mut W {
self.variant(TS_A::TSTAMP)
}
#[doc = "Suspended; Transmit descriptor unavailable or transmit buffer underflow"]
#[inline(always)]
pub fn suspend(self) -> &'a mut W {
self.variant(TS_A::SUSPEND)
}
#[doc = "Running; Closing transmit descriptor"]
#[inline(always)]
pub fn runctd(self) -> &'a mut W {
self.variant(TS_A::RUNCTD)
}
#[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 << 20)) | (((value as u32) & 0x07) << 20);
self.w
}
}
#[doc = "Access Error\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
#[repr(u8)]
pub enum AE_A {
#[doc = "0: Error during RX DMA Write Data Transfer"]
RXDMAWD = 0,
#[doc = "3: Error during TX DMA Read Data Transfer"]
TXDMARD = 3,
#[doc = "4: Error during RX DMA Descriptor Write Access"]
RXDMADW = 4,
#[doc = "5: Error during TX DMA Descriptor Write Access"]
TXDMADW = 5,
#[doc = "6: Error during RX DMA Descriptor Read Access"]
RXDMADR = 6,
#[doc = "7: Error during TX DMA Descriptor Read Access"]
TXDMADR = 7,
}
impl From<AE_A> for u8 {
#[inline(always)]
fn from(variant: AE_A) -> Self {
variant as _
}
}
#[doc = "Reader of field `AE`"]
pub type AE_R = crate::R<u8, AE_A>;
impl AE_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> crate::Variant<u8, AE_A> {
use crate::Variant::*;
match self.bits {
0 => Val(AE_A::RXDMAWD),
3 => Val(AE_A::TXDMARD),
4 => Val(AE_A::RXDMADW),
5 => Val(AE_A::TXDMADW),
6 => Val(AE_A::RXDMADR),
7 => Val(AE_A::TXDMADR),
i => Res(i),
}
}
#[doc = "Checks if the value of the field is `RXDMAWD`"]
#[inline(always)]
pub fn is_rxdmawd(&self) -> bool {
*self == AE_A::RXDMAWD
}
#[doc = "Checks if the value of the field is `TXDMARD`"]
#[inline(always)]
pub fn is_txdmard(&self) -> bool {
*self == AE_A::TXDMARD
}
#[doc = "Checks if the value of the field is `RXDMADW`"]
#[inline(always)]
pub fn is_rxdmadw(&self) -> bool {
*self == AE_A::RXDMADW
}
#[doc = "Checks if the value of the field is `TXDMADW`"]
#[inline(always)]
pub fn is_txdmadw(&self) -> bool {
*self == AE_A::TXDMADW
}
#[doc = "Checks if the value of the field is `RXDMADR`"]
#[inline(always)]
pub fn is_rxdmadr(&self) -> bool {
*self == AE_A::RXDMADR
}
#[doc = "Checks if the value of the field is `TXDMADR`"]
#[inline(always)]
pub fn is_txdmadr(&self) -> bool {
*self == AE_A::TXDMADR
}
}
#[doc = "Write proxy for field `AE`"]
pub struct AE_W<'a> {
w: &'a mut W,
}
impl<'a> AE_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: AE_A) -> &'a mut W {
unsafe { self.bits(variant.into()) }
}
#[doc = "Error during RX DMA Write Data Transfer"]
#[inline(always)]
pub fn rxdmawd(self) -> &'a mut W {
self.variant(AE_A::RXDMAWD)
}
#[doc = "Error during TX DMA Read Data Transfer"]
#[inline(always)]
pub fn txdmard(self) -> &'a mut W {
self.variant(AE_A::TXDMARD)
}
#[doc = "Error during RX DMA Descriptor Write Access"]
#[inline(always)]
pub fn rxdmadw(self) -> &'a mut W {
self.variant(AE_A::RXDMADW)
}
#[doc = "Error during TX DMA Descriptor Write Access"]
#[inline(always)]
pub fn txdmadw(self) -> &'a mut W {
self.variant(AE_A::TXDMADW)
}
#[doc = "Error during RX DMA Descriptor Read Access"]
#[inline(always)]
pub fn rxdmadr(self) -> &'a mut W {
self.variant(AE_A::RXDMADR)
}
#[doc = "Error during TX DMA Descriptor Read Access"]
#[inline(always)]
pub fn txdmadr(self) -> &'a mut W {
self.variant(AE_A::TXDMADR)
}
#[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 << 23)) | (((value as u32) & 0x07) << 23);
self.w
}
}
#[doc = "Reader of field `MMC`"]
pub type MMC_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MMC`"]
pub struct MMC_W<'a> {
w: &'a mut W,
}
impl<'a> MMC_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 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `PMT`"]
pub type PMT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PMT`"]
pub struct PMT_W<'a> {
w: &'a mut W,
}
impl<'a> PMT_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 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `TT`"]
pub type TT_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TT`"]
pub struct TT_W<'a> {
w: &'a mut W,
}
impl<'a> TT_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 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
impl R {
#[doc = "Bit 0 - Transmit Interrupt"]
#[inline(always)]
pub fn ti(&self) -> TI_R {
TI_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - Transmit Process Stopped"]
#[inline(always)]
pub fn tps(&self) -> TPS_R {
TPS_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - Transmit Buffer Unavailable"]
#[inline(always)]
pub fn tu(&self) -> TU_R {
TU_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Transmit Jabber Timeout"]
#[inline(always)]
pub fn tjt(&self) -> TJT_R {
TJT_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Receive Overflow"]
#[inline(always)]
pub fn ovf(&self) -> OVF_R {
OVF_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - Transmit Underflow"]
#[inline(always)]
pub fn unf(&self) -> UNF_R {
UNF_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - Receive Interrupt"]
#[inline(always)]
pub fn ri(&self) -> RI_R {
RI_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - Receive Buffer Unavailable"]
#[inline(always)]
pub fn ru(&self) -> RU_R {
RU_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - Receive Process Stopped"]
#[inline(always)]
pub fn rps(&self) -> RPS_R {
RPS_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - Receive Watchdog Timeout"]
#[inline(always)]
pub fn rwt(&self) -> RWT_R {
RWT_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - Early Transmit Interrupt"]
#[inline(always)]
pub fn eti(&self) -> ETI_R {
ETI_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 13 - Fatal Bus Error Interrupt"]
#[inline(always)]
pub fn fbi(&self) -> FBI_R {
FBI_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - Early Receive Interrupt"]
#[inline(always)]
pub fn eri(&self) -> ERI_R {
ERI_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - Abnormal Interrupt Summary"]
#[inline(always)]
pub fn ais(&self) -> AIS_R {
AIS_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - Normal Interrupt Summary"]
#[inline(always)]
pub fn nis(&self) -> NIS_R {
NIS_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bits 17:19 - Received Process State"]
#[inline(always)]
pub fn rs(&self) -> RS_R {
RS_R::new(((self.bits >> 17) & 0x07) as u8)
}
#[doc = "Bits 20:22 - Transmit Process State"]
#[inline(always)]
pub fn ts(&self) -> TS_R {
TS_R::new(((self.bits >> 20) & 0x07) as u8)
}
#[doc = "Bits 23:25 - Access Error"]
#[inline(always)]
pub fn ae(&self) -> AE_R {
AE_R::new(((self.bits >> 23) & 0x07) as u8)
}
#[doc = "Bit 27 - MAC MMC Interrupt"]
#[inline(always)]
pub fn mmc(&self) -> MMC_R {
MMC_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - MAC PMT Interrupt Status"]
#[inline(always)]
pub fn pmt(&self) -> PMT_R {
PMT_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - Timestamp Trigger Interrupt Status"]
#[inline(always)]
pub fn tt(&self) -> TT_R {
TT_R::new(((self.bits >> 29) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Transmit Interrupt"]
#[inline(always)]
pub fn ti(&mut self) -> TI_W {
TI_W { w: self }
}
#[doc = "Bit 1 - Transmit Process Stopped"]
#[inline(always)]
pub fn tps(&mut self) -> TPS_W {
TPS_W { w: self }
}
#[doc = "Bit 2 - Transmit Buffer Unavailable"]
#[inline(always)]
pub fn tu(&mut self) -> TU_W {
TU_W { w: self }
}
#[doc = "Bit 3 - Transmit Jabber Timeout"]
#[inline(always)]
pub fn tjt(&mut self) -> TJT_W {
TJT_W { w: self }
}
#[doc = "Bit 4 - Receive Overflow"]
#[inline(always)]
pub fn ovf(&mut self) -> OVF_W {
OVF_W { w: self }
}
#[doc = "Bit 5 - Transmit Underflow"]
#[inline(always)]
pub fn unf(&mut self) -> UNF_W {
UNF_W { w: self }
}
#[doc = "Bit 6 - Receive Interrupt"]
#[inline(always)]
pub fn ri(&mut self) -> RI_W {
RI_W { w: self }
}
#[doc = "Bit 7 - Receive Buffer Unavailable"]
#[inline(always)]
pub fn ru(&mut self) -> RU_W {
RU_W { w: self }
}
#[doc = "Bit 8 - Receive Process Stopped"]
#[inline(always)]
pub fn rps(&mut self) -> RPS_W {
RPS_W { w: self }
}
#[doc = "Bit 9 - Receive Watchdog Timeout"]
#[inline(always)]
pub fn rwt(&mut self) -> RWT_W {
RWT_W { w: self }
}
#[doc = "Bit 10 - Early Transmit Interrupt"]
#[inline(always)]
pub fn eti(&mut self) -> ETI_W {
ETI_W { w: self }
}
#[doc = "Bit 13 - Fatal Bus Error Interrupt"]
#[inline(always)]
pub fn fbi(&mut self) -> FBI_W {
FBI_W { w: self }
}
#[doc = "Bit 14 - Early Receive Interrupt"]
#[inline(always)]
pub fn eri(&mut self) -> ERI_W {
ERI_W { w: self }
}
#[doc = "Bit 15 - Abnormal Interrupt Summary"]
#[inline(always)]
pub fn ais(&mut self) -> AIS_W {
AIS_W { w: self }
}
#[doc = "Bit 16 - Normal Interrupt Summary"]
#[inline(always)]
pub fn nis(&mut self) -> NIS_W {
NIS_W { w: self }
}
#[doc = "Bits 17:19 - Received Process State"]
#[inline(always)]
pub fn rs(&mut self) -> RS_W {
RS_W { w: self }
}
#[doc = "Bits 20:22 - Transmit Process State"]
#[inline(always)]
pub fn ts(&mut self) -> TS_W {
TS_W { w: self }
}
#[doc = "Bits 23:25 - Access Error"]
#[inline(always)]
pub fn ae(&mut self) -> AE_W {
AE_W { w: self }
}
#[doc = "Bit 27 - MAC MMC Interrupt"]
#[inline(always)]
pub fn mmc(&mut self) -> MMC_W {
MMC_W { w: self }
}
#[doc = "Bit 28 - MAC PMT Interrupt Status"]
#[inline(always)]
pub fn pmt(&mut self) -> PMT_W {
PMT_W { w: self }
}
#[doc = "Bit 29 - Timestamp Trigger Interrupt Status"]
#[inline(always)]
pub fn tt(&mut self) -> TT_W {
TT_W { w: self }
}
}
|
use crate::ast;
use crate::{Spanned, ToTokens};
/// A return statement `<expr>.await`.
///
/// # Examples
///
/// ```rust
/// use rune::{testing, ast};
///
/// testing::roundtrip::<ast::Expr>("(42).await");
/// testing::roundtrip::<ast::Expr>("self.await");
/// testing::roundtrip::<ast::Expr>("test.await");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, ToTokens, Spanned)]
pub struct ExprAwait {
/// Attributes associated with expression.
#[rune(iter)]
pub attributes: Vec<ast::Attribute>,
/// The expression being awaited.
pub expr: ast::Expr,
/// The dot separating the expression.
pub dot: T![.],
/// The await token.
pub await_token: T![await],
}
expr_parse!(Await, ExprAwait, ".await expression");
|
use super::{BlockTimestamp, TimePointSec};
use crate::bytes::{NumBytes, Read, Write};
use core::convert::{TryFrom, TryInto};
use core::fmt;
use core::num::TryFromIntError;
/// High resolution time point in microseconds
/// <https://github.com/EOSIO/eosio.cdt/blob/4985359a30da1f883418b7133593f835927b8046/libraries/eosiolib/core/eosio/time.hpp#L49-L77>
#[derive(
Read,
Write,
NumBytes,
PartialEq,
Eq,
PartialOrd,
Ord,
Debug,
Clone,
Copy,
Hash,
Default,
)]
#[eosio(crate_path = "crate::bytes")]
pub struct TimePoint(i64);
impl TimePoint {
#[inline]
#[must_use]
pub const fn from_micros(micros: i64) -> Self {
Self(micros)
}
#[inline]
#[must_use]
pub const fn from_millis(millis: i64) -> Self {
Self::from_micros(millis * 1_000)
}
/// Gets the microseconds
#[inline]
#[must_use]
pub const fn as_micros(&self) -> i64 {
self.0
}
/// Gets the milliseconds
#[inline]
#[must_use]
pub const fn as_millis(&self) -> i64 {
self.0 / 1_000
}
#[inline]
#[must_use]
pub const fn as_secs(&self) -> i32 {
(self.0 / 1_000_000) as i32
}
#[inline]
#[must_use]
pub const fn as_time_point_sec(&self) -> TimePointSec {
TimePointSec::from_secs(self.as_secs() as u32)
}
}
impl From<i64> for TimePoint {
#[inline]
#[must_use]
fn from(i: i64) -> Self {
Self(i)
}
}
impl From<TimePoint> for i64 {
#[inline]
#[must_use]
fn from(t: TimePoint) -> Self {
t.0
}
}
impl TryFrom<u64> for TimePoint {
type Error = TryFromIntError;
#[inline]
fn try_from(i: u64) -> Result<Self, Self::Error> {
Ok(i64::try_from(i)?.into())
}
}
impl TryFrom<TimePoint> for u64 {
type Error = TryFromIntError;
#[inline]
fn try_from(t: TimePoint) -> Result<Self, Self::Error> {
t.as_micros().try_into()
}
}
|
// Based on t-1.xsd
// targetNamespace = "http://docs.oasis-open.org/wsn/t-1"
// xmlns:xsd="http://www.w3.org/2001/XMLSchema"
// xmlns:wstop = "http://docs.oasis-open.org/wsn/t-1"
use std::io::{Read, Write};
use yaserde::{YaDeserialize, YaSerialize};
|
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
use std::marker;
struct Invariant<'a> {
marker: marker::PhantomData<*mut &'a()>
}
fn to_same_lifetime<'r>(b_isize: Invariant<'r>) {
let bj: Invariant<'r> = b_isize;
}
fn to_longer_lifetime<'r>(b_isize: Invariant<'r>) -> Invariant<'static> {
b_isize
//[base]~^ ERROR mismatched types
//[nll]~^^ ERROR lifetime may not live long enough
}
fn main() {
}
|
#[doc = "Reader of register CFGR"]
pub type R = crate::R<u32, super::CFGR>;
#[doc = "Writer for register CFGR"]
pub type W = crate::W<u32, super::CFGR>;
#[doc = "Register CFGR `reset()`'s with value 0"]
impl crate::ResetValue for super::CFGR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SEL`"]
pub type SEL_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `SEL`"]
pub struct SEL_W<'a> {
w: &'a mut W,
}
impl<'a> SEL_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f);
self.w
}
}
#[doc = "Reader of field `UNIT`"]
pub type UNIT_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `UNIT`"]
pub struct UNIT_W<'a> {
w: &'a mut W,
}
impl<'a> UNIT_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x7f << 8)) | (((value as u32) & 0x7f) << 8);
self.w
}
}
#[doc = "Reader of field `LNG`"]
pub type LNG_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `LNG`"]
pub struct LNG_W<'a> {
w: &'a mut W,
}
impl<'a> LNG_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0fff << 16)) | (((value as u32) & 0x0fff) << 16);
self.w
}
}
#[doc = "Reader of field `LNGF`"]
pub type LNGF_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `LNGF`"]
pub struct LNGF_W<'a> {
w: &'a mut W,
}
impl<'a> LNGF_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 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bits 0:3 - Select the phase for the Output clock"]
#[inline(always)]
pub fn sel(&self) -> SEL_R {
SEL_R::new((self.bits & 0x0f) as u8)
}
#[doc = "Bits 8:14 - Delay Defines the delay of a Unit delay cell"]
#[inline(always)]
pub fn unit(&self) -> UNIT_R {
UNIT_R::new(((self.bits >> 8) & 0x7f) as u8)
}
#[doc = "Bits 16:27 - Delay line length value"]
#[inline(always)]
pub fn lng(&self) -> LNG_R {
LNG_R::new(((self.bits >> 16) & 0x0fff) as u16)
}
#[doc = "Bit 31 - Length valid flag"]
#[inline(always)]
pub fn lngf(&self) -> LNGF_R {
LNGF_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:3 - Select the phase for the Output clock"]
#[inline(always)]
pub fn sel(&mut self) -> SEL_W {
SEL_W { w: self }
}
#[doc = "Bits 8:14 - Delay Defines the delay of a Unit delay cell"]
#[inline(always)]
pub fn unit(&mut self) -> UNIT_W {
UNIT_W { w: self }
}
#[doc = "Bits 16:27 - Delay line length value"]
#[inline(always)]
pub fn lng(&mut self) -> LNG_W {
LNG_W { w: self }
}
#[doc = "Bit 31 - Length valid flag"]
#[inline(always)]
pub fn lngf(&mut self) -> LNGF_W {
LNGF_W { w: self }
}
}
|
use libc::c_uint;
use curses;
bitflags! {
flags Attributes: c_uint {
const NORMAL = curses::A_NORMAL,
const COLOR = curses::A_COLOR,
const STANDOUT = curses::A_STANDOUT,
const UNDERLINE = curses::A_UNDERLINE,
const REVERSE = curses::A_REVERSE,
const BLINK = curses::A_BLINK,
const DIM = curses::A_DIM,
const BOLD = curses::A_BOLD,
const ALTERNATE_CHARSET = curses::A_ALTCHARSET,
const INVISIBLE = curses::A_INVIS,
const PROTECTED = curses::A_PROTECT,
const HORIZONTAL = curses::A_HORIZONTAL,
const LEFT = curses::A_LEFT,
const LOW = curses::A_LOW,
const RIGHT = curses::A_RIGHT,
const TOP = curses::A_TOP,
const VERTICAL = curses::A_VERTICAL,
const ITALIC = curses::A_ITALIC,
}
}
|
pub mod hlayout;
pub mod layout;
pub mod str_layout;
pub mod vlayout;
|
/*
Copyright (c) 2015, 2016 Saurav Sachidanand
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#![allow(non_snake_case)]
extern crate astro;
use astro::*;
#[test]
fn ephemeris() {
let (mut P, mut B, mut L) = sun::ephemeris(
2448908.50068,
199.90234_f64.to_radians(),
199.906759_f64.to_radians(),
23.440144_f64.to_radians()
);
P = util::round_upto_digits(P.to_degrees(), 2);
B = util::round_upto_digits(B.to_degrees(), 2);
L = util::round_upto_digits(L.to_degrees(), 2);
assert_eq!((P, B, L), (26.27, 5.99, 238.63));
}
#[test]
fn ecl_coords_to_FK5() {
let (FK5_long, FK5_lat) = sun::ecl_coords_to_FK5(
2448908.5,
199.907372_f64.to_radians(),
angle::deg_frm_dms(0, 0, 0.644).to_radians()
);
assert_eq!(
util::round_upto_digits(FK5_long.to_degrees(), 6),
199.907347
);
let (d, m, s) = angle::dms_frm_deg(FK5_lat.to_degrees());
assert_eq!(
(d, m, util::round_upto_digits(s, 2)),
(0, 0, 0.62)
);
}
#[test]
fn geocent_ecl_coords() {
let (sun_ecl_point, rad_vec) = sun::geocent_ecl_pos(2448908.5);
assert_eq!(
util::round_upto_digits(sun_ecl_point.long.to_degrees(), 6),
199.907297
);
assert_eq!(
util::round_upto_digits(sun_ecl_point.lat.to_degrees(), 6),
0.000207
);
assert_eq!(
util::round_upto_digits(rad_vec, 8),
0.99760852
);
}
#[test]
fn approx_synd_rot() {
assert_eq!(
util::round_upto_digits(sun::synodic_rot(1699), 2),
2444480.72
);
}
|
use std::{
convert::TryInto,
array::TryFromSliceError,
};
const MAGIC_HEADER_STRING: [u8; 16] = [
0x53, 0x51, 0x4c, 0x69, 0x74, 0x65, 0x20, 0x66, 0x6f, 0x72, 0x6d, 0x61, 0x74, 0x20, 0x33, 0x00
];
fn main() -> Result<(), Box<dyn std::error::Error>> {
let contents = std::fs::read("data.sqlite")?;
assert!(contents[0..16] == MAGIC_HEADER_STRING);
println!("MAGIC HEADER STRING: {}", String::from_utf8_lossy(&contents[0..16]));
let bytes: [u8; 2] = contents[16..18].try_into().unwrap();
let page_size = u16::from_be_bytes(bytes);
assert!(page_size.is_power_of_two());
assert!(page_size > 511);
assert!(page_size < 32769);
println!("PAGE SIZE: {}", page_size);
println!("FILE FORMAT WRITE VERSION: {}", match contents[18] {
1 => "legacy",
2 => "Write-Ahead Logging",
_ => unimplemented!(),
});
println!("FILE FORMAT READ VERSION: {}", match contents[19] {
1 => "legacy",
2 => "Write-Ahead Logging",
_ => unimplemented!(),
});
println!("RESERVED BYTES PER PAGE: {}", contents[20]);
assert!(contents[21] == 64);
println!("MAXIMUM EMBEDDED PAYLOAD FRACTION: {}", contents[21]);
assert!(contents[22] == 32);
println!("MINIMUM EMBEDDED PAYLOAD FRACTION: {}", contents[22]);
assert!(contents[23] == 32);
println!("LEAF PAYLOAD FRACTION: {}", contents[23]);
let file_change_counter = slice_to_word(&contents[24..28])?;
println!("FILE CHANGE COUNTER: {}", file_change_counter);
let in_header_database_size = slice_to_word(&contents[28..32])?;
println!("IN-HEADER DATABASE SIZE: {:?}", in_header_database_size);
let freelist_index = slice_to_word(&contents[32..36])?;
println!("FREELIST PAGE INDEX: {}", freelist_index);
let freelist_count = slice_to_word(&contents[36..40])?;
println!("FREELIST COUNT: {}", freelist_count);
let schema_cookie = slice_to_word(&contents[40..44])?;
println!("SCHEMA COOKIE: {}", schema_cookie);
let schema_format = slice_to_word(&contents[44..48])?;
assert!([1, 2, 3, 4].contains(&schema_format));
println!("SCHEMA FORMAT: {}", schema_format);
let default_page_cache_size = slice_to_word(&contents[48..52])?;
println!("DEFAULT PAGE CACHE SIZE: {}", default_page_cache_size);
let btree_largest_page_root = slice_to_word(&contents[52..56])?;
println!("LARGEST ROOT B-TREE PAGE: {}", btree_largest_page_root);
let db_encoding = slice_to_word(&contents[56..60])?;
println!("DATABASE TEXT ENCODING: {}", match db_encoding {
1 => "UTF-8",
2 => "UTF-16le",
3 => "UTF-16be",
_ => unimplemented!(),
});
let user_version = slice_to_word(&contents[60..64])?;
println!("USER VERSION: {}", user_version);
let incremental_vacuum_mode = slice_to_word(&contents[64..68])? != 0;
println!("INCREMENTAL-VACUUM MODE: {}", incremental_vacuum_mode);
let application_id = slice_to_word(&contents[68..72])?;
println!("APPLICATION ID: {}", application_id);
let reserved = &contents[72..92];
assert!(reserved.iter().all(|&v| v == 0));
let version_valid_for_number = slice_to_word(&contents[92..96])?;
println!("VERSION VALID FOR NUMBER: {}", version_valid_for_number);
let sqlite_version_number = slice_to_word(&contents[96..100])?;
println!("SQLITE VERSION NUMBER: {}", sqlite_version_number);
Ok(())
}
fn slice_to_word(slice: &[u8]) -> Result<u32, TryFromSliceError> {
let bytes: [u8; 4] = slice.try_into()?;
Ok(u32::from_be_bytes(bytes))
}
|
//! This module implements the `table` CLI command
use influxdb_iox_client::connection::Connection;
use observability_deps::tracing::info;
use thiserror::Error;
mod create;
#[allow(clippy::enum_variant_names)]
#[derive(Debug, Error)]
pub enum Error {
#[error("JSON Serialization error: {0}")]
Serde(#[from] serde_json::Error),
#[error("Client error: {0}")]
ClientError(#[from] influxdb_iox_client::error::Error),
}
pub type Result<T, E = Error> = std::result::Result<T, E>;
/// Various commands for table inspection
#[derive(Debug, clap::Parser)]
pub struct Config {
#[clap(subcommand)]
command: Command,
}
/// All possible subcommands for table
#[derive(Debug, clap::Parser)]
enum Command {
/// Create a new table
Create(create::Config),
}
pub async fn command(connection: Connection, config: Config) -> Result<()> {
match config.command {
Command::Create(config) => {
info!("Creating table with config: {:?}", config);
create::command(connection, config).await?;
} // Deliberately not adding _ => so the compiler will direct people here to impl new
// commands
}
Ok(())
}
|
use crate::{
convert::{ToPyObject, TryFromObject},
object::{AsObject, PyObjectRef, PyResult},
VirtualMachine,
};
#[derive(result_like::OptionLike)]
pub enum PyArithmeticValue<T> {
Implemented(T),
NotImplemented,
}
impl PyArithmeticValue<PyObjectRef> {
pub fn from_object(vm: &VirtualMachine, obj: PyObjectRef) -> Self {
if obj.is(&vm.ctx.not_implemented) {
Self::NotImplemented
} else {
Self::Implemented(obj)
}
}
}
impl<T: TryFromObject> TryFromObject for PyArithmeticValue<T> {
fn try_from_object(vm: &VirtualMachine, obj: PyObjectRef) -> PyResult<Self> {
PyArithmeticValue::from_object(vm, obj)
.map(|x| T::try_from_object(vm, x))
.transpose()
}
}
impl<T> ToPyObject for PyArithmeticValue<T>
where
T: ToPyObject,
{
fn to_pyobject(self, vm: &VirtualMachine) -> PyObjectRef {
match self {
PyArithmeticValue::Implemented(v) => v.to_pyobject(vm),
PyArithmeticValue::NotImplemented => vm.ctx.not_implemented(),
}
}
}
pub type PyComparisonValue = PyArithmeticValue<bool>;
|
extern crate bulletproofs;
extern crate curve25519_dalek;
extern crate merlin;
extern crate rand;
extern crate subtle;
#[macro_use]
extern crate failure;
mod error;
mod gadgets;
mod spacesuit;
mod value;
pub use error::SpacesuitError;
pub use spacesuit::*;
pub use value::*;
|
// Copyright 2019 Liebi Technologies.
// This file is part of Bifrost.
// Bifrost is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Bifrost is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Bifrost. If not, see <http://www.gnu.org/licenses/>.
use crate::rpc::json_req::REQUEST_TRANSFER;
use log::{debug, error, info};
use std::sync::mpsc::Sender as ThreadOut;
use ws::{CloseCode, Handler, Handshake, Message, Result, Sender};
pub type OnMessageFn = fn(msg: Message, out: Sender, result: ThreadOut<String>) -> Result<()>;
pub struct RpcClient {
pub out: Sender,
pub request: String,
pub result: ThreadOut<String>,
pub on_message_fn: OnMessageFn,
}
impl Handler for RpcClient {
fn on_open(&mut self, _: Handshake) -> Result<()> {
info!("sending request: {}", self.request);
self.out.send(self.request.clone()).unwrap();
Ok(())
}
fn on_message(&mut self, msg: Message) -> Result<()> {
info!("got message");
debug!("{}", msg);
(self.on_message_fn)(msg, self.out.clone(), self.result.clone())
}
}
pub fn on_get_request_msg(msg: Message, out: Sender, result: ThreadOut<String>) -> Result<()> {
let retstr = msg.as_text().unwrap();
let value: serde_json::Value = serde_json::from_str(retstr).unwrap();
result.send(value["result"].to_string()).unwrap();
out.close(CloseCode::Normal).unwrap();
Ok(())
}
pub fn on_subscription_msg(msg: Message, _out: Sender, result: ThreadOut<String>) -> Result<()> {
let retstr = msg.as_text().unwrap();
let value: serde_json::Value = serde_json::from_str(retstr).unwrap();
match value["id"].as_str() {
Some(_idstr) => {}
_ => {
// subscriptions
debug!("no id field found in response. must be subscription");
debug!("method: {:?}", value["method"].as_str());
match value["method"].as_str() {
Some("state_storage") => {
let _changes = &value["params"]["result"]["changes"];
let _res_str = _changes[0][1].as_str().unwrap().to_string();
result.send(_res_str).unwrap();
}
_ => error!("unsupported method"),
}
}
};
Ok(())
}
pub fn on_extrinsic_msg(msg: Message, out: Sender, result: ThreadOut<String>) -> Result<()> {
let retstr = msg.as_text().unwrap();
let value: serde_json::Value = serde_json::from_str(retstr).unwrap();
match value["id"].as_str() {
Some(idstr) => match idstr.parse::<u32>() {
Ok(req_id) => match req_id {
REQUEST_TRANSFER => match value.get("error") {
Some(err) => error!("ERROR: {:?}", err),
_ => debug!("no error"),
},
_ => debug!("Unknown request id"),
},
Err(_) => error!("error assigning request id"),
},
_ => {
// subscriptions
debug!("no id field found in response. must be subscription");
debug!("method: {:?}", value["method"].as_str());
match value["method"].as_str() {
Some("author_extrinsicUpdate") => {
match value["params"]["result"].as_str() {
Some(res) => debug!("author_extrinsicUpdate: {}", res),
_ => {
debug!(
"author_extrinsicUpdate: finalized: {}",
value["params"]["result"]["finalized"].as_str().unwrap()
);
// return result to calling thread
result
.send(
value["params"]["result"]["finalized"]
.as_str()
.unwrap()
.to_string(),
)
.unwrap();
// we've reached the end of the flow. return
out.close(CloseCode::Normal).unwrap();
}
}
}
_ => error!("unsupported method"),
}
}
};
Ok(())
} |
// 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.
extern crate alloc;
// Segment indices and Selectors.
pub const SEG_KCODE : u16 = 1;
pub const SEG_KDATA : u16 = 2;
pub const SEG_UDATA : u16 = 3;
pub const SEG_UCODE64 : u16 = 4;
pub const SEG_TSS : u16 = 5;
pub const SEG_TSS_HI : u16 = 6;
pub const KCODE : u16 = SEG_KCODE << 3;
pub const KDATA : u16 = SEG_KDATA << 3;
pub const UDATA : u16 = (SEG_UDATA << 3) | 3;
pub const UCODE64 : u16 = (SEG_UCODE64 << 3) | 3;
pub const TSS : u16 = SEG_TSS << 3;
pub const CR0_PE : u64 = 1 << 0;
pub const CR0_MP : u64 = 1 << 1;
pub const CR0_EM : u64 = 1 << 2;
pub const CR0_TS : u64 = 1 << 3;
pub const CR0_ET : u64 = 1 << 4;
pub const CR0_NE : u64 = 1 << 5;
pub const CR0_WP : u64 = 1 << 16;
pub const CR0_AM : u64 = 1 << 18;
pub const CR0_NW : u64 = 1 << 29;
pub const CR0_CD : u64 = 1 << 30;
pub const CR0_PG : u64 = 1 << 31;
pub const CR4_PSE : u64 = 1 << 4;
pub const CR4_PAE : u64 = 1 << 5;
pub const CR4_PGE : u64 = 1 << 7;
pub const CR4_OSFXSR : u64 = 1 << 9;
pub const CR4_OSXMMEXCPT : u64 = 1 << 10;
pub const CR4_UMIP : u64 = 1 << 11;
pub const CR4_FSGSBASE : u64 = 1 << 16;
pub const CR4_PCIDE : u64 = 1 << 17;
pub const CR4_OSXSAVE : u64 = 1 << 18;
pub const CR4_SMEP : u64 = 1 << 20;
pub const CR4_SMAP : u64 = 1 << 21;
pub const RFLAGS_AC : u64 = 1 << 18;
pub const RFLAGS_NT : u64 = 1 << 14;
pub const RFLAGS_IOPL : u64 = 3 << 12;
pub const RFLAGS_DF : u64 = 1 << 10;
pub const RFLAGS_IF : u64 = 1 << 9;
pub const RFLAGS_STEP : u64 = 1 << 8;
pub const RFLAGS_RESERVED : u64 = 1 << 1;
pub const EFER_SCE : u64 = 0x001;
pub const EFER_LME : u64 = 0x100;
pub const EFER_LMA : u64 = 0x400;
pub const EFER_NX : u64 = 0x800;
pub const MSR_STAR : u64 = 0xc0000081;
pub const MSR_LSTAR : u64 = 0xc0000082;
pub const MSR_CSTAR : u64 = 0xc0000083;
pub const MSR_SYSCALL_MASK : u64 = 0xc0000084;
pub const MSR_PLATFORM_INFO : u64 = 0xce;
pub const MSR_MISC_FEATURES : u64 = 0x140;
pub const PLATFORM_INFO_CPUID_FAULT : u64 = 1 << 31;
pub const MISC_FEATURE_CPUID_TRAP : u64 = 0x1;
// KernelFlagsSet should always be set in the kernel.
pub const KERNEL_FLAGS_SET : u64 = RFLAGS_RESERVED;
// UserFlagsSet are always set in userspace.
pub const USER_FLAGS_SET : u64 = RFLAGS_RESERVED | RFLAGS_IF;
// KernelFlagsClear should always be clear in the kernel.
pub const KERNEL_FLAGS_CLEAR : u64 = RFLAGS_STEP | RFLAGS_IF | RFLAGS_IOPL | RFLAGS_AC | RFLAGS_NT;
// UserFlagsClear are always cleared in userspace.
pub const USER_FLAGS_CLEAR : u64 = RFLAGS_NT | RFLAGS_IOPL;
use alloc::string::String;
use super::linux_def::*;
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, Clone, PartialEq)]
pub enum TaskRunState {
RunApp,
RunInterrupt,
RunExit,
RunExitNotify,
RunThreadExit,
RunTreadExitNotify,
RunExitDone,
RunNoneReachAble,
// can't reach this state
RunSyscallRet,
}
// Error represents an error in the netstack error space. Using a special type
// ensures that errors outside of this space are not accidentally introduced.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub struct TcpipErr {
pub msg: &'static str,
pub ignoreStats: bool,
pub sysErr: i32,
}
impl TcpipErr {
pub fn New(msg: &'static str, ignoreStats: bool, sysErr: i32) -> Self {
return Self {
msg,
ignoreStats,
sysErr,
}
}
pub const ERR_UNKNOWN_PROTOCOL : Self = Self {msg: "unknown protocol", ignoreStats: false, sysErr: SysErr::EINVAL};
pub const ERR_UNKNOWN_NICID : Self = Self {msg: "unknown nic id", ignoreStats: false, sysErr: SysErr::EINVAL};
pub const ERR_UNKNOWN_DEVICE : Self = Self {msg: "unknown device", ignoreStats: false, sysErr: SysErr::ENODEV};
pub const ERR_UNKNOWN_PROTOCOL_OPTION : Self = Self {msg: "unknown option for protocol", ignoreStats: false, sysErr: SysErr::ENOPROTOOPT};
pub const ERR_DUPLICATE_NICID : Self = Self {msg: "duplicate nic id", ignoreStats: false, sysErr: SysErr::EEXIST};
pub const ERR_DUPLICATE_ADDRESS : Self = Self {msg: "duplicate address", ignoreStats: false, sysErr: SysErr::EEXIST};
pub const ERR_NO_ROUTE : Self = Self {msg: "no route", ignoreStats: false, sysErr: SysErr::EHOSTUNREACH};
pub const ERR_BAD_LINK_ENDPOINT : Self = Self {msg: "bad link layer endpoint", ignoreStats: false, sysErr: SysErr::EINVAL};
pub const ERR_ALREADY_BOUND : Self = Self {msg: "endpoint already bound", ignoreStats: true, sysErr: SysErr::EINVAL};
pub const ERR_INVALID_ENDPOINT_STATE : Self = Self {msg: "endpoint is in invalid state", ignoreStats: false, sysErr: SysErr::EINVAL};
pub const ERR_ALREADY_CONNECTING : Self = Self {msg: "endpoint is already connecting", ignoreStats: true, sysErr: SysErr::EALREADY};
pub const ERR_ALREADY_CONNECTED : Self = Self {msg: "endpoint is already connected", ignoreStats: true, sysErr: SysErr::EISCONN};
pub const ERR_NO_PORT_AVAILABLE : Self = Self {msg: "no ports are available", ignoreStats: false, sysErr: SysErr::EAGAIN};
pub const ERR_PORT_IN_USE : Self = Self {msg: "port is in use", ignoreStats: false, sysErr: SysErr::EADDRINUSE};
pub const ERR_BAD_LOCAL_ADDRESS : Self = Self {msg: "bad local address", ignoreStats: false, sysErr: SysErr::EADDRNOTAVAIL};
pub const ERR_CLOSED_FOR_SEND : Self = Self {msg: "endpoint is closed for send", ignoreStats: false, sysErr: SysErr::EPIPE};
pub const ERR_CLOSED_FOR_RECEIVE : Self = Self {msg: "endpoint is closed for receive", ignoreStats: false, sysErr: SysErr::NONE};
pub const ERR_WOULD_BLOCK : Self = Self {msg: "operation would block", ignoreStats: true, sysErr: SysErr::EWOULDBLOCK};
pub const ERR_CONNECTION_REFUSED : Self = Self {msg: "connection was refused", ignoreStats: false, sysErr: SysErr::ECONNREFUSED};
pub const ERR_TIMEOUT : Self = Self {msg: "operation timed out", ignoreStats: false, sysErr: SysErr::ETIMEDOUT};
pub const ERR_ABORTED : Self = Self {msg: "operation aborted", ignoreStats: false, sysErr: SysErr::EPIPE};
pub const ERR_CONNECT_STARTED : Self = Self {msg: "connection attempt started", ignoreStats: true, sysErr: SysErr::EINPROGRESS};
pub const ERR_DESTINATION_REQUIRED : Self = Self {msg: "destination address is required", ignoreStats: false, sysErr: SysErr::EDESTADDRREQ};
pub const ERR_NOT_SUPPORTED : Self = Self {msg: "operation not supported", ignoreStats: false, sysErr: SysErr::EOPNOTSUPP};
pub const ERR_QUEUE_SIZE_NOT_SUPPORTED : Self = Self {msg: "queue size querying not supported", ignoreStats: false, sysErr: SysErr::ENOTTY};
pub const ERR_NOT_CONNECTED : Self = Self {msg: "endpoint not connected", ignoreStats: false, sysErr: SysErr::ENOTCONN};
pub const ERR_CONNECTION_RESET : Self = Self {msg: "connection reset by peer", ignoreStats: false, sysErr: SysErr::ECONNRESET};
pub const ERR_CONNECTION_ABORTED : Self = Self {msg: "connection aborted", ignoreStats: false, sysErr: SysErr::ECONNABORTED};
pub const ERR_NO_SUCH_FILE : Self = Self {msg: "no such file", ignoreStats: false, sysErr: SysErr::ENOENT};
pub const ERR_INVALID_OPTION_VALUE : Self = Self {msg: "invalid option value specified", ignoreStats: false, sysErr: SysErr::EINVAL};
pub const ERR_NO_LINK_ADDRESS : Self = Self {msg: "no remote link address", ignoreStats: false, sysErr: SysErr::EHOSTDOWN};
pub const ERR_BAD_ADDRESS : Self = Self {msg: "bad address", ignoreStats: false, sysErr: SysErr::EFAULT};
pub const ERR_NETWORK_UNREACHABLE : Self = Self {msg: "network is unreachable", ignoreStats: false, sysErr: SysErr::ENETUNREACH};
pub const ERR_MESSAGE_TOO_LONG : Self = Self {msg: "message too long", ignoreStats: false, sysErr: SysErr::EMSGSIZE};
pub const ERR_NO_BUFFER_SPACE : Self = Self {msg: "no buffer space available", ignoreStats: false, sysErr: SysErr::ENOBUFS};
pub const ERR_BROADCAST_DISABLED : Self = Self {msg: "broadcast socket option disabled", ignoreStats: false, sysErr: SysErr::EACCES};
pub const ERR_NOT_PERMITTED : Self = Self {msg: "operation not permitted", ignoreStats: false, sysErr: SysErr::EPERM};
}
#[derive(Debug, Clone, PartialEq)]
pub enum Error {
None,
Timeout,
PipeClosed,
TcpipErr(TcpipErr),
SysCallNotImplement,
Common(String),
CreateMMap(String),
UnallignedAddress,
UnallignedSize,
NoEnoughMemory,
AddressNotInRange,
RootPageIdxNoExist,
IOError(String),
NoEnoughSpace,
RangeUnavailable,
Overflow,
WrongELFFormat,
ELFLoadError(&'static str),
InterpreterFileErr,
MMampError,
UnmatchRegion,
AddressDoesMatch,
Locked,
ZeroCount,
QueueFull,
NoData,
NoUringReq,
NoneIdx,
AddressNotMap(u64),
InvalidInput,
NotExist,
Signal,
Exit,
SysError(i32),
FileMapError,
NoEnoughData,
EOF,
ChanClose,
// mem map of /dev/zero
ErrDevZeroMap,
//todo handle this.
ErrClosedForReceive,
ErrConnectionReset,
//this is for chmod operation, fchmod doesn't work.
CHMOD,
SysCallRetCtrlWithRet(TaskRunState, u64),
SysCallRetCtrl(TaskRunState),
//link should be resolved via Readlink()
ErrResolveViaReadlink,
// ERESTARTSYS is returned by an interrupted syscall to indicate that it
// should be converted to EINTR if interrupted by a signal delivered to a
// user handler without SA_RESTART set, and restarted otherwise.
ERESTARTSYS,
// ERESTARTNOINTR is returned by an interrupted syscall to indicate that it
// should always be restarted.
ERESTARTNOINTR,
// ERESTARTNOHAND is returned by an interrupted syscall to indicate that it
// should be converted to EINTR if interrupted by a signal delivered to a
// user handler, and restarted otherwise.
ERESTARTNOHAND,
// ERESTART_RESTARTBLOCK is returned by an interrupted syscall to indicate
// that it should be restarted using a custom function. The interrupted
// syscall must register a custom restart function by calling
// Task.SetRestartSyscallFn.
ERESTARTRESTARTBLOCK,
// ErrWouldBlock is an internal error used to indicate that an operation
// cannot be satisfied immediately, and should be retried at a later
// time, possibly when the caller has received a notification that the
// operation may be able to complete. It is used by implementations of
// the kio.File interface.
ErrWouldBlock,
//request was interrupted
ErrInterrupted,
// ErrExceedsFileSizeLimit is returned if a request would exceed the
// file's size limit.
ErrExceedsFileSizeLimit,
// ErrNoWaitableEvent is returned by non-blocking Task.Waits (e.g.
// waitpid(WNOHANG)) that find no waitable events, but determine that waitable
// events may exist in the future. (In contrast, if a non-blocking or blocking
// Wait determines that there are no tasks that can produce a waitable event,
// Task.Wait returns ECHILD.)
ErrNoWaitableEvent,
}
impl Error {
pub fn SystemErr(err: i32) -> Self {
return Self::SysError(err)
}
pub fn Message(e: String) -> Self {
return Self::Common(e);
}
pub fn MapRes(res: i32) -> Result<()> {
if res == 0 {
return Ok(())
}
if res < 0 {
return Err(Error::SysError(-res))
}
panic!("MapRes get res {}", res);
}
}
impl Default for Error {
fn default() -> Self { Error::None }
}
pub fn ConvertIntr(err: Error, intr: Error) -> Error {
if err == Error::ErrInterrupted {
return intr
}
return err
}
pub trait RefMgr: Send {
//ret: (the page's ref count, the pma's ref count)
fn Ref(&self, addr: u64) -> Result<u64>;
fn Deref(&self, addr: u64) -> Result<u64>;
fn GetRef(&self, addr: u64) -> Result<u64>;
}
pub trait Allocator: RefMgr {
fn AllocPage(&self, incrRef: bool) -> Result<u64>;
fn FreePage(&self, addr: u64) -> Result<()>;
}
|
// Copyright 2021 Chiral Ltd.
// Licensed under the Apache-2.0 license (https://opensource.org/licenses/Apache-2.0)
// This file may not be copied, modified, or distributed
// except according to those terms.
use crate::core;
use crate::core::graph::*;
use super::atom;
/// Seperate vertices in an orbit according to their neighbours. Only applicable for endpoint atoms
fn group_by_neighbour(
orbit: &core::orbit_ops::Orbit,
vv: &core::graph::VertexVec<atom::Atom>,
) -> Vec<core::orbit_ops::Orbit> {
let mut atom_groups: std::collections::HashMap<usize, core::orbit_ops::Orbit> = std::collections::HashMap::new();
for &ai in orbit.iter() {
let nb_idx: usize = vv[ai].neighbour_indexes()[0]; // endpoint atom has only one neighbour
atom_groups.entry(nb_idx).or_insert(vec![]).push(ai);
}
atom_groups.into_values().collect()
}
/// Acyclic Local Symmetry
fn is_acyclic_local_symmetric(
orbit: &core::orbit_ops::Orbit,
vv: &core::graph::VertexVec<atom::Atom>,
) -> bool {
if vv[orbit[0]].degree() != 1 {
return false;
}
let orbits_local_symmetry: Vec<core::orbit_ops::Orbit> = group_by_neighbour(&orbit, vv);
orbits_local_symmetry.len() == 1
}
/// Find the cycle including the vertex with minimum size
fn find_cyclic_route(
vertex: usize,
vv: &core::graph::VertexVec<atom::Atom>,
max_size: usize
) -> Vec<usize> {
let mut cyclic_route: Vec<usize> = vec![0; max_size + 1];
for &neighbour in vv[vertex].neighbour_indexes().iter() {
match core::cycle_ops::find_cycle_for_vertices(vertex, neighbour, vv, max_size) {
Some(cr) => {
if cr.len() < cyclic_route.len() {
cyclic_route = cr
}
},
None => ()
}
}
cyclic_route
}
/// Cyclic Local Symmetry
fn is_cyclic_local_symmetric(
orbit: &core::orbit_ops::Orbit,
vv: &core::graph::VertexVec<atom::Atom>,
max_size: usize
) -> bool {
if orbit.len() != 2 {
return false;
}
if vv[orbit[0]].degree() != 2 {
return false;
}
// find the minimum cycle for orbit
let cyclic_route: Vec<usize> = find_cyclic_route(orbit[0], vv, max_size);
let cyclic_route_1: Vec<usize> = find_cyclic_route(orbit[1], vv, max_size);
if !core::orbit_ops::orbit_equal(&cyclic_route, &cyclic_route_1) {
return false;
}
if cyclic_route.len() > max_size {
return false;
}
let boundary_vertices: Vec<usize> = cyclic_route.clone().into_iter()
.filter(|&vi| vv[vi].degree() > 2)
.collect();
if cyclic_route.len() % 2 == 1 {
boundary_vertices.len() == 1
} else {
(boundary_vertices.len() == 1 && core::graph_ops::graph_distance(boundary_vertices[0], orbit[0], vv) != cyclic_route.len() / 2)
|| (boundary_vertices.len() == 2 && core::graph_ops::graph_distance(boundary_vertices[0], boundary_vertices[1], vv) == cyclic_route.len() / 2 && core::graph_ops::graph_distance(boundary_vertices[0], orbit[0], vv) == core::graph_ops::graph_distance(boundary_vertices[0], orbit[1], vv))
}
}
pub fn get_local_symmetric_orbits(
vv: &core::graph::VertexVec<atom::Atom>,
orbits_residual: &mut Vec<core::orbit_ops::Orbit>,
orbits_symmetry: &mut Vec<core::orbit_ops::Orbit>
) {
let mut orbits_tmp = orbits_residual.clone();
orbits_residual.clear();
while let Some(orbit) = orbits_tmp.pop() {
if is_acyclic_local_symmetric(&orbit, vv) {
orbits_symmetry.push(orbit);
} else if is_cyclic_local_symmetric(&orbit, vv, 6) {
orbits_symmetry.push(orbit);
} else {
orbits_residual.push(orbit);
}
}
}
#[cfg(test)]
mod test_ext_mol_local_symmetry {
use super::*;
use super::super::molecule;
#[test]
fn test_group_by_neighbour() {
let test_data: Vec<(String, core::orbit_ops::Orbit, Vec<core::orbit_ops::Orbit>)> = vec![
("C(C)(C)CCN",
vec![1, 2], vec![vec![1, 2]]),
("C(C)(C)CCNCCC(C)(C)",
vec![1, 2, 9, 10], vec![vec![1, 2], vec![9, 10]])
].into_iter().map(|s| (s.0.to_string(), s.1, s.2)).collect();
for td in test_data.iter() {
let mol = molecule::Molecule::from_smiles(&td.0);
let vv = core::graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone());
assert_eq!(core::orbit_ops::orbits_equal(&group_by_neighbour(&td.1, &vv), &td.2), true);
}
}
#[test]
fn test_is_acyclic_local_symmetric() {
type InputType1 = String;
type InputType2 = core::orbit_ops::Orbit;
type ReturnType = bool;
let test_data: Vec<(InputType1, InputType2, ReturnType)> = vec![
(
"C(C)(C)CCN",
vec![1, 2], true
),
(
"C(C)(C)CCNCCC(C)(C)",
vec![1, 2, 9, 10], false
)
].into_iter().map(|s| (s.0.to_string(), s.1, s.2)).collect();
for td in test_data.iter() {
let mol = molecule::Molecule::from_smiles(&td.0);
let vv = core::graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone());
assert_eq!(is_acyclic_local_symmetric(&td.1, &vv), td.2);
}
}
#[test]
fn test_is_cyclic_local_symmetric() {
type InputType1 = String;
type InputType2 = core::orbit_ops::Orbit;
type ResultType = bool;
let test_data: Vec<(InputType1, Vec<(InputType2, ResultType)>)> = vec![
(
"C1C(N)C1",
vec![
(vec![0, 3], true)
]
),
(
"OC1CCC1",
vec![
(vec![2, 4], true)
]
),
(
"OC1C(N)CC1",
vec![
(vec![4, 5], false)
]
),
(
"OC1CC(N)C1",
vec![
(vec![2, 5], true)
]
),
(
"OC1CCCC1",
vec![
(vec![2, 5], true),
(vec![3, 4], true),
]
),
(
"OC1C(C)CCC1",
vec![
(vec![4, 5], false)
]
),
(
"OC1CC(C)CC1",
vec![
(vec![5, 6], false)
]
),
(
"Oc1ccccc1",
vec![
(vec![2, 6], true),
(vec![3, 5], true),
]
),
(
"Oc1c(N)cccc1",
vec![
(vec![5, 6], false),
]
),
(
"Oc1cc(N)ccc1",
vec![
(vec![5, 6], false),
]
),
(
"Oc1ccc(N)cc1",
vec![
(vec![2, 7], true),
(vec![3, 6], true),
]
),
].into_iter().map(|s| (s.0.to_string(), s.1)).collect();
for td in test_data.iter() {
let mol = molecule::Molecule::from_smiles(&td.0);
let vv = core::graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone());
for test_param in td.1.iter() {
assert_eq!(is_cyclic_local_symmetric(&test_param.0, &vv, 6), test_param.1);
}
}
}
#[test]
fn test_get_local_symmetric_orbits() {
type InputType1 = String;
type InputType2 = Vec<core::orbit_ops::Orbit>;
type ResultType = (Vec<core::orbit_ops::Orbit>, Vec<core::orbit_ops::Orbit>);
let test_data: Vec<(InputType1, InputType2, ResultType)> = vec![
(
"FC(F)(F)c1ccc(C[N+]23CC[C@]45c6ccccc6N6[C@H]4[C@H]4[C@@H](C[C@@H]52)C(=CCO[C@H]4N2c4ccccc4[C@@]45CC[N+]7(Cc8ccc(C(F)(F)F)cc8)CC8=CCO[C@@H]6[C@@H]([C@H]24)[C@H]8C[C@@H]57)C3)cc1",
vec![vec![6, 43, 51, 64]],
(vec![vec![6, 43, 51, 64]], vec![]),
),
(
"FC(F)(F)c1ccc(C[N+]23CC[C@]45c6ccccc6N6[C@H]4[C@H]4[C@@H](C[C@@H]52)C(=CCO[C@H]4N2c4ccccc4[C@@]45CC[N+]7(Cc8ccc(C(F)(F)F)cc8)CC8=CCO[C@@H]6[C@@H]([C@H]24)[C@H]8C[C@@H]57)C3)cc1",
vec![vec![0, 2, 3, 47, 48, 49]],
(vec![vec![0, 2, 3, 47, 48, 49]], vec![]),
),
(
r#"COc1cc(Cc2cnc(/N=C3\C(=O)N(CN(Cc4ccccc4)Cc4ccccc4)c4ccc(Cl)cc43)nc2N)cc(OC)c1OC"#,
vec![vec![0, 44], vec![1, 43], vec![2, 42], vec![3, 41], vec![17, 24], vec![18, 25], vec![19, 23, 26, 30], vec![20, 22, 27, 29], vec![21, 28]],
(vec![vec![0, 44], vec![1, 43], vec![2, 42], vec![3, 41], vec![17, 24], vec![18, 25], vec![19, 23, 26, 30], vec![20, 22, 27, 29], vec![21, 28]], vec![])
),
].into_iter().map(|s| (s.0.to_string(), s.1, s.2)).collect();
for td in test_data.iter() {
let (smiles, mut orbits_residual, result) = td.clone();
let mol = molecule::Molecule::from_smiles(&smiles);
// println!("{}", mol.smiles_with_index(&smiles));
let vv = core::graph::VertexVec::init((0..mol.atoms.len()).collect(), mol.atoms.clone());
let mut orbits_symmetry: Vec<core::orbit_ops::Orbit> = vec![];
get_local_symmetric_orbits(&vv, &mut orbits_residual, &mut orbits_symmetry);
assert_eq!(core::orbit_ops::orbits_equal(&orbits_residual, &result.0), true);
assert_eq!(core::orbit_ops::orbits_equal(&orbits_symmetry, &result.1), true);
}
}
} |
// revisions: base nll
// ignore-compare-mode-nll
//[nll] compile-flags: -Z borrowck=mir
fn foo(&mut (ref mut v, w): &mut (&u8, &u8), x: &u8) {
*v = x;
//[base]~^ ERROR lifetime mismatch
//[nll]~^^ ERROR lifetime may not live long enough
}
fn main() { }
|
use constants::*;
/// Calculates the number of pieces required to hold this many bits in a genestring.
pub fn part_count_for_bits(bits: u64) -> u64 {
if bits == 0 {
1
} else if bits % PIECE_SIZE_IN_BITS == 0 {
bits / PIECE_SIZE_IN_BITS
} else {
(bits / PIECE_SIZE_IN_BITS) + 1
}
}
// Calculates which piece contains a given bit.
pub fn part_for_bit(bit: u64) -> u64 {
bit / PIECE_SIZE_IN_BITS
}
|
use std::fs;
use regex::Regex;
use std::collections::HashMap;
fn valid_part_1 (passport: &HashMap<String,String>) -> bool {
if !passport.contains_key("byr") {
return false;
}
if !passport.contains_key("iyr") {
return false;
}
if !passport.contains_key("eyr") {
return false;
}
if !passport.contains_key("hgt") {
return false;
}
if !passport.contains_key("hcl") {
return false;
}
if !passport.contains_key("ecl") {
return false;
}
if !passport.contains_key("pid"){
return false;
}
return true;
}
fn is_valid_date (value: Option<&String>, min: u32, max: u32) -> bool {
let date = value.unwrap().parse::<u32>().unwrap();
return date >= min && date <= max;
}
fn valid_part_2 (passport: &HashMap<String,String>) -> bool {
if !passport.contains_key("byr") || !is_valid_date(passport.get("byr"), 1920, 2002) {
return false;
}
if !passport.contains_key("iyr") || !is_valid_date(passport.get("iyr"), 2010, 2020) {
return false;
}
if !passport.contains_key("eyr") || !is_valid_date(passport.get("eyr"), 2020, 2030) {
return false;
}
if !passport.contains_key("hgt") {
return false;
} else {
let hgt = passport.get("hgt").unwrap();
let re = Regex::new(r"(\d+)(in|cm)").unwrap();
if !re.is_match(hgt) {
return false;
}
let res = re.captures(hgt).unwrap();
let amount = res[1].parse::<u32>().unwrap();
if &res[2] == "cm" && (amount < 150 || amount > 193) {
return false;
}
if &res[2] == "in" && (amount < 59 || amount > 76) {
return false;
}
}
if !passport.contains_key("hcl") {
return false;
} else {
let hcl = passport.get("hcl").unwrap();
let re = Regex::new(r"^#[0-9A-Fa-f]{6}$").unwrap();
if !re.is_match(hcl) {
return false;
}
}
if !passport.contains_key("ecl") {
return false;
} else {
let ecl = passport.get("ecl").unwrap();
let re = Regex::new(r"^(amb|blu|brn|gry|grn|hzl|oth)$").unwrap();
if !re.is_match(ecl) {
return false;
}
}
if !passport.contains_key("pid"){
return false;
} else {
let pid = passport.get("pid").unwrap();
let re = Regex::new(r"^\d{9}$").unwrap();
if !re.is_match(pid) {
return false;
}
}
return true;
}
fn run (filename: String, validate: fn(&HashMap<String,String>) -> bool) -> i32 {
let file_content = fs::read_to_string(filename).expect("Something went wrong reading the file");
let lines = file_content.lines();
let re = Regex::new(r"(\w+):([#\w]+)").unwrap();
let mut pass = HashMap::new();
let mut nb_valid = 0;
for line in lines {
if line.is_empty() {
if validate(&pass) {
nb_valid += 1;
}
pass.clear();
continue;
}
for cap in re.captures_iter(line) {
pass.insert(String::from(&cap[1]), String::from(&cap[2]));
}
}
return nb_valid;
}
fn main() {
// let result = run(String::from("src/exo4.source.txt"), valid_part_1);
let result = run(String::from("src/exo4.source.txt"), valid_part_2);
println!("{}", result);
}
|
use std::fs;
#[test]
fn validate() {
assert_eq!(algorithm("src/day_3/input_test.txt", false), 336);
}
fn algorithm(file_location: &str, print_results: bool) -> u64 {
let contents = fs::read_to_string(file_location).unwrap();
let values: Vec<&str> = contents.lines().collect();
let max_cols = values.first().unwrap().len();
let max_rows = values.len() - 1;
let mut total: u64 = 1;
let slope_strategies = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)];
for (right, down) in slope_strategies.iter() {
let mut curr_row = 0;
let mut curr_col = 0;
let mut first_iter = true;
let mut done = false;
let mut count = 0;
while !done {
let row = values[curr_row];
let target = row.chars().nth(curr_col).unwrap();
if target == '#' && !first_iter {
count = count + 1;
}
curr_row = curr_row + down;
curr_col = (curr_col + right) % max_cols;
if curr_row > max_rows {
done = true;
}
first_iter = false;
}
total = total * count;
if print_results {
println!("Right {}, down {}: we hit {} trees.", right, down, count);
}
}
total
}
pub fn run() {
println!(
"Multiplying all the values gives us {}.",
algorithm("src/day_3/input.txt", true)
);
}
|
pub fn p2(max: u32) -> u32 {
rec_while(
(1, 2, 0),
|&(c, n, t)| { (n, c + n, if c & 1 == 0 { t + c} else { t } ) },
|&(c, _, _)| { c <= max }
).2
}
fn rec_while<T, F, P>(x: T, next: F, pred: P) -> T
where F: Fn(&T) -> T,
P: Fn(&T) -> bool,
{
if pred(&x) { rec_while(next(&x), next, pred) }
else { x }
}
#[test]
fn test_p2() {
assert_eq!(p2(4_000_000), 4613732);
} |
#[test]
fn iterator_sum_consumer_test() {
let s: u32 = (1..20 + 1).sum();
assert_eq!(s, 210);
}
#[test]
fn iterator_factorial_consumer_test() {
let s: u32 = (1..5 + 1).product();
assert_eq!(s, 120);
}
#[test]
fn max_min_consumer_test() {
assert_eq!([0, 30, 12, 200, 67, 40].iter().max(), Some(&200));
assert_eq!([10, 30, 12, 200, 67, 40].iter().min(), Some(&10));
}
#[test]
fn max_min_by_cmp_consumer_test() {
let cmp = |l: &&f32, r: &&f32| -> std::cmp::Ordering { l.partial_cmp(r).unwrap() };
let numbers = [2.0, 4.0, 1.0, 6.0];
let max = &numbers.iter().max_by(cmp);
let min = &numbers.iter().min_by(cmp);
assert_eq!(*max, Some(&6.0));
assert_eq!(*min, Some(&1.0));
}
|
// 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.
mod agg;
use std::io::Write;
use bumpalo::Bump;
use comfy_table::Table;
use common_exception::Result;
use common_expression::date_helper::TzLUT;
use common_expression::type_check;
use common_expression::types::number::NumberScalar;
use common_expression::types::AnyType;
use common_expression::types::DataType;
use common_expression::BlockEntry;
use common_expression::Column;
use common_expression::ColumnBuilder;
use common_expression::DataBlock;
use common_expression::Evaluator;
use common_expression::FunctionContext;
use common_expression::RawExpr;
use common_expression::Scalar;
use common_expression::Value;
use common_functions::aggregates::AggregateFunctionFactory;
use common_functions::BUILTIN_FUNCTIONS;
use itertools::Itertools;
use super::scalars::parser;
pub trait AggregationSimulator =
Fn(&str, Vec<Scalar>, &[Column], usize) -> common_exception::Result<(Column, DataType)> + Copy;
/// run ast which is agg expr
pub fn run_agg_ast(
file: &mut impl Write,
text: &str,
columns: &[(&str, Column)],
simulator: impl AggregationSimulator,
) {
let raw_expr = parser::parse_raw_expr(
text,
&columns
.iter()
.map(|(name, col)| (*name, col.data_type()))
.collect::<Vec<_>>(),
);
let num_rows = columns.iter().map(|col| col.1.len()).max().unwrap_or(0);
let block = DataBlock::new(
columns
.iter()
.map(|(_, col)| BlockEntry {
data_type: col.data_type(),
value: Value::Column(col.clone()),
})
.collect::<Vec<_>>(),
num_rows,
);
let used_columns = raw_expr
.column_refs()
.keys()
.cloned()
.sorted()
.collect::<Vec<_>>();
// For test only, we just support agg function call here
let result: common_exception::Result<(Column, DataType)> = try {
match raw_expr {
common_expression::RawExpr::FunctionCall {
name, params, args, ..
} => {
let args: Vec<(Value<AnyType>, DataType)> = args
.iter()
.map(|raw_expr| run_scalar_expr(raw_expr, &block))
.collect::<Result<_>>()
.unwrap();
let params = params
.iter()
.map(|p| Scalar::Number(NumberScalar::UInt64(*p as u64)))
.collect();
let arg_columns: Vec<Column> = args
.iter()
.map(|(arg, ty)| match arg {
Value::Scalar(s) => {
let builder = ColumnBuilder::repeat(&s.as_ref(), block.num_rows(), ty);
builder.build()
}
Value::Column(c) => c.clone(),
})
.collect();
simulator(name.as_str(), params, &arg_columns, block.num_rows())?
}
_ => unimplemented!(),
}
};
match result {
Ok((column, _)) => {
writeln!(file, "ast: {text}").unwrap();
{
let mut table = Table::new();
table.load_preset("||--+-++| ++++++");
table.set_header(["Column", "Data"]);
let ids = match used_columns.is_empty() {
true => {
if columns.is_empty() {
vec![]
} else {
vec![0]
}
}
false => used_columns,
};
for id in ids.iter() {
let (name, col) = &columns[*id];
table.add_row(&[name.to_string(), format!("{col:?}")]);
}
table.add_row(["Output".to_string(), format!("{column:?}")]);
writeln!(file, "evaluation (internal):\n{table}").unwrap();
}
write!(file, "\n\n").unwrap();
}
Err(e) => {
writeln!(file, "error: {}\n", e.message()).unwrap();
}
}
}
pub fn run_scalar_expr(
raw_expr: &RawExpr,
block: &DataBlock,
) -> Result<(Value<AnyType>, DataType)> {
let expr = type_check::check(raw_expr, &BUILTIN_FUNCTIONS)?;
let func_ctx = FunctionContext {
tz: TzLUT::default(),
};
let evaluator = Evaluator::new(block, func_ctx, &BUILTIN_FUNCTIONS);
let result = evaluator.run(&expr)?;
Ok((result, expr.data_type().clone()))
}
/// Simulate group-by aggregation.
/// Rows are ditributed into two group-by keys.
///
/// Example:
///
/// If the column is:
///
/// ```
/// let column = vec![1, 2, 3, 4, 5];
/// ```
///
/// then the groups are:
///
/// ```
/// let group1 = vec![1, 3, 5];
/// let group2 = vec![2, 4];
/// ```
pub fn simulate_two_groups_group_by(
name: &str,
params: Vec<Scalar>,
columns: &[Column],
rows: usize,
) -> common_exception::Result<(Column, DataType)> {
let factory = AggregateFunctionFactory::instance();
let arguments: Vec<DataType> = columns.iter().map(|c| c.data_type()).collect();
let cols: Vec<Column> = columns.to_owned();
let func = factory.get(name, params, arguments)?;
let data_type = func.return_type()?;
let arena = Bump::new();
// init state for two groups
let addr1 = arena.alloc_layout(func.state_layout());
func.init_state(addr1.into());
let addr2 = arena.alloc_layout(func.state_layout());
func.init_state(addr2.into());
let places = (0..rows)
.map(|i| {
if i % 2 == 0 {
addr1.into()
} else {
addr2.into()
}
})
.collect::<Vec<_>>();
func.accumulate_keys(&places, 0, &cols, rows)?;
let mut builder = ColumnBuilder::with_capacity(&data_type, 1024);
func.merge_result(addr1.into(), &mut builder)?;
func.merge_result(addr2.into(), &mut builder)?;
Ok((builder.build(), data_type))
}
|
pub(crate) mod process;
pub mod recipe;
// mod state_machine;
pub use recipe::Recipe;
/// Redefine BeerXML types as Bryggio types.
/// This is for future convenience
/// If the original BeerXML types are ever replaced with custom Bryggio types,
/// then only the definitions below need to change and the entire code base
/// will be in sync.
type Hop = beerxml::Hop;
type Fermentable = beerxml::Fermentable;
type Yeast = beerxml::Yeast;
type Water = beerxml::Water;
type Equipment = beerxml::Equipment;
type Style = beerxml::Style;
type Misc = beerxml::Misc;
type Type = beerxml::Type;
|
#![allow(unused)]
#![allow(non_snake_case)]
use std::fmt; //fmt METHOD
use serde::{Deserialize, Serialize};
// Universal flags can apply to any transaction type
#[derive(Serialize, Deserialize, Debug)]
pub enum Universal {
FullyCanonicalSig = 0x80000000
}
#[derive(Serialize, Deserialize, Debug)]
pub enum AccountSet {
RequireDestTag = 0x00010000,
OptionalDestTag = 0x00020000,
RequireAuth = 0x00040000,
OptionalAuth = 0x00080000,
DisallowSWT = 0x00100000,
AllowSWT = 0x00200000,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum TrustSet {
SetAuth = 0x00010000,
ClearNoSkywell = 0x00040000,
SetFreeze = 0x00100000,
ClearFreeze = 0x00200000,
// NoSkywell = 0x00020000,
// SetNoSkywell = 0x00020000,
NoSkywell,
SetNoSkywell,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum OfferCreate {
Passive = 0x00010000,
ImmediateOrCancel = 0x00020000,
FillOrKill = 0x00040000,
Sell = 0x00080000,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum Payment {
NoSkywellDirect = 0x00010000,
PartialPayment = 0x00020000,
LimitQuality = 0x00040000,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum RelationSet {
Authorize = 0x00000001,
Freeze = 0x00000011,
}
#[derive(Serialize, Deserialize, Debug)]
pub enum Flags {
Universal { name: Universal },
AccountSet { name: AccountSet },
TrustSet { name: TrustSet },
OfferCreate{ name: OfferCreate },
Payment { name: Payment },
RelationSet{ name: RelationSet },
Other,
}
//Get enum as string
impl fmt::Display for Flags {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", self)
}
}
impl Flags {
pub fn get(&self) -> u32 {
match *self {
//Universal
Flags::Universal { ref name } => {
match name {
&Universal::FullyCanonicalSig => { Universal::FullyCanonicalSig as u32
}
}}
//AccountSet
Flags::AccountSet { ref name } => {
match name {
&AccountSet::RequireDestTag => { AccountSet::RequireDestTag as u32 },
&AccountSet::OptionalDestTag => { AccountSet::OptionalDestTag as u32 },
&AccountSet::RequireAuth => { AccountSet::RequireAuth as u32 },
&AccountSet::OptionalAuth => { AccountSet::OptionalAuth as u32 },
&AccountSet::DisallowSWT => { AccountSet::DisallowSWT as u32 },
&AccountSet::AllowSWT => { AccountSet::AllowSWT as u32 },
}
}
//TrustSet
Flags::TrustSet { ref name } => {
match name {
&TrustSet::SetAuth => { TrustSet::SetAuth as u32 },
&TrustSet::ClearNoSkywell => { TrustSet::ClearNoSkywell as u32 },
&TrustSet::SetFreeze => { TrustSet::SetFreeze as u32 },
&TrustSet::ClearFreeze => { TrustSet::ClearFreeze as u32 },
// NoSkywell => { TrustSet::NoSkywell as i32 },
// SetNoSkywell => { TrustSet::SetNoSkywell as i32 },
&TrustSet::NoSkywell => { 0x00020000 as u32 },
&TrustSet::SetNoSkywell => { 0x00020000 as u32 },
}
}
//OfferCreate
Flags::OfferCreate { ref name } => {
match name {
&OfferCreate::Passive => { OfferCreate::Passive as u32 },
&OfferCreate::ImmediateOrCancel => { OfferCreate::ImmediateOrCancel as u32 },
&OfferCreate::FillOrKill => { OfferCreate::FillOrKill as u32 },
&OfferCreate::Sell => { OfferCreate::Sell as u32 },
}
}
//Payment
Flags::Payment { ref name } => {
match name {
&Payment::NoSkywellDirect => { Payment::NoSkywellDirect as u32 },
&Payment::PartialPayment => { Payment::PartialPayment as u32 },
&Payment::LimitQuality => { Payment::LimitQuality as u32 },
}
}
//RelationSet
Flags::RelationSet { ref name } => {
match name {
&RelationSet::Authorize => { RelationSet::Authorize as u32 },
&RelationSet::Freeze => { RelationSet::Freeze as u32 },
}
}
Flags::Other => { 0 as u32 },
_ => 0,
}
}
}
|
pub mod support;
pub mod api; |
use game_core::loading::RequiredAssetLoader;
use game_lib::bevy::{
prelude::*,
reflect::TypeUuid,
render::{pipeline::PipelineDescriptor, shader::ShaderStages},
};
pub const REGION_PIPELINE_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(PipelineDescriptor::TYPE_UUID, 0x5BA3E190095C409A);
pub const REGION_MESH_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(Mesh::TYPE_UUID, 0x3F8EB05B6CD0403A);
pub const REGION_TEXTURE_ATLAS_HANDLE: HandleUntyped =
HandleUntyped::weak_from_u64(TextureAtlas::TYPE_UUID, 0x3A06EC1D04544655);
pub fn build_region_pipeline(asset_loader: &mut RequiredAssetLoader) -> PipelineDescriptor {
PipelineDescriptor {
name: Some("region".into()),
..PipelineDescriptor::default_config(ShaderStages {
vertex: asset_loader.load_required("shaders/region.vert"),
fragment: Some(asset_loader.load_required("shaders/region.frag")),
})
}
}
|
mod gifcard;
pub use gifcard::gifcard;
mod navbar;
pub use navbar::navbar;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.