text stringlengths 8 4.13M |
|---|
use std::io;
use memchr::memchr;
use crate::errors::ParseError;
use crate::parser::record::SequenceRecord;
pub(crate) const BUFSIZE: usize = 64 * 1024;
/// Remove a final '\r' from a byte slice
#[inline]
pub(crate) fn trim_cr(line: &[u8]) -> &[u8] {
if let Some((&b'\r', remaining)) = line.split_last() {
remaining
} else {
line
}
}
/// Standard buffer policy: buffer size
/// doubles until it reaches 8 MiB. Above, it will
/// increase in steps of 8 MiB. Buffer size is not limited,
/// it could theoretically grow indefinitely.
pub(crate) fn grow_to(current_size: usize) -> usize {
if current_size < 1 << 23 {
current_size * 2
} else {
current_size + (1 << 23)
}
}
/// Makes sure the buffer is full after this call (unless EOF reached)
/// code adapted from `io::Read::read_exact`
pub(crate) fn fill_buf<R>(reader: &mut buffer_redux::BufReader<R>) -> io::Result<usize>
where
R: io::Read,
{
let initial_size = reader.buffer().len();
let mut num_read = 0;
while initial_size + num_read < reader.capacity() {
match reader.read_into_buf() {
Ok(0) => break,
Ok(n) => num_read += n,
Err(ref e) if e.kind() == io::ErrorKind::Interrupted => {}
Err(e) => return Err(e),
}
}
Ok(num_read)
}
/// Holds line number and byte offset of our current state in a parser
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Position {
pub(crate) line: u64,
pub(crate) byte: u64,
}
impl Position {
pub fn new(line: u64, byte: u64) -> Position {
Position { line, byte }
}
/// Line number (starting with 1)
pub fn line(&self) -> u64 {
self.line
}
/// Byte offset within the file
pub fn byte(&self) -> u64 {
self.byte
}
}
/// FASTA or FASTQ?
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Format {
Fasta,
Fastq,
}
impl Format {
pub fn start_char(&self) -> char {
match self {
Format::Fasta => '>',
Format::Fastq => '@',
}
}
}
/// Whether it uses \r\n or only \n
#[derive(Debug, PartialEq, Eq, Hash, Copy, Clone)]
pub enum LineEnding {
Windows,
Unix,
}
impl LineEnding {
pub fn to_bytes(&self) -> Vec<u8> {
match self {
LineEnding::Windows => vec![b'\r', b'\n'],
LineEnding::Unix => vec![b'\n'],
}
}
}
pub fn find_line_ending(bytes: &[u8]) -> Option<LineEnding> {
if !bytes.is_empty() {
if let Some(idx) = memchr(b'\n', bytes) {
if idx > 0 && bytes[idx - 1] == b'\r' {
return Some(LineEnding::Windows);
} else {
return Some(LineEnding::Unix);
}
}
}
None
}
/// The main trait, iterator-like, that the FASTA and FASTQ readers implement
pub trait FastxReader: Send {
/// Gets the next record in the stream.
/// This imitates the Iterator API but does not support any iterator functions.
/// This returns None once we reached the EOF.
fn next(&mut self) -> Option<Result<SequenceRecord, ParseError>>;
/// Returns the current line/byte in the stream we are reading from
fn position(&self) -> &Position;
/// Returns whether the current stream uses Windows or Unix style line endings
/// It is `None` only before calling `next`, once `next` has been called it will always
/// return a line ending.
fn line_ending(&self) -> Option<LineEnding>;
}
|
pub mod app;
pub use self::app::*;
pub mod easings;
pub use self::easings::*;
pub mod f32;
pub use self::f32::*;
pub mod hsl;
pub use self::hsl::*;
pub mod iterator;
pub use self::iterator::*;
pub mod point2;
pub use self::point2::*;
pub mod vector2;
pub use self::vector2::*;
pub mod path2;
pub use self::path2::*;
pub mod path3;
pub use self::path3::*;
pub mod triangles;
pub use self::triangles::*;
pub mod line_segment;
pub use self::line_segment::*;
pub mod paths;
pub use self::paths::*;
pub mod range_inclusive;
pub use self::range_inclusive::*;
pub mod rbg_hue;
pub use self::rbg_hue::*;
pub mod rect;
pub use self::rect::*;
pub mod tri;
pub use self::tri::*;
pub mod srgb8;
pub use self::srgb8::*;
pub mod usize;
pub use self::usize::*;
pub mod vec;
pub use self::vec::*;
pub mod draw;
pub use self::draw::*;
|
//! The Signal type.
//!
//! Signals are values that change over time. They represent shared mutable state, but exposed
//! in a functional way. The value can be read using the `Signal::sample` method. Signals do all
//! their work on the receiver side, so they're "lazy". Operations applied on a signal are applied
//! to the value every time the signal is sampled.
//!
//! Signals are usually constructed by stream operations like `Stream::hold` and `Stream::fold`.
//! They can also take values from a custom function by using `Signal::from_fn`.
//!
//! # Example
//! ```
//! use frappe::Sink;
//!
//! let sink = Sink::new();
//! let sig1 = sink.stream().fold(0, |a, n| a + *n);
//! let sig2 = sig1.map(|x| x + 2);
//!
//! sink.send(10);
//! assert_eq!(sig1.sample(), 10);
//! assert_eq!(sig2.sample(), 12);
//!
//! sink.send(30);
//! assert_eq!(sig1.sample(), 40);
//! assert_eq!(sig2.sample(), 42);
//! ```
use crate::stream::Stream;
use crate::sync::Mutex;
use crate::types::{MaybeOwned, Storage};
use std::fmt;
use std::sync::{mpsc, Arc};
#[cfg(feature = "lazycell")]
use lazycell::AtomicLazyCell;
/// Represents a value that changes over time.
pub struct Signal<T>(Arc<dyn Fn() -> T + Send + Sync>);
impl<T> Signal<T> {
/// Creates a signal with constant value.
#[inline]
pub fn constant(val: T) -> Self
where
T: Clone + Send + Sync + 'static,
{
Signal::from_fn(move || val.clone())
}
/// Creates a signal that samples it's values from an external source.
#[inline]
pub fn from_fn<F>(f: F) -> Self
where
F: Fn() -> T + Send + Sync + 'static,
{
Signal(Arc::new(f))
}
/// Creates a signal from shared storage.
#[inline]
pub(crate) fn from_storage<S>(storage: Arc<Storage<T>>, source: S) -> Self
where
T: Clone + Send + Sync + 'static,
S: Send + Sync + 'static,
{
Signal::from_fn(move || {
let _keepalive = &source;
storage.get()
})
}
/// Samples the value of the signal.
///
/// The action of sampling pulls the value through the signal chain until it finds it's source,
/// clones it if necessary, and then transforms it into the result value.
#[inline]
pub fn sample(&self) -> T {
self.0()
}
/// Maps a signal using the provided function.
///
/// The map operation applies the function to the signal value every time it's sampled.
pub fn map<F, R>(&self, f: F) -> Signal<R>
where
F: Fn(T) -> R + Send + Sync + 'static,
T: 'static,
{
let this = self.clone();
Signal::from_fn(move || f(this.sample()))
}
/// Folds a signal using the provided function.
///
/// The fold operation applies a `Fn(A, T) -> A` function on the signal every time it's sampled,
/// where `A` is the current accumulator value and `T` is the value of the input signal.
/// The result of this call is stored on the accumulator and returned as the output signal's
/// value.
pub fn fold<A, F>(&self, initial: A, f: F) -> Signal<A>
where
F: Fn(A, T) -> A + Send + Sync + 'static,
T: 'static,
A: Clone + Send + Sync + 'static,
{
let this = self.clone();
let storage = Storage::new(initial);
Signal::from_fn(move || {
let val = this.sample();
storage.replace_fetch(|acc| f(acc, val))
})
}
/// Samples the value of this signal every time the trigger stream fires.
pub fn snapshot<S, F, R>(&self, trigger: &Stream<S>, f: F) -> Stream<R>
where
F: Fn(T, MaybeOwned<'_, S>) -> R + Send + Sync + 'static,
T: 'static,
S: 'static,
R: 'static,
{
let this = self.clone();
trigger.map(move |t| f(this.sample(), t))
}
/// Stores the last value sent to a channel.
///
/// When sampled, the resulting signal consumes all the current values on the channel
/// (using `try_recv`) and returns the last value seen.
#[inline]
pub fn from_channel(initial: T, rx: mpsc::Receiver<T>) -> Self
where
T: Clone + Send + Sync + 'static,
{
Self::fold_channel(initial, rx, |_, v| v)
}
/// Creates a signal that folds the values from a channel.
///
/// When sampled, the resulting signal consumes all the current values on the channel
/// (using `try_recv`) and folds them using the current signal value as the
/// initial accumulator state.
pub fn fold_channel<V, F>(initial: T, rx: mpsc::Receiver<V>, f: F) -> Self
where
F: Fn(T, V) -> T + Send + Sync + 'static,
T: Clone + Send + Sync + 'static,
V: Send + 'static,
{
let storage = Storage::new(initial);
let rx = Mutex::new(rx);
Signal::from_fn(move || {
let source = rx.lock();
if let Ok(first) = source.try_recv() {
storage.replace_fetch(|old| {
let acc = f(old, first);
source.try_iter().fold(acc, &f)
})
} else {
storage.get()
}
})
}
/// Creates a signal with a cyclic definition.
///
/// This allows creating a self-referential Signal definition. The closure receives a forward
/// declaration of a signal that must be used to construct the final Signal. Then this
/// previous forward-declaration is replaced with the value returned by the closure.
///
/// Sampling the forward-declared signal will cause a panic.
#[cfg(feature = "lazycell")]
pub fn cyclic<F>(definition: F) -> Self
where
F: FnOnce(&Signal<T>) -> Signal<T>,
T: 'static,
{
let storage = Arc::new(AtomicLazyCell::new());
let st = storage.clone();
let sig = Signal::from_fn(move || {
Signal::sample(st.borrow().expect("sampled forward-declared Signal"))
});
storage.fill(definition(&sig)).unwrap();
sig
}
}
impl<T: 'static> Signal<Signal<T>> {
/// Creates a new signal that samples the inner value of a nested signal.
pub fn switch(&self) -> Signal<T> {
let this = self.clone();
Signal::from_fn(move || this.sample().sample())
}
}
impl<T> Clone for Signal<T> {
/// Creates a new signal that references the same value.
#[inline]
fn clone(&self) -> Self {
Signal(self.0.clone())
}
}
impl<T: Default + 'static> Default for Signal<T> {
/// Creates a constant signal with T's default value.
#[inline]
fn default() -> Self {
Signal::from_fn(T::default)
}
}
impl<T: Clone + Send + Sync + 'static> From<T> for Signal<T> {
/// Creates a constant signal from T.
#[inline]
fn from(val: T) -> Self {
Signal::constant(val)
}
}
impl<T> fmt::Debug for Signal<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Signal(Fn@{:p})", self.0)
}
}
impl<T: fmt::Display> fmt::Display for Signal<T> {
/// Samples the signal and formats the value.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.sample(), f)
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Instant;
#[test]
fn signal_constant() {
let signal = Signal::constant(42);
let double = signal.map(|a| a * 2);
let plusone = double.map(|a| a + 1);
assert_eq!(signal.sample(), 42);
assert_eq!(double.sample(), 84);
assert_eq!(plusone.sample(), 85);
let c = AtomicUsize::new(0);
let counter = signal.map(move |a| a + c.fetch_add(1, Ordering::Relaxed));
assert_eq!(counter.sample(), 42);
assert_eq!(counter.sample(), 43);
}
#[test]
fn signal_dynamic() {
let t = Instant::now();
let signal = Signal::from_fn(move || t);
assert_eq!(signal.sample(), t);
let n = Arc::new(AtomicUsize::new(1));
let n_ = n.clone();
let signal = Signal::from_fn(move || n_.load(Ordering::Relaxed));
let double = signal.map(|a| a * 2);
let plusone = double.map(|a| a + 1);
assert_eq!(signal.sample(), 1);
assert_eq!(double.sample(), 2);
assert_eq!(plusone.sample(), 3);
n.store(13, Ordering::Relaxed);
assert_eq!(signal.sample(), 13);
assert_eq!(double.sample(), 26);
assert_eq!(plusone.sample(), 27);
}
#[test]
fn signal_fold() {
let sig1 = Signal::constant(1).fold(0, |a, n| a + n);
let sig2 = Signal::from_fn(|| 1).fold(0, |a, n| a + n);
assert_eq!(sig1.sample(), 1);
assert_eq!(sig2.sample(), 1);
assert_eq!(sig1.sample(), 2);
assert_eq!(sig2.sample(), 2);
}
#[test]
fn signal_default() {
let sig1: Signal<i32> = Default::default();
let sig2: Signal<String> = Default::default();
assert_eq!(sig1.sample(), 0);
assert_eq!(sig2.sample(), "");
}
#[test]
fn signal_from() {
let sig1 = Signal::from(42);
let sig2: Signal<i32> = 13.into();
assert_eq!(sig1.sample(), 42);
assert_eq!(sig2.sample(), 13);
}
#[test]
fn signal_display() {
let sig1 = Signal::constant(42);
let sig2 = Signal::from_fn(|| 13);
assert_eq!(format!("{}", sig1), "42");
assert_eq!(format!("{}", sig2), "13");
}
#[test]
fn signal_channel() {
let (tx, rx) = mpsc::channel();
let sig = Signal::fold_channel(0, rx, |a, n| a + n);
for i in 0..=10 {
tx.send(i).unwrap();
}
assert_eq!(sig.sample(), 55);
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub type ContactDataProviderConnection = *mut ::core::ffi::c_void;
pub type ContactDataProviderTriggerDetails = *mut ::core::ffi::c_void;
pub type ContactListCreateOrUpdateContactRequest = *mut ::core::ffi::c_void;
pub type ContactListCreateOrUpdateContactRequestEventArgs = *mut ::core::ffi::c_void;
pub type ContactListDeleteContactRequest = *mut ::core::ffi::c_void;
pub type ContactListDeleteContactRequestEventArgs = *mut ::core::ffi::c_void;
pub type ContactListServerSearchReadBatchRequest = *mut ::core::ffi::c_void;
pub type ContactListServerSearchReadBatchRequestEventArgs = *mut ::core::ffi::c_void;
pub type ContactListSyncManagerSyncRequest = *mut ::core::ffi::c_void;
pub type ContactListSyncManagerSyncRequestEventArgs = *mut ::core::ffi::c_void;
|
use bigdecimal::BigDecimal;
pub struct Point {
// [-90;+90]
pub latitude: BigDecimal,
// [-180;+180)
pub longitude: BigDecimal,
}
|
fn double[T](a: &T) -> T[] { ret ~[a] + ~[a]; }
fn double_int(a: int) -> int[] { ret ~[a] + ~[a]; }
fn main() {
let d = double(1);
assert (d.(0) == 1);
assert (d.(1) == 1);
d = double_int(1);
assert (d.(0) == 1);
assert (d.(1) == 1);
}
|
// 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::util::{get_source_kind, SourceKind};
use crate::{env, errors::Result};
use clap::ArgMatches;
use io::BufReader;
use lexer::Tokenizer;
use std::io::Write;
use std::io::{self, Read};
use termcolor::{Color, ColorSpec};
use tremor_common::ids::OperatorIdGen;
use tremor_script::highlighter::{Dumb as TermNoHighlighter, Highlighter, Term as TermHighlighter};
use tremor_script::lexer::{self, Token};
use tremor_script::pos::{Span, Spanned};
use tremor_script::query::Query;
use tremor_script::script::Script;
struct Opts<'src> {
banner: bool,
raw_output: bool,
kind: SourceKind,
src: &'src str,
raw: String,
}
fn banner<W>(h: &mut W, opts: &Opts, section: &str, detail: &str) -> Result<()>
where
W: Highlighter,
{
if opts.banner {
let mut banner = ColorSpec::new();
let mut banner = banner.set_fg(Some(Color::Green));
h.set_color(&mut banner)?;
let spec = format!(
"\n\n****************\n* {} - {}\n****************\n\n",
section, detail
);
write!(h.get_writer(), "{}", spec,)?;
}
Ok(())
}
fn preprocessed_tokens<'input>(
opts: &Opts,
input: &'input mut String,
) -> Result<Vec<Spanned<'input>>> {
let mut include_stack = lexer::IncludeStack::default();
let cu = include_stack.push(&opts.src)?;
let lexemes: Vec<_> = lexer::Preprocessor::preprocess(
&tremor_script::path::load(),
opts.src,
input,
cu,
&mut include_stack,
)?
.into_iter()
.filter_map(std::result::Result::ok)
.collect();
Ok(lexemes)
}
fn dbg_src<W>(h: &mut W, opts: &Opts, preprocess: bool) -> Result<()>
where
W: Highlighter,
{
banner(h, opts, "Source", "Source code listing")?;
match &opts.kind {
SourceKind::Tremor | SourceKind::Json => {
if preprocess {
let mut raw_src = opts.raw.clone();
let lexemes = preprocessed_tokens(opts, &mut raw_src)?;
h.highlight(None, &lexemes, "", !opts.raw_output, None)?;
} else {
Script::highlight_script_with(&opts.raw, h, !&opts.raw_output)?;
}
}
SourceKind::Trickle => {
if preprocess {
let mut raw_src = opts.raw.clone();
let lexemes = preprocessed_tokens(opts, &mut raw_src)?;
h.highlight(None, &lexemes, "", !opts.raw_output, None)?;
} else {
Query::highlight_script_with(&opts.raw, h, !opts.raw_output)?;
}
}
SourceKind::Yaml => error!("Unsupported: yaml"),
SourceKind::Unsupported(Some(t)) => error!("Unsupported: {}", t),
SourceKind::Unsupported(None) => error!("Unsupported: no file type"),
}
Ok(())
}
fn dbg_tokens<W>(h: &mut W, lexemes: Vec<Spanned>) -> Result<()>
where
W: Highlighter,
{
let mut default = ColorSpec::new();
let mut line = ColorSpec::new();
let mut line = line.set_fg(Some(Color::Blue));
let mut directive = ColorSpec::new();
let mut directive = directive.set_fg(Some(Color::White));
for l in lexemes {
let Spanned {
span:
Span {
start,
end,
pp_start,
pp_end,
},
value,
} = l;
match &value {
// We ignore whitespace and newlines
Token::Whitespace(_)
| Token::NewLine
// TODO Enhance to support doc/mod ( multi-line ) comments
| Token::DocComment(_)
| Token::ModComment(_) => (),
Token::ConfigDirective => {
h.set_color(&mut line)?;
let line_spec = format!(
"{}:{} - {}:{}",
start.line(), start.column(), end.line(), end.column()
);
write!(h.get_writer(), "{:^16} \u{2219} ", line_spec,)?;
h.set_color(&mut directive)?;
writeln!(h.get_writer(), " #!config ")?;
}
Token::LineDirective(_location, file) => {
h.set_color(&mut line)?;
let line_spec = format!(
"{}:{} - {}:{}",
start.line(), start.column(), end.line(), end.column()
);
write!(h.get_writer(), "{:^16} \u{2219} ", line_spec,)?;
h.set_color(&mut directive)?;
writeln!(h.get_writer(), " #!line {}", file.to_string())?;
}
_other_token => {
h.set_color(&mut line)?;
let line_spec = format!(
"{}:{} - {}:{}",
start.line(), start.column(), end.line(), end.column()
);
write!(h.get_writer(), "{:^16} \u{2219} ", line_spec,)?;
h.set_color(&mut default)?;
write!(
&mut h.get_writer(),
" {:<30} \u{2219} ",
format!("{:?}", value).split('(').collect::<Vec<&str>>()[0]
)?;
h.highlight(
None,
&[Spanned {
span: Span { start, end, pp_start, pp_end },
value,
}],
"",
false,
None
)?;
}
}
}
Ok(())
}
fn dbg_lex<W>(h: &mut W, opts: &Opts, preprocess: bool) -> Result<()>
where
W: Highlighter,
{
if preprocess {
banner(
h,
opts,
"Lexemes",
"Lexical token stream after preprocessing",
)?;
let mut raw_src = opts.raw.clone();
let lexemes = preprocessed_tokens(opts, &mut raw_src)?;
dbg_tokens(h, lexemes)?;
} else {
banner(
h,
opts,
"Lexemes",
"Lexical token stream before preprocessing",
)?;
let lexemes: Vec<_> = Tokenizer::new(&opts.raw).tokenize_until_err().collect();
dbg_tokens(h, lexemes)?;
}
h.reset()?;
Ok(())
}
fn dbg_ast<'src, W>(h: &mut W, opts: &Opts<'src>, exprs_only: bool) -> Result<()>
where
W: Highlighter,
{
banner(h, opts, "AST", "Abstract Syntax Tree")?;
let env = env::setup()?;
match opts.kind {
SourceKind::Tremor | SourceKind::Json => {
match Script::parse(&env.module_path, opts.src, opts.raw.clone(), &env.fun) {
Ok(runnable) => {
let ast = if exprs_only {
simd_json::to_string_pretty(&runnable.script.suffix().exprs)?
} else {
simd_json::to_string_pretty(&runnable.script.suffix())?
};
println!();
Script::highlight_script_with(&ast, h, !opts.raw_output)?;
}
Err(e) => {
if let Err(e) = Script::format_error_from_script(&opts.raw, h, &e) {
eprintln!("Error: {}", e);
};
}
}
}
SourceKind::Trickle => {
match Query::parse(
&env.module_path,
opts.src,
&opts.raw,
vec![],
&env.fun,
&env.aggr,
) {
Ok(runnable) => {
let ast = simd_json::to_string_pretty(&runnable.query.suffix())?;
println!();
Script::highlight_script_with(&ast, h, !opts.raw_output)?;
}
Err(e) => {
if let Err(e) = Script::format_error_from_script(&opts.raw, h, &e) {
eprintln!("Error: {}", e);
};
}
};
}
SourceKind::Unsupported(_) | SourceKind::Yaml => {
eprintln!("Unsupported");
}
};
h.reset()?;
Ok(())
}
fn script_opts(matches: &ArgMatches, no_banner: bool, raw_output: bool) -> Result<Opts> {
let src = matches.value_of("SCRIPT");
let mut raw = String::new();
let mut buffer: Box<dyn Read> = match src {
None | Some("-") => Box::new(BufReader::new(io::stdin())),
Some(data) => Box::new(BufReader::new(crate::open_file(data, None)?)),
};
let kind = match src {
None | Some("-") => SourceKind::Tremor,
Some(data) => get_source_kind(data),
};
let src = match src {
None | Some("-") => "<stdin>",
Some(data) => data,
};
buffer.read_to_string(&mut raw)?;
println!();
raw.push('\n'); // Ensure last token is whitespace
let opts = Opts {
banner: !no_banner,
raw_output,
src,
kind,
raw,
};
Ok(opts)
}
fn dbg_dot<W>(h: &mut W, opts: &Opts) -> Result<()>
where
W: Highlighter,
{
if opts.kind != SourceKind::Trickle {
return Err("Dot visualisation is only supported for trickle files.".into());
}
let env = env::setup()?;
match Query::parse(
&env.module_path,
opts.src,
&opts.raw,
vec![],
&env.fun,
&env.aggr,
) {
Ok(runnable) => {
let mut idgen = OperatorIdGen::new();
let g = tremor_pipeline::query::Query(runnable).to_pipe(&mut idgen)?;
println!("{}", g.dot);
}
Err(e) => {
if let Err(e) = Script::format_error_from_script(&opts.raw, h, &e) {
eprintln!("Error: {}", e);
};
}
};
Ok(())
}
pub(crate) fn run_cmd(matches: &ArgMatches) -> Result<()> {
let raw = matches.is_present("raw");
// Do not highlist or put banner when raw provided raw flag.
let no_highlight = matches.is_present("no-highlight") || raw;
let no_banner = matches.is_present("no-banner") || raw;
if no_highlight {
let mut h = TermNoHighlighter::new();
let r = if let Some(args) = matches.subcommand_matches("ast") {
let opts = script_opts(args, no_banner, raw)?;
let exprs_only = args.is_present("exprs-only");
dbg_ast(&mut h, &opts, exprs_only)
} else if let Some(args) = matches.subcommand_matches("lex") {
let opts = script_opts(args, no_banner, raw)?;
let preprocess = args.is_present("preprocess");
dbg_lex(&mut h, &opts, preprocess)
} else if let Some(args) = matches.subcommand_matches("src") {
let opts = script_opts(args, no_banner, raw)?;
let preprocess = args.is_present("preprocess");
dbg_src(&mut h, &opts, preprocess)
} else if let Some(args) = matches.subcommand_matches("dot") {
let opts = script_opts(args, no_banner, raw)?;
dbg_dot(&mut h, &opts)
} else {
Err("Missing subcommand".into())
};
h.finalize()?;
h.reset()?;
println!("{}", h.to_string());
r?;
} else {
let mut h = TermHighlighter::default();
let r = if let Some(args) = matches.subcommand_matches("ast") {
let opts = script_opts(args, no_banner, raw)?;
let exprs_only = args.is_present("exprs-only");
dbg_ast(&mut h, &opts, exprs_only)
} else if let Some(args) = matches.subcommand_matches("lex") {
let opts = script_opts(args, no_banner, raw)?;
let preprocess = args.is_present("preprocess");
dbg_lex(&mut h, &opts, preprocess)
} else if let Some(args) = matches.subcommand_matches("src") {
let opts = script_opts(args, no_banner, raw)?;
let preprocess = args.is_present("preprocess");
dbg_src(&mut h, &opts, preprocess)
} else if let Some(args) = matches.subcommand_matches("dot") {
let opts = script_opts(args, no_banner, raw)?;
dbg_dot(&mut h, &opts)
} else {
Err("Missing subcommand".into())
};
h.finalize()?;
h.reset()?;
r?;
};
Ok(())
}
|
use crate::{
app::{
config::{self, Rgba},
sample::{create_sample_plume, Sample},
AppContext, AppContextPointer, ZoomableDrawingAreas,
},
coords::{DeviceCoords, DtHCoords, ScreenCoords, ScreenRect, XYCoords},
errors::SondeError,
gui::{
plot_context::{GenericContext, HasGenericContext, PlotContext, PlotContextExt},
utility::{check_overlap_then_add, draw_filled_polygon, plot_curve_from_points},
Drawable, DrawingArgs, MasterDrawable,
},
};
use gtk::{
prelude::*, DrawingArea, EventControllerKey, EventControllerMotion, EventControllerScroll,
EventControllerScrollFlags, GestureClick, Inhibit,
};
use itertools::izip;
use metfor::{CelsiusDiff, Meters, Quantity};
use std::rc::Rc;
pub struct FirePlumeContext {
generic: GenericContext,
}
impl FirePlumeContext {
pub fn new() -> Self {
FirePlumeContext {
generic: GenericContext::new(),
}
}
pub fn convert_dth_to_xy(coords: DtHCoords) -> XYCoords {
let min_h = config::MIN_FIRE_PLUME_HEIGHT.unpack();
let max_h = config::MAX_FIRE_PLUME_HEIGHT.unpack();
let DtHCoords {
dt,
height: Meters(h),
} = coords;
let x = super::convert_dt_to_x(dt);
let y = (h - min_h) / (max_h - min_h);
XYCoords { x, y }
}
pub fn convert_xy_to_dth(coords: XYCoords) -> DtHCoords {
let min_h = config::MIN_FIRE_PLUME_HEIGHT.unpack();
let max_h = config::MAX_FIRE_PLUME_HEIGHT.unpack();
let XYCoords { x, y } = coords;
let dt = super::convert_x_to_dt(x);
let height = Meters(y * (max_h - min_h) + min_h);
DtHCoords { dt, height }
}
pub fn convert_dth_to_screen(&self, coords: DtHCoords) -> ScreenCoords {
let xy = FirePlumeContext::convert_dth_to_xy(coords);
self.convert_xy_to_screen(xy)
}
pub fn convert_device_to_dth(&self, coords: DeviceCoords) -> DtHCoords {
let xy = self.convert_device_to_xy(coords);
Self::convert_xy_to_dth(xy)
}
}
impl HasGenericContext for FirePlumeContext {
fn get_generic_context(&self) -> &GenericContext {
&self.generic
}
}
impl PlotContextExt for FirePlumeContext {
fn convert_xy_to_screen(&self, coords: XYCoords) -> ScreenCoords {
super::convert_xy_to_screen(self, coords)
}
/// Conversion from (x,y) coords to screen coords
fn convert_screen_to_xy(&self, coords: ScreenCoords) -> XYCoords {
super::convert_screen_to_xy(self, coords)
}
}
impl Drawable for FirePlumeContext {
/***********************************************************************************************
* Initialization
**********************************************************************************************/
fn set_up_drawing_area(acp: &AppContextPointer) -> Result<(), SondeError> {
let da: DrawingArea = acp.fetch_widget("fire_plume_height_area")?;
// Set up the drawing function.
let ac = Rc::clone(acp);
da.set_draw_func(move |_da, cr, _width, _height| {
ac.fire_plume.draw_callback(cr, &ac);
});
// Set up the scroll (or zoom in/out) callbacks.
let ac = Rc::clone(acp);
let scroll_control = EventControllerScroll::new(EventControllerScrollFlags::VERTICAL);
scroll_control.connect_scroll(move |_scroll_control, _dx, dy| {
ac.mark_background_dirty();
ac.fire_plume.scroll_event(dy, &ac);
Inhibit(true)
});
da.add_controller(scroll_control);
// Set up the button clicks.
let left_mouse_button = GestureClick::builder().build();
let ac = Rc::clone(acp);
left_mouse_button.connect_pressed(move |_mouse_button, _n_pressed, x, y| {
ac.fire_plume.left_button_press_event((x, y), &ac);
});
let ac = Rc::clone(acp);
left_mouse_button.connect_released(move |_mouse_button, _n_press, x, y| {
ac.fire_plume.left_button_release_event((x, y), &ac);
});
da.add_controller(left_mouse_button);
let right_mouse_button = GestureClick::builder().button(3).build();
let ac = Rc::clone(acp);
right_mouse_button.connect_released(move |_mouse_button, _n_press, x, y| {
ac.fire_plume.right_button_release_event((x, y), &ac);
});
da.add_controller(right_mouse_button);
// Set up the mouse motion events
let mouse_motion = EventControllerMotion::new();
let ac = Rc::clone(acp);
mouse_motion.connect_motion(move |mouse_motion, x, y| {
ac.fire_plume.mouse_motion_event(mouse_motion, (x, y), &ac);
});
let ac = Rc::clone(acp);
mouse_motion.connect_enter(move |_mouse_motion, _x, _y| {
ac.fire_plume.enter_event(&ac);
});
let ac = Rc::clone(acp);
mouse_motion.connect_leave(move |_mouse_motion| {
ac.fire_plume.leave_event(&ac);
});
da.add_controller(mouse_motion);
// Set up the key presses.
let key_press = EventControllerKey::new();
let ac = Rc::clone(acp);
key_press.connect_key_pressed(move |_key_press, key, _code, _key_modifier| {
FirePlumeContext::key_press_event(key, &ac)
});
da.add_controller(key_press);
let ac = Rc::clone(acp);
da.connect_resize(move |da, width, height| {
// TODO merge below methods into one.
ac.fire_plume.size_allocate_event(da);
ac.fire_plume.resize_event(width, height, &ac);
});
Ok(())
}
// Shouldn't override, but need to set font size larger. Failure to DRY.
fn prepare_to_make_text(&self, args: DrawingArgs<'_, '_>) {
super::prepare_to_make_text(self, args)
}
/***********************************************************************************************
* Background Drawing.
**********************************************************************************************/
fn draw_background_fill(&self, _args: DrawingArgs<'_, '_>) {}
fn draw_background_lines(&self, args: DrawingArgs<'_, '_>) {
let (cr, config) = (args.cr, args.ac.config.borrow());
// Draw iso heights
for pnts in config::FIRE_PLUME_HEIGHT_PNTS.iter() {
let pnts = pnts
.iter()
.map(|xy_coords| self.convert_xy_to_screen(*xy_coords));
plot_curve_from_points(cr, config.background_line_width, config.isobar_rgba, pnts);
}
super::draw_iso_dts(self, &config, cr);
}
fn collect_labels(&self, args: DrawingArgs<'_, '_>) -> Vec<(String, ScreenRect)> {
let (ac, cr) = (args.ac, args.cr);
let mut labels = vec![];
let screen_edges = self.calculate_plot_edges(cr, ac);
let ScreenRect { lower_left, .. } = screen_edges;
for &dt in config::FIRE_PLUME_DTS.iter().skip(1) {
let label = format!("{:.0}\u{00B0}C", dt.unpack());
let extents = cr.text_extents(&label).unwrap();
let ScreenCoords {
x: mut screen_x, ..
} = self.convert_dth_to_screen(DtHCoords {
dt,
height: Meters(0.0),
});
screen_x -= extents.width() / 2.0;
let label_lower_left = ScreenCoords {
x: screen_x,
y: lower_left.y,
};
let label_upper_right = ScreenCoords {
x: screen_x + extents.width(),
y: lower_left.y + extents.height(),
};
let pair = (
label,
ScreenRect {
lower_left: label_lower_left,
upper_right: label_upper_right,
},
);
check_overlap_then_add(cr, ac, &mut labels, &screen_edges, pair);
}
for &h in config::FIRE_PLUME_HEIGHTS.iter().skip(1) {
let label = format!("{:.0}", h.unpack() / 1_000.0);
let extents = cr.text_extents(&label).unwrap();
let ScreenCoords {
y: mut screen_y, ..
} = self.convert_dth_to_screen(DtHCoords {
dt: CelsiusDiff(0.0),
height: h,
});
screen_y -= extents.height() / 2.0;
let label_lower_left = ScreenCoords {
x: lower_left.x,
y: screen_y,
};
let label_upper_right = ScreenCoords {
x: lower_left.x + extents.width(),
y: screen_y + extents.height(),
};
let pair = (
label,
ScreenRect {
lower_left: label_lower_left,
upper_right: label_upper_right,
},
);
check_overlap_then_add(cr, ac, &mut labels, &screen_edges, pair);
}
labels
}
fn build_legend_strings(ac: &AppContext) -> Vec<(String, Rgba)> {
let config = ac.config.borrow();
vec![
(
"Level of Max Int. Buoyancy (km)".to_owned(),
config.fire_plume_lmib_color,
),
(
"Lifting Condensation Level (km)".to_owned(),
config.fire_plume_lcl_color,
),
(
"Max Plume Height (km)".to_owned(),
config.fire_plume_maxh_color,
),
]
}
/***********************************************************************************************
* Data Drawing.
**********************************************************************************************/
fn draw_data(&self, args: DrawingArgs<'_, '_>) {
let (ac, cr) = (args.ac, args.cr);
let config = ac.config.borrow();
let anal = match ac.get_sounding_for_display() {
Some(anal) => anal,
None => return,
};
let anal = anal.borrow();
if let (Some(vals_low), Some(vals_high)) =
(anal.plume_heating_low(), anal.plume_heating_high())
{
let line_width = config.profile_line_width;
let lmib_rgba = config.fire_plume_lmib_color;
let mut lmib_polygon_color = lmib_rgba;
lmib_polygon_color.3 /= 2.0;
let max_hgt_rgba = config.fire_plume_maxh_color;
let mut max_hgt_polygon_color = max_hgt_rgba;
max_hgt_polygon_color.3 /= 2.0;
let lcl_rgba = config.fire_plume_lcl_color;
let mut lcl_polygon_color = lcl_rgba;
lcl_polygon_color.3 /= 2.0;
let els_low = izip!(&vals_low.dts, &vals_low.el_heights)
.filter_map(|(&dt, height)| height.map(|h| (dt, h)))
.map(|(dt, height)| DtHCoords { dt, height })
.map(|dt_coord| ac.fire_plume.convert_dth_to_screen(dt_coord));
let els_high = izip!(&vals_high.dts, &vals_high.el_heights)
.filter_map(|(&dt, height)| height.map(|h| (dt, h)))
.map(|(dt, height)| DtHCoords { dt, height })
.map(|dt_coord| ac.fire_plume.convert_dth_to_screen(dt_coord));
let polygon = els_low.clone().chain(els_high.clone().rev());
draw_filled_polygon(cr, lmib_polygon_color, polygon);
plot_curve_from_points(cr, line_width, lmib_rgba, els_low);
plot_curve_from_points(cr, line_width, lmib_rgba, els_high);
let lcls_low = izip!(&vals_low.dts, &vals_low.lcl_heights)
.filter_map(|(&dt, height)| height.map(|h| (dt, h)))
.map(|(dt, height)| DtHCoords { dt, height })
.map(|dt_coord| ac.fire_plume.convert_dth_to_screen(dt_coord));
let lcls_high = izip!(&vals_high.dts, &vals_high.lcl_heights)
.filter_map(|(&dt, height)| height.map(|h| (dt, h)))
.map(|(dt, height)| DtHCoords { dt, height })
.map(|dt_coord| ac.fire_plume.convert_dth_to_screen(dt_coord));
let polygon = lcls_low.clone().chain(lcls_high.clone().rev());
draw_filled_polygon(cr, lcl_polygon_color, polygon);
plot_curve_from_points(cr, line_width, lcl_rgba, lcls_low);
plot_curve_from_points(cr, line_width, lcl_rgba, lcls_high);
let maxhs_low = izip!(&vals_low.dts, &vals_low.max_heights)
.filter_map(|(&dt, height)| height.map(|h| (dt, h)))
.map(|(dt, height)| DtHCoords { dt, height })
.map(|dt_coord| ac.fire_plume.convert_dth_to_screen(dt_coord));
let maxhs_high = izip!(&vals_high.dts, &vals_high.max_heights)
.filter_map(|(&dt, height)| height.map(|h| (dt, h)))
.map(|(dt, height)| DtHCoords { dt, height })
.map(|dt_coord| ac.fire_plume.convert_dth_to_screen(dt_coord));
let polygon = maxhs_low.clone().chain(maxhs_high.clone().rev());
draw_filled_polygon(cr, max_hgt_polygon_color, polygon);
plot_curve_from_points(cr, line_width, max_hgt_rgba, maxhs_low);
plot_curve_from_points(cr, line_width, max_hgt_rgba, maxhs_high);
}
}
/***********************************************************************************************
* Overlays Drawing.
**********************************************************************************************/
fn draw_active_sample(&self, args: DrawingArgs<'_, '_>) {
if !self.has_data() {
return;
}
let (ac, config) = (args.ac, args.ac.config.borrow());
let vals = ac.get_sample();
if let Sample::FirePlume {
plume_anal_low,
plume_anal_high,
..
} = *vals
{
let t0 = match ac.get_sounding_for_display() {
Some(anal) => match anal.borrow().starting_parcel_for_blow_up_anal() {
Some(pcl) => pcl.temperature,
None => return,
},
None => return,
};
let pnt_color = config.active_readout_line_rgba;
let dt_low = plume_anal_low.parcel.temperature - t0;
let dt_high = plume_anal_high.parcel.temperature - t0;
if let Some(lmib_low) = plume_anal_low.el_height.into_option() {
let lmib_pnt = DtHCoords {
dt: dt_low,
height: lmib_low,
};
let screen_coords_el = ac.fire_plume.convert_dth_to_screen(lmib_pnt);
Self::draw_point(screen_coords_el, pnt_color, args);
}
if let Some(lmib_high) = plume_anal_high.el_height.into_option() {
let lmib_pnt = DtHCoords {
dt: dt_high,
height: lmib_high,
};
let screen_coords_el = ac.fire_plume.convert_dth_to_screen(lmib_pnt);
Self::draw_point(screen_coords_el, pnt_color, args);
}
if let Some(maxh_low) = plume_anal_low.max_height.into_option() {
let maxh_pnt = DtHCoords {
dt: dt_low,
height: maxh_low,
};
let screen_coords_maxh = ac.fire_plume.convert_dth_to_screen(maxh_pnt);
Self::draw_point(screen_coords_maxh, pnt_color, args);
}
if let Some(maxh_high) = plume_anal_high.max_height.into_option() {
let maxh_pnt = DtHCoords {
dt: dt_high,
height: maxh_high,
};
let screen_coords_maxh = ac.fire_plume.convert_dth_to_screen(maxh_pnt);
Self::draw_point(screen_coords_maxh, pnt_color, args);
}
if let Some(lcl_low) = plume_anal_low.lcl_height.into_option() {
let lcl_pnt = DtHCoords {
dt: dt_low,
height: lcl_low,
};
let screen_coords_lcl = ac.fire_plume.convert_dth_to_screen(lcl_pnt);
Self::draw_point(screen_coords_lcl, pnt_color, args);
}
if let Some(lcl_high) = plume_anal_high.lcl_height.into_option() {
let lcl_pnt = DtHCoords {
dt: dt_high,
height: lcl_high,
};
let screen_coords_lcl = ac.fire_plume.convert_dth_to_screen(lcl_pnt);
Self::draw_point(screen_coords_lcl, pnt_color, args);
}
}
}
/***********************************************************************************************
* Events
**********************************************************************************************/
fn mouse_motion_event(
&self,
controller: &EventControllerMotion,
new_position: (f64, f64),
ac: &AppContextPointer,
) {
let da: DrawingArea = controller.widget().downcast().unwrap();
da.grab_focus();
let position = DeviceCoords::from(new_position);
if self.get_left_button_pressed() {
if let Some(last_position) = self.get_last_cursor_position() {
let old_position = self.convert_device_to_xy(last_position);
let new_position = self.convert_device_to_xy(position);
let delta = (
new_position.x - old_position.x,
new_position.y - old_position.y,
);
let mut translate = self.get_translate();
translate.x -= delta.0;
translate.y -= delta.1;
self.set_translate(translate);
self.bound_view();
self.mark_background_dirty();
crate::gui::draw_all(ac);
ac.set_sample(Sample::None);
}
} else if ac.plottable() {
let sample = ac
.get_sounding_for_display()
.and_then(|anal| {
let DtHCoords { dt, .. } = self.convert_device_to_dth(position);
let pcl = anal.borrow().starting_parcel_for_blow_up_anal();
pcl.map(|pcl| (anal, pcl, dt))
})
.map(|(anal, pcl, dt)| {
create_sample_plume(pcl, pcl.temperature + dt, &anal.borrow())
})
.unwrap_or(Sample::None);
ac.set_sample(sample);
ac.mark_overlay_dirty();
crate::gui::draw_all(ac);
}
self.set_last_cursor_position(Some(position));
}
fn enter_event(&self, ac: &AppContextPointer) {
ac.set_last_focus(ZoomableDrawingAreas::FirePlume);
}
}
impl MasterDrawable for FirePlumeContext {}
|
/// pretyy print menggunakan format `{:#?}`
///
#[derive(Debug)]
struct Person {
name: &'static str,
age: u8,
}
fn main() {
let name = "Agus";
let age = 35;
let agus = Person { name, age };
println!("{:#?}", agus);
} |
use std::time::Duration;
use assert_matches::assert_matches;
use data_types::NamespaceId;
use generated_types::influxdata::{
iox::{
ingester::v1::WriteRequest,
namespace::v1::{namespace_service_server::NamespaceService, *},
partition_template::v1::*,
table::v1::{table_service_server::TableService, *},
},
pbdata::v1::DatabaseBatch,
};
use hyper::StatusCode;
use iox_catalog::interface::{Error as CatalogError, SoftDeletedRows};
use iox_time::{SystemProvider, TimeProvider};
use router::{
dml_handlers::{CachedServiceProtectionLimit, DmlError, RetentionError, SchemaError},
namespace_resolver::{self, NamespaceCreationError},
server::http::Error,
};
use test_helpers::assert_error;
use tonic::{Code, Request};
use crate::common::TestContextBuilder;
pub mod common;
/// Ensure invoking the gRPC NamespaceService to create a namespace populates
/// the catalog.
#[tokio::test]
async fn test_namespace_create() {
// Initialise a TestContext without a namespace autocreation policy.
let ctx = TestContextBuilder::default().build().await;
// Try writing to the non-existent namespace, which should return an error.
let now = SystemProvider::default()
.now()
.timestamp_nanos()
.to_string();
let lp = "platanos,tag1=A,tag2=B val=42i ".to_string() + &now;
let response = ctx
.write_lp("bananas", "test", &lp)
.await
.expect_err("write failed");
assert_matches!(
response,
Error::NamespaceResolver(namespace_resolver::Error::Create(
NamespaceCreationError::Reject(_)
))
);
assert_eq!(
response.to_string(),
"rejecting write due to non-existing namespace: bananas_test"
);
// The failed write MUST NOT populate the catalog.
{
let current = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::AllRows)
.await
.expect("failed to query for existing namespaces");
assert!(current.is_empty());
}
// The RPC endpoint must know nothing about the namespace either.
{
let current = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert!(current.namespaces.is_empty());
}
const RETENTION: i64 = Duration::from_secs(42 * 60 * 60).as_nanos() as _;
// Explicitly create the namespace.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: Some(RETENTION),
partition_template: None,
service_protection_limits: None,
};
let got = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await
.expect("failed to create namespace")
.into_inner()
.namespace
.expect("no namespace in response");
assert_eq!(got.name, "bananas_test");
assert_eq!(got.id, 1);
assert_eq!(got.retention_period_ns, Some(RETENTION));
// The list namespace RPC should show the new namespace
{
let list = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert_matches!(list.namespaces.as_slice(), [ns] => {
assert_eq!(*ns, got);
});
}
// The catalog should contain the namespace.
{
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::ExcludeDeleted)
.await
.expect("query failure");
assert_matches!(db_list.as_slice(), [ns] => {
assert_eq!(ns.id.get(), got.id);
assert_eq!(ns.name, got.name);
assert_eq!(ns.retention_period_ns, got.retention_period_ns);
assert!(ns.deleted_at.is_none());
});
}
// And writing should succeed
let response = ctx
.write_lp("bananas", "test", lp)
.await
.expect("write failed");
assert_eq!(response.status(), StatusCode::NO_CONTENT);
}
/// Ensure invoking the gRPC NamespaceService to delete a namespace propagates
/// the catalog and denies writes after the cache has converged / router
/// restarted.
#[tokio::test]
async fn test_namespace_delete() {
// Initialise a TestContext with implicit namespace creation.
let ctx = TestContextBuilder::default()
.with_autocreate_namespace(None)
.build()
.await;
const RETENTION: i64 = Duration::from_secs(42 * 60 * 60).as_nanos() as _;
// Explicitly create the namespace.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: Some(RETENTION),
partition_template: None,
service_protection_limits: None,
};
let got = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await
.expect("failed to create namespace")
.into_inner()
.namespace
.expect("no namespace in response");
assert_eq!(got.name, "bananas_test");
assert_eq!(got.id, 1);
assert_eq!(got.retention_period_ns, Some(RETENTION));
// The namespace is usable.
let now = SystemProvider::default()
.now()
.timestamp_nanos()
.to_string();
let lp = "platanos,tag1=A,tag2=B val=42i ".to_string() + &now;
let response = ctx
.write_lp("bananas", "test", &lp)
.await
.expect("write failed");
assert_eq!(response.status(), StatusCode::NO_CONTENT);
// The RPC endpoint must return a namespace.
{
let current = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert!(!current.namespaces.is_empty());
}
// Delete the namespace
{
let _resp = ctx
.grpc_delegate()
.namespace_service()
.delete_namespace(Request::new(DeleteNamespaceRequest {
name: "bananas_test".to_string(),
}))
.await
.expect("must delete");
}
// The RPC endpoint must not return the namespace.
{
let current = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert!(current.namespaces.is_empty());
}
// The catalog should contain the namespace, but "soft-deleted".
{
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::ExcludeDeleted)
.await
.expect("query failure");
assert!(db_list.is_empty());
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::OnlyDeleted)
.await
.expect("query failure");
assert_matches!(db_list.as_slice(), [ns] => {
assert_eq!(ns.id.get(), got.id);
assert_eq!(ns.name, got.name);
assert_eq!(ns.retention_period_ns, got.retention_period_ns);
assert!(ns.deleted_at.is_some());
});
}
// The cached entry is not affected, and writes continue to be validated
// against cached entry.
//
// https://github.com/influxdata/influxdb_iox/issues/6175
let response = ctx
.write_lp("bananas", "test", &lp)
.await
.expect("write failed");
assert_eq!(response.status(), StatusCode::NO_CONTENT);
// The router restarts, and writes are no longer accepted for the
// soft-deleted bucket.
let ctx = ctx.restart().await;
let err = ctx
.write_lp("bananas", "test", lp)
.await
.expect_err("write should fail");
assert_matches!(
err,
router::server::http::Error::NamespaceResolver(router::namespace_resolver::Error::Lookup(
iox_catalog::interface::Error::NamespaceNotFoundByName { .. }
))
);
}
/// Ensure creating a namespace with a retention period of 0 maps to "infinite"
/// and not "none".
#[tokio::test]
async fn test_create_namespace_0_retention_period() {
// Initialise a test context without implicit namespace creation policy.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create the namespace.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: Some(0), // A zero!
partition_template: None,
service_protection_limits: None,
};
let got = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await
.expect("failed to create namespace")
.into_inner()
.namespace
.expect("no namespace in response");
assert_eq!(got.name, "bananas_test");
assert_eq!(got.id, 1);
assert_eq!(got.retention_period_ns, None);
// The list namespace RPC should show the new namespace
{
let list = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert_matches!(list.namespaces.as_slice(), [ns] => {
assert_eq!(*ns, got);
});
}
// The catalog should contain the namespace.
{
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::ExcludeDeleted)
.await
.expect("query failure");
assert_matches!(db_list.as_slice(), [ns] => {
assert_eq!(ns.id.get(), got.id);
assert_eq!(ns.name, got.name);
assert_eq!(ns.retention_period_ns, got.retention_period_ns);
assert!(ns.deleted_at.is_none());
});
}
// And writing should succeed
let response = ctx
.write_lp("bananas", "test", "platanos,tag1=A,tag2=B val=42i 42424242")
.await
.expect("write failed");
assert_eq!(response.status(), StatusCode::NO_CONTENT);
}
/// Ensure creating a namespace with a negative retention period is rejected.
#[tokio::test]
async fn test_create_namespace_negative_retention_period() {
let ctx = TestContextBuilder::default().build().await;
// Explicitly create the namespace.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: Some(-42),
partition_template: None,
service_protection_limits: None,
};
let err = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await
.expect_err("negative retention period should fail to create namespace");
assert_eq!(err.code(), Code::InvalidArgument);
assert_eq!(err.message(), "invalid negative retention period");
// The list namespace RPC should not show a new namespace
{
let list = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert!(list.namespaces.is_empty());
}
// The catalog should not contain the namespace.
{
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::AllRows)
.await
.expect("query failure");
assert!(db_list.is_empty());
}
// And writing should not succeed
let response = ctx
.write_lp("bananas", "test", "platanos,tag1=A,tag2=B val=42i 42424242")
.await
.expect_err("write should fail");
assert_matches!(
response,
Error::NamespaceResolver(namespace_resolver::Error::Create(
NamespaceCreationError::Reject(_)
))
);
}
/// Ensure updating a namespace with a retention period of 0 maps to "infinite"
/// and not "none".
#[tokio::test]
async fn test_update_namespace_0_retention_period() {
// Initialise a TestContext requiring explicit namespace creation.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create the namespace.
let create = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: Some(42),
partition_template: None,
service_protection_limits: None,
}))
.await
.expect("failed to create namespace")
.into_inner()
.namespace
.expect("no namespace in response");
// And writing in the past should fail
ctx.write_lp("bananas", "test", "platanos,tag1=A,tag2=B val=42i 42424242")
.await
.expect_err("write outside retention period should fail");
let got = ctx
.grpc_delegate()
.namespace_service()
.update_namespace_retention(Request::new(UpdateNamespaceRetentionRequest {
name: "bananas_test".to_string(),
retention_period_ns: Some(0), // A zero!
}))
.await
.expect("failed to create namespace")
.into_inner()
.namespace
.expect("no namespace in response");
assert_eq!(got.name, create.name);
assert_eq!(got.id, create.id);
assert_eq!(create.retention_period_ns, Some(42));
assert_eq!(got.retention_period_ns, None);
// The list namespace RPC should show the updated namespace
{
let list = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert_matches!(list.namespaces.as_slice(), [ns] => {
assert_eq!(*ns, got);
});
}
// The catalog should contain the namespace.
{
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::ExcludeDeleted)
.await
.expect("query failure");
assert_matches!(db_list.as_slice(), [ns] => {
assert_eq!(ns.id.get(), got.id);
assert_eq!(ns.name, got.name);
assert_eq!(ns.retention_period_ns, got.retention_period_ns);
assert!(ns.deleted_at.is_none());
});
}
// The cached entry is not affected, and writes continue to be validated
// against the old value.
//
// https://github.com/influxdata/influxdb_iox/issues/6175
let err = ctx
.write_lp("bananas", "test", "platanos,tag1=A,tag2=B val=42i 42424242")
.await
.expect_err("cached entry rejects write");
assert_matches!(
err,
router::server::http::Error::DmlHandler(DmlError::Retention(
RetentionError::OutsideRetention{table_name, min_acceptable_ts, observed_ts}
)) => {
assert_eq!(table_name, "platanos");
assert!(observed_ts < min_acceptable_ts);
}
);
// The router restarts, and writes are then accepted.
let ctx = ctx.restart().await;
let response = ctx
.write_lp("bananas", "test", "platanos,tag1=A,tag2=B val=42i 42424242")
.await
.expect("cached entry should be removed");
assert_eq!(response.status(), StatusCode::NO_CONTENT);
}
/// Ensure updating a namespace with a negative retention period fails.
#[tokio::test]
async fn test_update_namespace_negative_retention_period() {
// Initialise a TestContext requiring explicit namespace creation.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create the namespace.
let create = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: Some(42),
partition_template: None,
service_protection_limits: None,
}))
.await
.expect("failed to create namespace")
.into_inner()
.namespace
.expect("no namespace in response");
let err = ctx
.grpc_delegate()
.namespace_service()
.update_namespace_retention(Request::new(UpdateNamespaceRetentionRequest {
name: "bananas_test".to_string(),
retention_period_ns: Some(-42),
}))
.await
.expect_err("negative retention period should fail to create namespace");
assert_eq!(err.code(), Code::InvalidArgument);
assert_eq!(err.message(), "invalid negative retention period");
// The list namespace RPC should show the original namespace
{
let list = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert_matches!(list.namespaces.as_slice(), [ns] => {
assert_eq!(*ns, create);
});
}
// The catalog should contain the original namespace.
{
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::ExcludeDeleted)
.await
.expect("query failure");
assert_matches!(db_list.as_slice(), [ns] => {
assert_eq!(ns.id.get(), create.id);
assert_eq!(ns.name, create.name);
assert_eq!(ns.retention_period_ns, create.retention_period_ns);
});
}
}
#[tokio::test]
async fn test_update_namespace_limit_max_tables() {
// Initialise a TestContext with namespace autocreation.
let ctx = TestContextBuilder::default()
.with_autocreate_namespace(None)
.build()
.await;
// Writing to two initial tables should succeed
ctx.write_lp("bananas", "test", "ananas,tag1=A,tag2=B val=42i 42424242")
.await
.expect("write should succeed");
ctx.write_lp("bananas", "test", "platanos,tag3=C,tag4=D val=99i 42424243")
.await
.expect("write should succeed");
// Limit the maximum number of tables to prevent a write adding another table
let got = ctx
.grpc_delegate()
.namespace_service()
.update_namespace_service_protection_limit(Request::new(
UpdateNamespaceServiceProtectionLimitRequest {
name: "bananas_test".to_string(),
limit_update: Some(
update_namespace_service_protection_limit_request::LimitUpdate::MaxTables(1),
),
},
))
.await
.expect("failed to update namespace max table limit")
.into_inner()
.namespace
.expect("no namespace in response");
assert_eq!(got.name, "bananas_test");
assert_eq!(got.id, 1);
assert_eq!(got.max_tables, 1);
assert_eq!(
got.max_columns_per_table,
iox_catalog::DEFAULT_MAX_COLUMNS_PER_TABLE
);
// The list namespace RPC should show the updated namespace
{
let list = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert_matches!(list.namespaces.as_slice(), [ns] => {
assert_eq!(*ns, got);
});
}
// The catalog should contain the namespace.
{
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::ExcludeDeleted)
.await
.expect("query failure");
assert_matches!(db_list.as_slice(), [ns] => {
assert_eq!(ns.id.get(), got.id);
assert_eq!(ns.name, got.name);
assert_eq!(ns.retention_period_ns, got.retention_period_ns);
assert_eq!(ns.max_tables, got.max_tables);
assert_eq!(ns.max_columns_per_table, got.max_columns_per_table);
assert!(ns.deleted_at.is_none());
});
}
// New table should fail to be created by the catalog.
let err = ctx
.write_lp(
"bananas",
"test",
"arán_banana,tag1=A,tag2=B val=42i 42424244",
)
.await
.expect_err("cached entry should be removed");
assert_matches!(err, router::server::http::Error::DmlHandler(DmlError::Schema(SchemaError::ServiceLimit(e))) => {
let e: CatalogError = *e.downcast::<CatalogError>().expect("error returned should be a table create limit error");
assert_matches!(&e, CatalogError::TableCreateLimitError { table_name, .. } => {
assert_eq!(table_name, "arán_banana");
assert_eq!(e.to_string(), "couldn't create table arán_banana; limit reached on namespace 1")
});
});
}
#[tokio::test]
async fn test_update_namespace_limit_max_columns_per_table() {
// Initialise a TestContext with namespace autocreation.
let ctx = TestContextBuilder::default()
.with_autocreate_namespace(None)
.build()
.await;
// Initial write within limit should succeed
ctx.write_lp("bananas", "test", "ananas,tag1=A,tag2=B val=42i 42424242")
.await
.expect("write should succeed");
// Limit the maximum number of columns per table so an extra column is rejected
let got = ctx
.grpc_delegate()
.namespace_service()
.update_namespace_service_protection_limit(Request::new(
UpdateNamespaceServiceProtectionLimitRequest {
name: "bananas_test".to_string(),
limit_update: Some(
update_namespace_service_protection_limit_request::LimitUpdate::MaxColumnsPerTable(1),
),
},
))
.await
.expect("failed to update namespace max table limit")
.into_inner()
.namespace
.expect("no namespace in response");
assert_eq!(got.name, "bananas_test");
assert_eq!(got.id, 1);
assert_eq!(got.max_tables, iox_catalog::DEFAULT_MAX_TABLES);
assert_eq!(got.max_columns_per_table, 1);
// The list namespace RPC should show the updated namespace
{
let list = ctx
.grpc_delegate()
.namespace_service()
.get_namespaces(Request::new(Default::default()))
.await
.expect("must return namespaces")
.into_inner();
assert_matches!(list.namespaces.as_slice(), [ns] => {
assert_eq!(*ns, got);
});
}
// The catalog should contain the namespace.
{
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::ExcludeDeleted)
.await
.expect("query failure");
assert_matches!(db_list.as_slice(), [ns] => {
assert_eq!(ns.id.get(), got.id);
assert_eq!(ns.name, got.name);
assert_eq!(ns.retention_period_ns, got.retention_period_ns);
assert_eq!(ns.max_tables, got.max_tables);
assert_eq!(ns.max_columns_per_table, got.max_columns_per_table);
assert!(ns.deleted_at.is_none());
});
}
// The cached entry is not affected, and writes continue to be validated
// against the old value.
//
// https://github.com/influxdata/influxdb_iox/issues/6175
// Writing to second table should succeed while using the cached entry
ctx.write_lp(
"bananas",
"test",
"platanos,tag1=A,tag2=B val=1337i 42424243",
)
.await
.expect("write should succeed");
// The router restarts, and writes with too many columns are then rejected.
let ctx = ctx.restart().await;
let err = ctx
.write_lp(
"bananas",
"test",
"arán_banana,tag1=A,tag2=B val=76i 42424243",
)
.await
.expect_err("cached entry should be removed and write should be blocked");
assert_matches!(
err, router::server::http::Error::DmlHandler(DmlError::Schema(
SchemaError::ServiceLimit(e)
)) => {
let e: CachedServiceProtectionLimit = *e.downcast::<CachedServiceProtectionLimit>().expect("error returned should be a cached service protection limit");
assert_matches!(e, CachedServiceProtectionLimit::Column {
table_name,
max_columns_per_table,
..
} => {
assert_eq!(table_name, "arán_banana");
assert_eq!(max_columns_per_table, 1);
});
}
)
}
#[tokio::test]
async fn test_update_namespace_limit_0_max_tables_max_columns() {
// Initialise a TestContext requiring explicit namespace creation.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create the namespace.
let create = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: Some(0),
partition_template: None,
service_protection_limits: None,
}))
.await
.expect("failed to create namespace")
.into_inner()
.namespace
.expect("no namespace in response");
// Attempt to use an invalid table limit
let err = ctx
.grpc_delegate()
.namespace_service()
.update_namespace_service_protection_limit(Request::new(
UpdateNamespaceServiceProtectionLimitRequest {
name: "bananas_test".to_string(),
limit_update: Some(
update_namespace_service_protection_limit_request::LimitUpdate::MaxTables(0),
),
},
))
.await
.expect_err("should not have been able to update the table limit to 0");
assert_eq!(err.code(), Code::InvalidArgument);
// Attempt to use an invalid column limit
let err = ctx
.grpc_delegate()
.namespace_service()
.update_namespace_service_protection_limit(Request::new(
UpdateNamespaceServiceProtectionLimitRequest {
name: "bananas_test".to_string(),
limit_update: Some(
update_namespace_service_protection_limit_request::LimitUpdate::MaxColumnsPerTable(0),
),
},
))
.await
.expect_err("should not have been able to update the column per table limit to 0");
assert_eq!(err.code(), Code::InvalidArgument);
// The catalog should contain the namespace unchanged.
{
let db_list = ctx
.catalog()
.repositories()
.await
.namespaces()
.list(SoftDeletedRows::ExcludeDeleted)
.await
.expect("query failure");
assert_matches!(db_list.as_slice(), [ns] => {
assert_eq!(ns.id.get(), create.id);
assert_eq!(ns.name, create.name);
assert_eq!(ns.retention_period_ns, create.retention_period_ns);
assert_eq!(ns.max_tables, create.max_tables);
assert_eq!(ns.max_columns_per_table, create.max_columns_per_table);
assert!(ns.deleted_at.is_none());
});
}
}
/// Ensure invoking the gRPC TableService to create a table populates
/// the catalog.
#[tokio::test]
async fn test_table_create() {
// Initialise a TestContext without a namespace autocreation policy.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create the namespace.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: None,
partition_template: None,
service_protection_limits: None,
};
let namespace = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await
.unwrap()
.into_inner()
.namespace
.unwrap();
// Explicitly create the table.
let req = CreateTableRequest {
name: "plantains".to_string(),
namespace: "bananas_test".to_string(),
partition_template: None,
};
let got = ctx
.grpc_delegate()
.table_service()
.create_table(Request::new(req))
.await
.unwrap()
.into_inner()
.table
.unwrap();
assert_eq!(got.name, "plantains");
assert_eq!(got.id, 1);
// The catalog should contain the table.
{
let db_list = ctx
.catalog()
.repositories()
.await
.tables()
.list_by_namespace_id(NamespaceId::new(namespace.id))
.await
.unwrap();
assert_matches!(db_list.as_slice(), [table] => {
assert_eq!(table.id.get(), got.id);
assert_eq!(table.name, got.name);
});
}
let lp = "plantains,tag1=A,tag2=B val=42i 1685026200000000000".to_string();
// Writing should succeed and should use the default partition template because no partition
// template was set on either the namespace or the table.
let response = ctx.write_lp("bananas", "test", lp).await.unwrap();
assert_eq!(response.status(), StatusCode::NO_CONTENT);
let writes = ctx.write_calls();
assert_eq!(writes.len(), 1);
assert_matches!(
writes.as_slice(),
[
WriteRequest {
payload: Some(DatabaseBatch {
table_batches,
partition_key,
..
}),
},
] => {
let table_id = ctx.table_id("bananas_test", "plantains").await.get();
assert_eq!(table_batches.len(), 1);
assert_eq!(table_batches[0].table_id, table_id);
assert_eq!(partition_key, "2023-05-25");
})
}
#[tokio::test]
async fn test_invalid_strftime_partition_template() {
// Initialise a TestContext without a namespace autocreation policy.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create a namespace with a custom partition template.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: None,
partition_template: Some(PartitionTemplate {
parts: vec![TemplatePart {
part: Some(template_part::Part::TimeFormat("%3F".into())),
}],
}),
service_protection_limits: None,
};
// Check namespace creation returned an error
let got = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await;
assert_error!(
got,
ref status
if status.code() == Code::InvalidArgument
&& status.message() == "invalid strftime format in partition template: %3F"
);
}
#[tokio::test]
async fn test_invalid_tag_value_partition_template() {
// Initialise a TestContext without a namespace autocreation policy.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create a namespace with a custom partition template.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: None,
partition_template: Some(PartitionTemplate {
parts: vec![TemplatePart {
part: Some(template_part::Part::TagValue("time".into())),
}],
}),
service_protection_limits: None,
};
// Check namespace creation returned an error
let got = ctx
.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await;
assert_error!(
got,
ref status
if status.code() == Code::InvalidArgument
&& status.message() == "invalid tag value in partition template: time cannot be used"
);
}
#[tokio::test]
async fn test_namespace_partition_template_implicit_table_creation() {
// Initialise a TestContext without a namespace autocreation policy.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create a namespace with a custom partition template.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: None,
partition_template: Some(PartitionTemplate {
parts: vec![TemplatePart {
part: Some(template_part::Part::TagValue("tag1".into())),
}],
}),
service_protection_limits: None,
};
ctx.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await
.unwrap()
.into_inner()
.namespace
.unwrap();
// Write, which implicitly creates the table with the namespace's custom partition template
let lp = "plantains,tag1=A,tag2=B val=42i".to_string();
let response = ctx.write_lp("bananas", "test", lp).await.unwrap();
assert_eq!(response.status(), StatusCode::NO_CONTENT);
// Check the ingester observed the correct write that uses the namespace's template.
let writes = ctx.write_calls();
assert_eq!(writes.len(), 1);
assert_matches!(
writes.as_slice(),
[
WriteRequest {
payload: Some(DatabaseBatch {
table_batches,
partition_key,
..
}),
},
] => {
let table_id = ctx.table_id("bananas_test", "plantains").await.get();
assert_eq!(table_batches.len(), 1);
assert_eq!(table_batches[0].table_id, table_id);
assert_eq!(partition_key, "A");
});
}
#[tokio::test]
async fn test_namespace_partition_template_explicit_table_creation_without_partition_template() {
// Initialise a TestContext without a namespace autocreation policy.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create a namespace with a custom partition template.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: None,
partition_template: Some(PartitionTemplate {
parts: vec![TemplatePart {
part: Some(template_part::Part::TagValue("tag1".into())),
}],
}),
service_protection_limits: None,
};
ctx.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await
.unwrap()
.into_inner()
.namespace
.unwrap();
// Explicitly create a table *without* a custom partition template.
let req = CreateTableRequest {
name: "plantains".to_string(),
namespace: "bananas_test".to_string(),
partition_template: None,
};
ctx.grpc_delegate()
.table_service()
.create_table(Request::new(req))
.await
.unwrap()
.into_inner()
.table
.unwrap();
// Write to the just-created table
let lp = "plantains,tag1=A,tag2=B val=42i".to_string();
let response = ctx.write_lp("bananas", "test", lp).await.unwrap();
assert_eq!(response.status(), StatusCode::NO_CONTENT);
// Check the ingester observed the correct write that uses the namespace's template.
let writes = ctx.write_calls();
assert_eq!(writes.len(), 1);
assert_matches!(
writes.as_slice(),
[
WriteRequest {
payload: Some(DatabaseBatch {
table_batches,
partition_key,
..
}),
},
] => {
let table_id = ctx.table_id("bananas_test", "plantains").await.get();
assert_eq!(table_batches.len(), 1);
assert_eq!(table_batches[0].table_id, table_id);
assert_eq!(partition_key, "A");
});
}
#[tokio::test]
async fn test_namespace_partition_template_explicit_table_creation_with_partition_template() {
// Initialise a TestContext without a namespace autocreation policy.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create a namespace with a custom partition template.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: None,
partition_template: Some(PartitionTemplate {
parts: vec![TemplatePart {
part: Some(template_part::Part::TagValue("tag1".into())),
}],
}),
service_protection_limits: None,
};
ctx.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await
.unwrap()
.into_inner()
.namespace
.unwrap();
// Explicitly create a table with a *different* custom partition template.
let req = CreateTableRequest {
name: "plantains".to_string(),
namespace: "bananas_test".to_string(),
partition_template: Some(PartitionTemplate {
parts: vec![TemplatePart {
part: Some(template_part::Part::TagValue("tag2".into())),
}],
}),
};
ctx.grpc_delegate()
.table_service()
.create_table(Request::new(req))
.await
.unwrap()
.into_inner()
.table
.unwrap();
// Write to the just-created table
let lp = "plantains,tag1=A,tag2=B val=42i".to_string();
let response = ctx.write_lp("bananas", "test", lp).await.unwrap();
assert_eq!(response.status(), StatusCode::NO_CONTENT);
// Check the ingester observed the correct write that uses the table's template.
let writes = ctx.write_calls();
assert_eq!(writes.len(), 1);
assert_matches!(
writes.as_slice(),
[
WriteRequest {
payload: Some(DatabaseBatch {
table_batches,
partition_key,
..
}),
},
] => {
let table_id = ctx.table_id("bananas_test", "plantains").await.get();
assert_eq!(table_batches.len(), 1);
assert_eq!(table_batches[0].table_id, table_id);
assert_eq!(partition_key, "B");
});
}
#[tokio::test]
async fn test_namespace_without_partition_template_table_with_partition_template() {
// Initialise a TestContext without a namespace autocreation policy.
let ctx = TestContextBuilder::default().build().await;
// Explicitly create a namespace _without_ a custom partition template.
let req = CreateNamespaceRequest {
name: "bananas_test".to_string(),
retention_period_ns: None,
partition_template: None,
service_protection_limits: None,
};
ctx.grpc_delegate()
.namespace_service()
.create_namespace(Request::new(req))
.await
.unwrap()
.into_inner()
.namespace
.unwrap();
// Explicitly create a table _with_ a custom partition template.
let req = CreateTableRequest {
name: "plantains".to_string(),
namespace: "bananas_test".to_string(),
partition_template: Some(PartitionTemplate {
parts: vec![TemplatePart {
part: Some(template_part::Part::TagValue("tag2".into())),
}],
}),
};
ctx.grpc_delegate()
.table_service()
.create_table(Request::new(req))
.await
.unwrap()
.into_inner()
.table
.unwrap();
// Write to the just-created table
let lp = "plantains,tag1=A,tag2=B val=42i".to_string();
let response = ctx.write_lp("bananas", "test", lp).await.unwrap();
assert_eq!(response.status(), StatusCode::NO_CONTENT);
// Check the ingester observed the correct write that uses the table's template.
let writes = ctx.write_calls();
assert_eq!(writes.len(), 1);
assert_matches!(
writes.as_slice(),
[
WriteRequest {
payload: Some(DatabaseBatch {
table_batches,
partition_key,
..
}),
},
] => {
let table_id = ctx.table_id("bananas_test", "plantains").await.get();
assert_eq!(table_batches.len(), 1);
assert_eq!(table_batches[0].table_id, table_id);
assert_eq!(partition_key, "B");
});
}
|
use chamomile_types::message::DeliveryType as P2pDeliveryType;
use lazy_static::lazy_static;
use std::path::PathBuf;
/// P2P default binding addr.
pub const P2P_ADDR: &str = "0.0.0.0:7364";
/// P2P default transport.
pub const P2P_TRANSPORT: &str = "tcp";
/// RPC default binding addr.
pub const RPC_ADDR: &str = "127.0.0.1:8000";
/// Configure file name
pub const CONFIG_FILE_NAME: &str = "config.toml";
pub const DEFAULT_SECRET: [u8; 32] = [0u8; 32];
pub const DEFAULT_STORAGE_DIR_NAME: &str = ".tdn";
lazy_static! {
pub static ref DEFAULT_STORAGE_DIR: PathBuf = {
#[cfg(feature = "dev")]
let mut path = PathBuf::from("./");
#[cfg(not(feature = "dev"))]
let mut path = if dirs::home_dir().is_some() {
dirs::home_dir().unwrap()
} else {
PathBuf::from("./")
};
path.push(DEFAULT_STORAGE_DIR_NAME);
let _ = std::fs::create_dir_all(&path)
.expect(&format!("Cannot Build Storage Path: {:?}", path));
path
};
}
/// Type: PeerAddr
pub type PeerAddr = chamomile_types::types::PeerId;
/// Type: P2P common Broadcast
pub use chamomile_types::types::Broadcast;
/// Type: P2P stream type.
pub use chamomile_types::message::StreamType;
/// Type: P2P transport stream type.
pub use chamomile_types::types::TransportStream;
pub type Result<T> = std::io::Result<T>;
#[inline]
pub fn new_io_error(info: &str) -> std::io::Error {
std::io::Error::new(std::io::ErrorKind::Other, info)
}
#[inline]
pub fn vec_remove_item<T: Eq + PartialEq>(vec: &mut Vec<T>, item: &T) {
if let Some(pos) = vec.iter().position(|x| x == item) {
vec.remove(pos);
}
}
#[inline]
pub fn vec_check_push<T: Eq + PartialEq>(vec: &mut Vec<T>, item: T) {
for i in vec.iter() {
if i == &item {
return;
}
}
vec.push(item);
}
/// message delivery feedback type, include three type,
/// `Connect`, `Result`, `Event`.
#[derive(Debug, Clone)]
pub enum DeliveryType {
Event,
Connect,
Result,
}
impl Into<P2pDeliveryType> for DeliveryType {
#[inline]
fn into(self) -> P2pDeliveryType {
match self {
DeliveryType::Event => P2pDeliveryType::Data,
DeliveryType::Connect => P2pDeliveryType::StableConnect,
DeliveryType::Result => P2pDeliveryType::StableResult,
}
}
}
impl Into<DeliveryType> for P2pDeliveryType {
#[inline]
fn into(self) -> DeliveryType {
match self {
P2pDeliveryType::Data => DeliveryType::Event,
P2pDeliveryType::StableConnect => DeliveryType::Connect,
P2pDeliveryType::StableResult => DeliveryType::Result,
}
}
}
#[cfg(not(feature = "single"))]
use crate::group::GroupId;
use crate::message::{NetworkType, SendType};
use crate::rpc::RpcParam;
/// Helper: this is the group/layer/rpc handle result in the network.
pub struct HandleResult {
/// rpc tasks: [(method, params)].
pub rpcs: Vec<RpcParam>,
/// group tasks: [GroupSendMessage]
#[cfg(any(feature = "single", feature = "std"))]
pub groups: Vec<SendType>,
/// group tasks: [GroupSendMessage]
#[cfg(any(feature = "full", feature = "multiple"))]
pub groups: Vec<(GroupId, SendType)>,
/// layer tasks: [LayerSendMessage]
#[cfg(feature = "std")]
pub layers: Vec<(GroupId, SendType)>,
/// layer tasks: [LayerSendMessage]
#[cfg(feature = "full")]
pub layers: Vec<(GroupId, GroupId, SendType)>,
/// network tasks: [NetworkType]
pub networks: Vec<NetworkType>,
}
impl<'a> HandleResult {
pub fn new() -> Self {
HandleResult {
rpcs: vec![],
#[cfg(any(
feature = "single",
feature = "std",
feature = "multiple",
feature = "full",
))]
groups: vec![],
#[cfg(any(feature = "full", feature = "std"))]
layers: vec![],
networks: vec![],
}
}
pub fn rpc(p: RpcParam) -> Self {
HandleResult {
rpcs: vec![p],
#[cfg(any(
feature = "single",
feature = "std",
feature = "multiple",
feature = "full",
))]
groups: vec![],
#[cfg(any(feature = "full", feature = "std"))]
layers: vec![],
networks: vec![],
}
}
#[cfg(any(feature = "single", feature = "std"))]
pub fn group(m: SendType) -> Self {
HandleResult {
rpcs: vec![],
groups: vec![m],
#[cfg(feature = "std")]
layers: vec![],
networks: vec![],
}
}
#[cfg(any(feature = "multiple", feature = "full"))]
pub fn group(gid: GroupId, m: SendType) -> Self {
HandleResult {
rpcs: vec![],
groups: vec![(gid, m)],
#[cfg(feature = "full")]
layers: vec![],
networks: vec![],
}
}
#[cfg(feature = "std")]
pub fn layer(gid: GroupId, m: SendType) -> Self {
HandleResult {
rpcs: vec![],
groups: vec![],
layers: vec![(gid, m)],
networks: vec![],
}
}
#[cfg(feature = "full")]
pub fn layer(fgid: GroupId, tgid: GroupId, m: SendType) -> Self {
HandleResult {
rpcs: vec![],
groups: vec![],
layers: vec![(fgid, tgid, m)],
networks: vec![],
}
}
pub fn network(m: NetworkType) -> Self {
HandleResult {
rpcs: vec![],
#[cfg(any(
feature = "single",
feature = "std",
feature = "multiple",
feature = "full",
))]
groups: vec![],
#[cfg(any(feature = "full", feature = "std"))]
layers: vec![],
networks: vec![m],
}
}
}
|
use crate::driver::pca::PCA9685;
use embedded_hal::blocking::i2c::{Write, WriteRead};
use motor_direction::*;
pub struct Motors<TI2C> {
pca: PCA9685<TI2C>,
}
impl<TI2C: Write + WriteRead> Motors<TI2C> {
pub fn init(pca: PCA9685<TI2C>, i2c: &mut TI2C) -> Result<Self, <TI2C as Write>::Error> {
let mut motors = Self { pca };
motors.all_off(i2c)?;
Ok(motors)
}
/// Set a motor's speed in the given direction.
/// Switches off the opposite direction, as a motor can't go both
/// forward and backward at the same time
pub fn set_motor_speed(
&mut self,
i2c: &mut TI2C,
motor_dir: &MotorDirection,
speed: u16,
) -> Result<(), <TI2C as Write>::Error> {
self.pca
.set_pwm(i2c, &motor_dir.ant().into(), 0x000, 0xFFF)?;
self.pca
.set_pwm(i2c, &(*motor_dir).into(), speed, 0xFFF - speed)
}
pub fn all_off(&mut self, i2c: &mut TI2C) -> Result<(), <TI2C as Write>::Error> {
self.pca
.set_pwm(i2c, &MotorDirection::flf().into(), 0x000, 0xFFF)?;
self.pca
.set_pwm(i2c, &MotorDirection::flb().into(), 0x000, 0xFFF)?;
self.pca
.set_pwm(i2c, &MotorDirection::frf().into(), 0x000, 0xFFF)?;
self.pca
.set_pwm(i2c, &MotorDirection::frb().into(), 0x000, 0xFFF)?;
self.pca
.set_pwm(i2c, &MotorDirection::rlf().into(), 0x000, 0xFFF)?;
self.pca
.set_pwm(i2c, &MotorDirection::rlb().into(), 0x000, 0xFFF)?;
self.pca
.set_pwm(i2c, &MotorDirection::rrf().into(), 0x000, 0xFFF)?;
self.pca
.set_pwm(i2c, &MotorDirection::rrb().into(), 0x000, 0xFFF)
}
}
pub mod motor_direction {
use crate::driver::pca;
#[derive(Copy, Clone, Debug)]
pub enum Motor {
FrontLeft,
FrontRight,
RearLeft,
RearRight,
}
#[derive(Copy, Clone, Debug)]
pub enum Direction {
Forward,
Backward,
}
#[derive(Copy, Clone, Debug)]
pub struct MotorDirection {
motor: Motor,
dir: Direction,
}
impl MotorDirection {
/// The MotorDirection's antagonist
pub fn ant(&self) -> Self {
match self.dir {
Direction::Forward => Self {
motor: self.motor,
dir: Direction::Backward,
},
Direction::Backward => Self {
motor: self.motor,
dir: Direction::Forward,
},
}
}
pub fn flf() -> Self {
(Motor::FrontLeft, Direction::Forward).into()
}
pub fn flb() -> Self {
(Motor::FrontLeft, Direction::Backward).into()
}
pub fn frf() -> Self {
(Motor::FrontRight, Direction::Forward).into()
}
pub fn frb() -> Self {
(Motor::FrontRight, Direction::Backward).into()
}
pub fn rlf() -> Self {
(Motor::RearLeft, Direction::Forward).into()
}
pub fn rlb() -> Self {
(Motor::RearLeft, Direction::Backward).into()
}
pub fn rrf() -> Self {
(Motor::RearRight, Direction::Forward).into()
}
pub fn rrb() -> Self {
(Motor::RearRight, Direction::Backward).into()
}
}
impl From<(Motor, Direction)> for MotorDirection {
fn from((motor, dir): (Motor, Direction)) -> Self {
Self { motor, dir }
}
}
impl From<MotorDirection> for pca::Led {
fn from(motor_dir: MotorDirection) -> Self {
use crate::driver::pca::Led::*;
use Direction::*;
use Motor::*;
let MotorDirection { motor, dir } = motor_dir;
match (motor, dir) {
(FrontLeft, Forward) => Led2,
(FrontLeft, Backward) => Led3,
(FrontRight, Forward) => Led0,
(FrontRight, Backward) => Led1,
(RearLeft, Forward) => Led4,
(RearLeft, Backward) => Led5,
(RearRight, Forward) => Led7,
(RearRight, Backward) => Led6,
}
}
}
/* NOTE: Black swag mobiel mapping
impl From<MotorDirection> for pca::Led {
fn from(motor_dir: MotorDirection) -> Self {
use crate::driver::pca::Led::*;
use Direction::*;
use Motor::*;
let MotorDirection { motor, dir } = motor_dir;
match (motor, dir) {
(FrontLeft, Forward) => Led0,
(FrontLeft, Backward) => Led1,
(FrontRight, Forward) => Led7,
(FrontRight, Backward) => Led6,
(RearLeft, Forward) => Led2,
(RearLeft, Backward) => Led3,
(RearRight, Forward) => Led4,
(RearRight, Backward) => Led5,
}
}
}
*/
}
|
// 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.
// lazy_static is required for re_find_static.
use lazy_static::lazy_static;
use nom::{
branch::alt,
bytes::complete::{escaped, is_not, tag},
character::complete::multispace0,
character::complete::{char, digit1, hex_digit1, one_of},
combinator::{map, map_res, opt, value},
error::{ErrorKind, ParseError},
multi::{many0, separated_nonempty_list},
named, re_find_static,
sequence::{delimited, preceded},
IResult,
};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct CompoundIdentifier {
pub namespace: Vec<String>,
pub name: String,
}
impl CompoundIdentifier {
pub fn nest(&self, name: String) -> CompoundIdentifier {
let mut namespace = self.namespace.clone();
namespace.push(self.name.clone());
CompoundIdentifier { namespace, name }
}
pub fn parent(&self) -> Option<CompoundIdentifier> {
let mut namespace = self.namespace.clone();
let name = namespace.pop()?;
Some(CompoundIdentifier { namespace, name })
}
}
impl ToString for CompoundIdentifier {
fn to_string(&self) -> String {
let mut temp = self.namespace.clone();
temp.push(self.name.clone());
temp.join(".")
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Include {
pub name: CompoundIdentifier,
pub alias: Option<String>,
}
#[derive(Debug, PartialEq)]
pub enum BindParserError {
Type(String),
StringLiteral(String),
NumericLiteral(String),
BoolLiteral(String),
Identifier(String),
Semicolon(String),
Assignment(String),
ListStart(String),
ListEnd(String),
ListSeparator(String),
LibraryKeyword(String),
UsingKeyword(String),
AsKeyword(String),
IfBlockStart(String),
IfBlockEnd(String),
IfKeyword(String),
ElseKeyword(String),
ConditionOp(String),
ConditionValue(String),
AcceptKeyword(String),
UnrecognisedInput(String),
Unknown(String, ErrorKind),
}
impl ParseError<&str> for BindParserError {
fn from_error_kind(input: &str, kind: ErrorKind) -> Self {
BindParserError::Unknown(input.to_string(), kind)
}
fn append(_input: &str, _kind: ErrorKind, e: Self) -> Self {
e
}
}
pub fn string_literal(input: &str) -> IResult<&str, String, BindParserError> {
let escapable = escaped(is_not(r#"\""#), '\\', one_of(r#"\""#));
let literal = delimited(char('"'), escapable, char('"'));
map_err(map(literal, |s: &str| s.to_string()), BindParserError::StringLiteral)(input)
}
pub fn numeric_literal(input: &str) -> IResult<&str, u64, BindParserError> {
let base10 = map_res(digit1, |s| u64::from_str_radix(s, 10));
let base16 = map_res(preceded(tag("0x"), hex_digit1), |s| u64::from_str_radix(s, 16));
// Note: When the base16 parser fails but input starts with '0x' this will succeed and return 0.
map_err(alt((base16, base10)), BindParserError::NumericLiteral)(input)
}
pub fn bool_literal(input: &str) -> IResult<&str, bool, BindParserError> {
let true_ = value(true, tag("true"));
let false_ = value(false, tag("false"));
map_err(alt((true_, false_)), BindParserError::BoolLiteral)(input)
}
pub fn identifier(input: &str) -> IResult<&str, String, BindParserError> {
named!(matcher<&str,&str>, re_find_static!(r"^[a-zA-Z]([a-zA-Z0-9_]*[a-zA-Z0-9])?"));
map_err(map(matcher, |s| s.to_string()), BindParserError::Identifier)(input)
}
pub fn compound_identifier(input: &str) -> IResult<&str, CompoundIdentifier, BindParserError> {
let (input, mut segments) = separated_nonempty_list(tag("."), identifier)(input)?;
// Segments must be nonempty, so it's safe to pop off the name.
let name = segments.pop().unwrap();
Ok((input, CompoundIdentifier { namespace: segments, name }))
}
pub fn using(input: &str) -> IResult<&str, Include, BindParserError> {
let as_keyword = map_err(ws(tag("as")), BindParserError::AsKeyword);
let (input, name) = compound_identifier(input)?;
let (input, alias) = opt(preceded(as_keyword, identifier))(input)?;
Ok((input, Include { name, alias }))
}
pub fn using_list(input: &str) -> IResult<&str, Vec<Include>, BindParserError> {
let using_keyword = map_err(ws(tag("using")), BindParserError::UsingKeyword);
let terminator = map_err(ws(tag(";")), BindParserError::Semicolon);
let using = delimited(using_keyword, ws(using), terminator);
many0(ws(using))(input)
}
// Reimplementation of nom::combinator::all_consuming with BindParserError error type.
pub fn all_consuming<'a, O, F>(f: F) -> impl Fn(&'a str) -> IResult<&'a str, O, BindParserError>
where
F: Fn(&'a str) -> IResult<&'a str, O, BindParserError>,
{
move |input: &'a str| {
let (input, res) = f(input)?;
if input.len() == 0 {
Ok((input, res))
} else {
Err(nom::Err::Error(BindParserError::UnrecognisedInput(input.to_string())))
}
}
}
// Wraps a parser |f| and discards zero or more whitespace characters before and after it.
pub fn ws<I, O, E: ParseError<I>, F>(f: F) -> impl Fn(I) -> IResult<I, O, E>
where
I: nom::InputTakeAtPosition<Item = char>,
F: Fn(I) -> IResult<I, O, E>,
{
delimited(multispace0, f, multispace0)
}
// Wraps a parser and replaces its error.
pub fn map_err<'a, O, P, G>(
parser: P,
f: G,
) -> impl Fn(&'a str) -> IResult<&'a str, O, BindParserError>
where
P: Fn(&'a str) -> IResult<&'a str, O, (&'a str, ErrorKind)>,
G: Fn(String) -> BindParserError,
{
move |input: &str| {
parser(input).map_err(|e| match e {
nom::Err::Error((i, _)) => nom::Err::Error(f(i.to_string())),
nom::Err::Failure((i, _)) => nom::Err::Failure(f(i.to_string())),
nom::Err::Incomplete(_) => {
unreachable!("Parser should never generate Incomplete errors")
}
})
}
}
#[macro_export]
macro_rules! make_identifier{
( $name:tt ) => {
{
CompoundIdentifier {
namespace: Vec::new(),
name: String::from($name),
}
}
};
( $namespace:tt , $($rest:tt)* ) => {
{
let mut identifier = make_identifier!($($rest)*);
identifier.namespace.insert(0, String::from($namespace));
identifier
}
};
}
#[cfg(test)]
mod test {
use super::*;
mod string_literal {
use super::*;
#[test]
fn basic() {
// Matches a string literal, leaves correct tail.
assert_eq!(string_literal(r#""abc 123"xyz"#), Ok(("xyz", "abc 123".to_string())));
}
#[test]
fn match_once() {
assert_eq!(string_literal(r#""abc""123""#), Ok((r#""123""#, "abc".to_string())));
}
#[test]
fn escaped() {
assert_eq!(
string_literal(r#""abc \"esc\" xyz""#),
Ok(("", r#"abc \"esc\" xyz"#.to_string()))
);
}
#[test]
fn requires_quotations() {
assert_eq!(
string_literal(r#"abc"#),
Err(nom::Err::Error(BindParserError::StringLiteral("abc".to_string())))
);
}
#[test]
fn empty() {
assert_eq!(
string_literal(""),
Err(nom::Err::Error(BindParserError::StringLiteral("".to_string())))
);
}
}
mod numeric_literals {
use super::*;
#[test]
fn decimal() {
assert_eq!(numeric_literal("123"), Ok(("", 123)));
}
#[test]
fn hex() {
assert_eq!(numeric_literal("0x123"), Ok(("", 0x123)));
assert_eq!(numeric_literal("0xabcdef"), Ok(("", 0xabcdef)));
assert_eq!(numeric_literal("0xABCDEF"), Ok(("", 0xabcdef)));
assert_eq!(numeric_literal("0x123abc"), Ok(("", 0x123abc)));
// Does not match hex without '0x' prefix.
assert_eq!(
numeric_literal("abc123"),
Err(nom::Err::Error(BindParserError::NumericLiteral("abc123".to_string())))
);
assert_eq!(numeric_literal("123abc"), Ok(("abc", 123)));
}
#[test]
fn non_numbers() {
assert_eq!(
numeric_literal("xyz"),
Err(nom::Err::Error(BindParserError::NumericLiteral("xyz".to_string())))
);
// Does not match negative numbers (for now).
assert_eq!(
numeric_literal("-1"),
Err(nom::Err::Error(BindParserError::NumericLiteral("-1".to_string())))
);
}
#[test]
fn overflow() {
// Does not match numbers larger than u64.
assert_eq!(numeric_literal("18446744073709551615"), Ok(("", 18446744073709551615)));
assert_eq!(numeric_literal("0xffffffffffffffff"), Ok(("", 18446744073709551615)));
assert_eq!(
numeric_literal("18446744073709551616"),
Err(nom::Err::Error(BindParserError::NumericLiteral(
"18446744073709551616".to_string()
)))
);
// Note: This is matching '0' from '0x' but failing to parse the entire string.
assert_eq!(numeric_literal("0x10000000000000000"), Ok(("x10000000000000000", 0)));
}
#[test]
fn empty() {
// Does not match an empty string.
assert_eq!(
numeric_literal(""),
Err(nom::Err::Error(BindParserError::NumericLiteral("".to_string())))
);
}
}
mod bool_literals {
use super::*;
#[test]
fn basic() {
assert_eq!(bool_literal("true"), Ok(("", true)));
assert_eq!(bool_literal("false"), Ok(("", false)));
}
#[test]
fn non_bools() {
// Does not match anything else.
assert_eq!(
bool_literal("tralse"),
Err(nom::Err::Error(BindParserError::BoolLiteral("tralse".to_string())))
);
}
#[test]
fn empty() {
// Does not match an empty string.
assert_eq!(
bool_literal(""),
Err(nom::Err::Error(BindParserError::BoolLiteral("".to_string())))
);
}
}
mod identifiers {
use super::*;
#[test]
fn basic() {
// Matches identifiers with lowercase, uppercase, digits, and underscores.
assert_eq!(identifier("abc_123_ABC"), Ok(("", "abc_123_ABC".to_string())));
// Match is terminated by whitespace or punctuation.
assert_eq!(identifier("abc_123_ABC "), Ok((" ", "abc_123_ABC".to_string())));
assert_eq!(identifier("abc_123_ABC;"), Ok((";", "abc_123_ABC".to_string())));
}
#[test]
fn invalid() {
// Does not match an identifier beginning or ending with '_'.
assert_eq!(
identifier("_abc"),
Err(nom::Err::Error(BindParserError::Identifier("_abc".to_string())))
);
// Note: Matches up until the '_' but fails to parse the entire string.
assert_eq!(identifier("abc_"), Ok(("_", "abc".to_string())));
}
#[test]
fn empty() {
// Does not match an empty string.
assert_eq!(
identifier(""),
Err(nom::Err::Error(BindParserError::Identifier("".to_string())))
);
}
}
mod compound_identifiers {
use super::*;
#[test]
fn single_identifier() {
// Matches single identifier.
assert_eq!(
compound_identifier("abc_123_ABC"),
Ok(("", make_identifier!["abc_123_ABC"]))
);
}
#[test]
fn multiple_identifiers() {
// Matches compound identifiers.
assert_eq!(compound_identifier("abc.def"), Ok(("", make_identifier!["abc", "def"])));
assert_eq!(
compound_identifier("abc.def.ghi"),
Ok(("", make_identifier!["abc", "def", "ghi"]))
);
}
#[test]
fn empty() {
// Does not match empty identifiers.
assert_eq!(
compound_identifier("."),
Err(nom::Err::Error(BindParserError::Identifier(".".to_string())))
);
assert_eq!(
compound_identifier(".abc"),
Err(nom::Err::Error(BindParserError::Identifier(".abc".to_string())))
);
assert_eq!(compound_identifier("abc..def"), Ok(("..def", make_identifier!["abc"])));
assert_eq!(compound_identifier("abc."), Ok((".", make_identifier!["abc"])));
// Does not match an empty string.
assert_eq!(
compound_identifier(""),
Err(nom::Err::Error(BindParserError::Identifier("".to_string())))
);
}
}
mod using_lists {
use super::*;
#[test]
fn one_include() {
assert_eq!(
using_list("using test;"),
Ok(("", vec![Include { name: make_identifier!["test"], alias: None }]))
);
}
#[test]
fn multiple_includes() {
assert_eq!(
using_list("using abc;using def;"),
Ok((
"",
vec![
Include { name: make_identifier!["abc"], alias: None },
Include { name: make_identifier!["def"], alias: None },
]
))
);
assert_eq!(
using_list("using abc;using def;using ghi;"),
Ok((
"",
vec![
Include { name: make_identifier!["abc"], alias: None },
Include { name: make_identifier!["def"], alias: None },
Include { name: make_identifier!["ghi"], alias: None },
]
))
);
}
#[test]
fn compound_identifiers() {
assert_eq!(
using_list("using abc.def;"),
Ok(("", vec![Include { name: make_identifier!["abc", "def"], alias: None }]))
);
}
#[test]
fn aliases() {
assert_eq!(
using_list("using abc.def as one;using ghi as two;"),
Ok((
"",
vec![
Include {
name: make_identifier!["abc", "def"],
alias: Some("one".to_string()),
},
Include { name: make_identifier!["ghi"], alias: Some("two".to_string()) },
]
))
);
}
#[test]
fn whitespace() {
assert_eq!(
using_list(" using abc\t as one ;\n using def ; "),
Ok((
"",
vec![
Include { name: make_identifier!["abc"], alias: Some("one".to_string()) },
Include { name: make_identifier!["def"], alias: None },
]
))
);
assert_eq!(
using_list("usingabc;"),
Ok(("", vec![Include { name: make_identifier!["abc"], alias: None }]))
);
}
#[test]
fn invalid() {
// Must be followed by ';'.
assert_eq!(using_list("using abc"), Ok(("using abc", vec![])));
}
#[test]
fn empty() {
assert_eq!(using_list(""), Ok(("", vec![])));
}
}
}
|
use std::fs::File;
use std::io::prelude::*;
use std::time::Instant;
use super::regex;
struct BenchmarkCase {
name: &'static str,
comment: &'static str,
filename: &'static str,
regex: &'static str,
}
pub fn run_all_tests<T>(stream: &mut T) -> Result<(), std::io::Error>
where
T: std::io::Write,
{
if cfg!(debug_assertions) {
eprintln!("[WARNING] Running benchmarks in debug mode.");
}
let benchmarks = vec![
BenchmarkCase {
name: "First columns of CSV",
comment: "Extract the first three columns of the input CSV document.",
filename: "benchmarks/pablo_alto_trees.csv",
regex: r"\n(?P<x>[^,]+),(?P<y>[^,]+),(?P<z>[^,]+),",
},
BenchmarkCase {
name: "Pairs of words",
comment: "Extract all pairs of words that are in the same sentence.",
filename: "benchmarks/lorem_ipsum.txt",
regex: r"[^\w](?P<word1>\w+)[^\w]((.|\n)*[^\w])?(?P<word2>\w+)[^\w]",
},
BenchmarkCase {
name: "Close DNA",
comment: "Find two substrings of a DNA sequence that are close from one another.",
filename: "benchmarks/dna.txt",
regex: r"TTAC.{0,1000}CACC",
},
BenchmarkCase {
name: "All substrings",
comment: "Extract all non-empty substrings from the input document.",
filename: "benchmarks/lorem_ipsum.txt",
regex: r"(.|\n)+",
},
];
for benchmark in benchmarks {
let mut input = String::new();
write!(stream, "-- {} ---------------\n", benchmark.name)?;
write!(stream, "{}\n", benchmark.comment)?;
// Read input file content.
write!(stream, " - Loading file content ... ")?;
stream.flush()?;
let timer = Instant::now();
File::open(benchmark.filename)?.read_to_string(&mut input)?;
write!(
stream,
"{:.2?}\t({} bytes)\n",
timer.elapsed(),
input.as_bytes().len()
)?;
// Run the test itself.
run_test(stream, benchmark.regex, input)?;
write!(stream, "\n")?;
}
Ok(())
}
/// Compute time spent on running the regex over the given input file.
fn run_test<T>(stream: &mut T, regex: &str, input: String) -> Result<(), std::io::Error>
where
T: std::io::Write,
{
// Compile the regex.
write!(stream, " - Compiling regex ... ")?;
stream.flush()?;
let timer = Instant::now();
let regex = regex::compile(regex);
write!(
stream,
"{:.2?}\t({} states)\n",
timer.elapsed(),
regex.get_nb_states()
)?;
// Prepare the enumeration.
write!(stream, " - Compiling matches ... ")?;
stream.flush()?;
let timer = Instant::now();
let compiled_matches = regex::compile_matches(regex, &input);
write!(
stream,
"{:.2?}\t({} levels)\n",
timer.elapsed(),
compiled_matches.get_nb_levels()
)?;
// Enumerate matches.
write!(stream, " - Enumerate matches ... ")?;
stream.flush()?;
let timer = Instant::now();
let count_matches = compiled_matches.iter().count();
write!(
stream,
"{:.2?}\t({} matches)\n",
timer.elapsed(),
count_matches
)?;
Ok(())
}
|
//! ParquetFile cache
use backoff::{Backoff, BackoffConfig};
use cache_system::{
backend::policy::{
lru::{LruPolicy, ResourcePool},
remove_if::{RemoveIfHandle, RemoveIfPolicy},
ttl::{ConstantValueTtlProvider, TtlPolicy},
PolicyBackend,
},
cache::{driver::CacheDriver, metrics::CacheWithMetrics, Cache},
loader::{metrics::MetricsLoader, FunctionLoader},
resource_consumption::FunctionEstimator,
};
use data_types::{ParquetFile, TableId};
use iox_catalog::interface::Catalog;
use iox_time::TimeProvider;
use snafu::{ResultExt, Snafu};
use std::{collections::HashMap, mem, sync::Arc, time::Duration};
use trace::span::Span;
use uuid::Uuid;
use super::ram::RamSize;
/// Duration to keep cached view.
///
/// This is currently `12h`.
pub const TTL: Duration = Duration::from_secs(12 * 60 * 60);
const CACHE_ID: &str = "parquet_file";
#[derive(Debug, Snafu)]
#[allow(missing_copy_implementations, missing_docs)]
pub enum Error {
#[snafu(display("CatalogError refreshing parquet file cache: {}", source))]
Catalog {
source: iox_catalog::interface::Error,
},
}
type IngesterCounts = Option<Arc<[(Uuid, u64)]>>;
/// Holds catalog information about a parquet file
#[derive(Debug)]
pub struct CachedParquetFiles {
/// Parquet catalog information
pub files: Arc<[Arc<ParquetFile>]>,
/// Number of persisted Parquet files per table ID per ingester UUID that ingesters have told
/// us about. When a call to `get` includes a number of persisted Parquet files for this table
/// and a particular ingester UUID that doesn't match what we've previously seen, the cache
/// needs to be expired.
///
/// **This list is sorted!**
persisted_file_counts_from_ingesters: IngesterCounts,
}
impl CachedParquetFiles {
fn new(
parquet_files: Vec<ParquetFile>,
persisted_file_counts_from_ingesters: IngesterCounts,
) -> Self {
let files = parquet_files.into_iter().map(Arc::new).collect();
Self {
files,
persisted_file_counts_from_ingesters,
}
}
/// return the underlying files as a new Vec
#[cfg(test)]
fn vec(&self) -> Vec<Arc<ParquetFile>> {
self.files.as_ref().to_vec()
}
/// Estimate the memory consumption of this object and its contents
fn size(&self) -> usize {
// simplify accounting by ensuring len and capacity of vector are the same
assert_eq!(self.files.len(), self.files.len());
// Note size_of_val is the size of the Arc
// https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=ae8fee8b4f7f5f013dc01ea1fda165da
// size of the Arc+(Option+HashMap) itself
mem::size_of_val(self) +
// Vec overhead
mem::size_of_val(self.files.as_ref()) +
// size of the underlying parquet files
self.files.iter().map(|f| f.size()).sum::<usize>() +
// hashmap data
self.persisted_file_counts_from_ingesters
.as_ref()
.map(|map| {
std::mem::size_of_val(map.as_ref()) +
map.len() * mem::size_of::<(Uuid, u64)>()
}).unwrap_or_default()
}
}
type CacheT = Box<
dyn Cache<
K = TableId,
V = Arc<CachedParquetFiles>,
GetExtra = (IngesterCounts, Option<Span>),
PeekExtra = ((), Option<Span>),
>,
>;
/// Cache for parquet file information.
///
/// DOES NOT CACHE the actual parquet bytes from object store
#[derive(Debug)]
pub struct ParquetFileCache {
cache: CacheT,
/// Handle that allows clearing entries for existing cache entries
remove_if_handle: RemoveIfHandle<TableId, Arc<CachedParquetFiles>>,
}
impl ParquetFileCache {
/// Create new empty cache.
pub fn new(
catalog: Arc<dyn Catalog>,
backoff_config: BackoffConfig,
time_provider: Arc<dyn TimeProvider>,
metric_registry: &metric::Registry,
ram_pool: Arc<ResourcePool<RamSize>>,
testing: bool,
) -> Self {
let loader = FunctionLoader::new(move |table_id: TableId, extra: IngesterCounts| {
let catalog = Arc::clone(&catalog);
let backoff_config = backoff_config.clone();
async move {
Backoff::new(&backoff_config)
.retry_all_errors("get parquet_files", || {
let extra = extra.clone();
async {
// TODO refreshing all parquet files for the
// entire table is likely to be quite wasteful
// for large tables.
//
// Some this code could be more efficeint:
//
// 1. incrementally fetch only NEW parquet
// files that aren't already in the cache
//
// 2. track time ranges needed for queries and
// limit files fetched to what is actually
// needed
let parquet_files: Vec<_> = catalog
.repositories()
.await
.parquet_files()
.list_by_table_not_to_delete(table_id)
.await
.context(CatalogSnafu)?;
Ok(Arc::new(CachedParquetFiles::new(parquet_files, extra)))
as std::result::Result<_, Error>
}
})
.await
.expect("retry forever")
}
});
let loader = Arc::new(MetricsLoader::new(
loader,
CACHE_ID,
Arc::clone(&time_provider),
metric_registry,
testing,
));
let mut backend = PolicyBackend::hashmap_backed(Arc::clone(&time_provider));
let (policy_constructor, remove_if_handle) =
RemoveIfPolicy::create_constructor_and_handle(CACHE_ID, metric_registry);
backend.add_policy(policy_constructor);
backend.add_policy(LruPolicy::new(
Arc::clone(&ram_pool),
CACHE_ID,
Arc::new(FunctionEstimator::new(
|k: &TableId, v: &Arc<CachedParquetFiles>| {
RamSize(mem::size_of_val(k) + mem::size_of_val(v) + v.size())
},
)),
));
backend.add_policy(TtlPolicy::new(
Arc::new(ConstantValueTtlProvider::new(Some(TTL))),
CACHE_ID,
metric_registry,
));
let cache = CacheDriver::new(loader, backend);
let cache = Box::new(CacheWithMetrics::new(
cache,
CACHE_ID,
time_provider,
metric_registry,
));
Self {
cache,
remove_if_handle,
}
}
/// Get list of cached parquet files, by table ID. This API is designed to be called with a
/// response from the ingster(s) so there is a single place where the invalidation logic
/// is handled.
///
/// # Expiration
///
/// Clear the Parquet file cache if the information from the ingesters contains an ingester
/// UUID we have never seen before (which indicates an ingester started or restarted) or if an
/// ingester UUID we *have* seen before reports a different number of persisted Parquet files
/// than what we've previously been told from the ingesters for this table. Otherwise, we can
/// use the cache.
pub async fn get(
&self,
table_id: TableId,
persisted_file_counts_by_ingester_uuid: Option<HashMap<Uuid, u64>>,
span: Option<Span>,
) -> Arc<CachedParquetFiles> {
let persisted_file_counts_by_ingester_uuid =
persisted_file_counts_by_ingester_uuid.map(|map| {
let mut entries = map.into_iter().collect::<Vec<_>>();
entries.sort();
entries.into()
});
let persisted_file_counts_by_ingester_uuid_captured =
persisted_file_counts_by_ingester_uuid.clone();
self.remove_if_handle
.remove_if_and_get(
&self.cache,
table_id,
|cached_file| {
if let Some(ingester_counts) = &persisted_file_counts_by_ingester_uuid_captured
{
// If there's new or different information about the ingesters or the
// number of files they've persisted, we need to refresh.
different(
cached_file
.persisted_file_counts_from_ingesters
.as_ref()
.map(|x| x.as_ref()),
ingester_counts,
)
} else {
false
}
},
(persisted_file_counts_by_ingester_uuid, span),
)
.await
}
/// Mark the entry for table_id as expired (and needs a refresh)
#[cfg(test)]
pub fn expire(&self, table_id: TableId) {
self.remove_if_handle.remove_if(&table_id, |_| true);
}
}
fn different(stored_counts: Option<&[(Uuid, u64)]>, ingester_counts: &[(Uuid, u64)]) -> bool {
// If we have some information stored for this table,
if let Some(stored) = stored_counts {
ingester_counts != stored
} else {
// Otherwise, we've never seen ingester file counts for this table.
// If the hashmap we got is empty, then we still haven't gotten any information, so we
// don't need to refresh the cache.
// If we did get information about the ingester state, then we do need to refresh the cache.
!ingester_counts.is_empty()
}
}
#[cfg(test)]
mod tests {
use std::{collections::HashSet, time::Duration};
use super::*;
use data_types::{ColumnType, ParquetFileId};
use iox_tests::{TestCatalog, TestNamespace, TestParquetFileBuilder, TestPartition, TestTable};
use crate::cache::{
ram::test_util::test_ram_pool, test_util::assert_catalog_access_metric_count,
};
const METRIC_NAME: &str = "parquet_list_by_table_not_to_delete";
const TABLE1_LINE_PROTOCOL: &str = "table1 foo=1 11";
const TABLE1_LINE_PROTOCOL2: &str = "table1 foo=2 22";
const TABLE1_LINE_PROTOCOL3: &str = "table1 foo=3 33";
const TABLE2_LINE_PROTOCOL: &str = "table2 foo=1 11";
#[tokio::test]
async fn test_parquet_chunks() {
let (catalog, table, partition) = make_catalog().await;
let builder = TestParquetFileBuilder::default().with_line_protocol(TABLE1_LINE_PROTOCOL);
let tfile = partition.create_parquet_file(builder).await;
let cache = make_cache(&catalog);
let cached_files = cache.get(table.table.id, None, None).await.vec();
assert_eq!(cached_files.len(), 1);
let expected_parquet_file = &tfile.parquet_file;
assert_eq!(cached_files[0].as_ref(), expected_parquet_file);
// validate a second request doesn't result in a catalog request
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 1);
cache.get(table.table.id, None, None).await;
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 1);
}
#[tokio::test]
async fn test_multiple_tables() {
let catalog = TestCatalog::new();
let ns = catalog.create_namespace_1hr_retention("ns").await;
let (table1, partition1) = make_table_and_partition("table1", &ns).await;
let (table2, partition2) = make_table_and_partition("table2", &ns).await;
let builder = TestParquetFileBuilder::default().with_line_protocol(TABLE1_LINE_PROTOCOL);
let tfile1 = partition1.create_parquet_file(builder).await;
let builder = TestParquetFileBuilder::default().with_line_protocol(TABLE2_LINE_PROTOCOL);
let tfile2 = partition2.create_parquet_file(builder).await;
let cache = make_cache(&catalog);
let cached_files = cache.get(table1.table.id, None, None).await.vec();
assert_eq!(cached_files.len(), 1);
let expected_parquet_file = &tfile1.parquet_file;
assert_eq!(cached_files[0].as_ref(), expected_parquet_file);
let cached_files = cache.get(table2.table.id, None, None).await.vec();
assert_eq!(cached_files.len(), 1);
let expected_parquet_file = &tfile2.parquet_file;
assert_eq!(cached_files[0].as_ref(), expected_parquet_file);
}
#[tokio::test]
async fn test_table_does_not_exist() {
let (_catalog, table, partition) = make_catalog().await;
let builder = TestParquetFileBuilder::default().with_line_protocol(TABLE1_LINE_PROTOCOL);
partition.create_parquet_file(builder).await;
// check in a different catalog where the table doesn't exist (yet)
let different_catalog = TestCatalog::new();
let cache = make_cache(&different_catalog);
let cached_files = cache.get(table.table.id, None, None).await.vec();
assert!(cached_files.is_empty());
}
#[tokio::test]
async fn test_size_estimation() {
let (catalog, table, partition) = make_catalog().await;
let builder = TestParquetFileBuilder::default().with_line_protocol(TABLE1_LINE_PROTOCOL);
partition.create_parquet_file(builder).await;
let table_id = table.table.id;
let single_file_size = 256;
let two_file_size = 480;
assert!(single_file_size < two_file_size);
let cache = make_cache(&catalog);
let cached_files = cache.get(table_id, None, None).await;
assert_eq!(cached_files.size(), single_file_size);
// add a second file, and force the cache to find it
let builder = TestParquetFileBuilder::default().with_line_protocol(TABLE1_LINE_PROTOCOL);
partition.create_parquet_file(builder).await;
cache.expire(table_id);
let cached_files = cache.get(table_id, None, None).await;
assert_eq!(cached_files.size(), two_file_size);
}
#[tokio::test]
async fn ingester_uuid_file_counts() {
let (catalog, table, _partition) = make_catalog().await;
let uuid = Uuid::new_v4();
let table_id = table.table.id;
let cache = make_cache(&catalog);
// No metadata: make one request that should be cached
cache.get(table_id, None, None).await;
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 1);
cache.get(table_id, None, None).await;
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 1);
// Empty metadata: make one request, should still be cached
cache.get(table_id, Some(HashMap::new()), None).await;
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 1);
// See a new UUID: refresh the cache
cache
.get(table_id, Some(HashMap::from([(uuid, 3)])), None)
.await;
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 2);
// See the same UUID with the same count: should still be cached
cache
.get(table_id, Some(HashMap::from([(uuid, 3)])), None)
.await;
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 2);
// See the same UUID with a different count: refresh the cache
cache
.get(table_id, Some(HashMap::from([(uuid, 4)])), None)
.await;
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 3);
// Empty metadata again: still use the cache
cache.get(table_id, Some(HashMap::new()), None).await;
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 4);
// See a new UUID and not the old one: refresh the cache
let new_uuid = Uuid::new_v4();
cache
.get(table_id, Some(HashMap::from([(new_uuid, 1)])), None)
.await;
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 5);
}
#[tokio::test]
async fn test_ttl() {
let (catalog, table, partition) = make_catalog().await;
let builder = TestParquetFileBuilder::default()
.with_line_protocol(TABLE1_LINE_PROTOCOL)
.with_creation_time(catalog.time_provider.now());
let tfile1 = partition.create_parquet_file(builder).await;
let builder = TestParquetFileBuilder::default()
.with_line_protocol(TABLE1_LINE_PROTOCOL2)
.with_creation_time(catalog.time_provider.now());
let tfile2 = partition.create_parquet_file(builder).await;
let cache = make_cache(&catalog);
let mut cached_files = cache.get(table.table.id, None, None).await.vec();
cached_files.sort_by_key(|f| f.id);
assert_eq!(cached_files.len(), 2);
assert_eq!(cached_files[0].as_ref(), &tfile1.parquet_file);
assert_eq!(cached_files[1].as_ref(), &tfile2.parquet_file);
// update state
// replace first file and add a new one
catalog.mock_time_provider().inc(Duration::from_secs(60));
let builder = TestParquetFileBuilder::default()
.with_line_protocol(TABLE1_LINE_PROTOCOL)
.with_creation_time(catalog.time_provider.now());
let tfile3 = partition.create_parquet_file(builder).await;
let builder = TestParquetFileBuilder::default()
.with_line_protocol(TABLE1_LINE_PROTOCOL3)
.with_creation_time(catalog.time_provider.now());
let tfile4 = partition.create_parquet_file(builder).await;
tfile1.flag_for_delete().await;
// validate a second request doesn't result in a catalog request
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 1);
let cached_files = cache.get(table.table.id, None, None).await.vec();
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 1);
// still the old data
assert_eq!(cached_files.len(), 2);
assert_eq!(cached_files[0].as_ref(), &tfile1.parquet_file);
assert_eq!(cached_files[1].as_ref(), &tfile2.parquet_file);
// trigger TTL
catalog.mock_time_provider().inc(TTL);
let mut cached_files = cache.get(table.table.id, None, None).await.vec();
cached_files.sort_by_key(|f| f.id);
assert_catalog_access_metric_count(&catalog.metric_registry, METRIC_NAME, 2);
assert_eq!(cached_files.len(), 3);
assert_eq!(cached_files[0].as_ref(), &tfile2.parquet_file);
assert_eq!(cached_files[1].as_ref(), &tfile3.parquet_file);
assert_eq!(cached_files[2].as_ref(), &tfile4.parquet_file);
}
/// Extracts parquet ids from various objects
trait ParquetIds {
fn ids(&self) -> HashSet<ParquetFileId>;
}
impl ParquetIds for &CachedParquetFiles {
fn ids(&self) -> HashSet<ParquetFileId> {
self.files.iter().map(|f| f.id).collect()
}
}
impl ParquetIds for Arc<CachedParquetFiles> {
fn ids(&self) -> HashSet<ParquetFileId> {
self.as_ref().ids()
}
}
async fn make_catalog() -> (Arc<TestCatalog>, Arc<TestTable>, Arc<TestPartition>) {
let catalog = TestCatalog::new();
let ns = catalog.create_namespace_1hr_retention("ns").await;
let (table, partition) = make_table_and_partition("table1", &ns).await;
table.create_column("foo", ColumnType::F64).await;
table.create_column("time", ColumnType::Time).await;
(catalog, table, partition)
}
async fn make_table_and_partition(
table_name: &str,
ns: &Arc<TestNamespace>,
) -> (Arc<TestTable>, Arc<TestPartition>) {
let table = ns.create_table(table_name).await;
table.create_column("foo", ColumnType::F64).await;
table.create_column("time", ColumnType::Time).await;
let partition = table.create_partition("k").await;
(table, partition)
}
fn make_cache(catalog: &TestCatalog) -> ParquetFileCache {
ParquetFileCache::new(
catalog.catalog(),
BackoffConfig::default(),
catalog.time_provider(),
&catalog.metric_registry(),
test_ram_pool(),
true,
)
}
}
|
use actix::prelude::*;
#[derive(Debug, Message)]
#[rtype(result = "Data")]
struct CreateData {
value: u32,
}
#[derive(Debug, MessageResponse)]
struct Data {
id: String,
value: u32,
}
struct SampleActor;
impl Actor for SampleActor {
type Context = SyncContext<Self>;
fn started(&mut self, _ctx: &mut Self::Context) {
println!("*** started: {:?}", std::thread::current().id());
}
}
impl Handler<CreateData> for SampleActor {
type Result = Data;
fn handle(&mut self, msg: CreateData,
_ctx: &mut Self::Context) -> Self::Result {
let id = format!("test-{:?}", std::thread::current().id());
println!("*** {} handle message: {:?}", id, msg);
Data { id: id, value: msg.value }
}
}
#[actix_rt::main]
async fn main() {
let addr = SyncArbiter::start(5, || SampleActor);
let a1 = addr.send(CreateData { value: 11}).await;
println!("a1: {:?}", a1);
let a2 = addr.send(CreateData { value: 12}).await;
println!("a2: {:?}", a2);
let (b1, b2, b3) = futures::join!(
addr.send(CreateData { value: 21}),
addr.send(CreateData { value: 22}),
addr.send(CreateData { value: 23}),
);
println!("b1: {:?}", b1);
println!("b2: {:?}", b2);
println!("b3: {:?}", b3);
let rs: Vec<_> = (0..3).map(|i|
addr.send(CreateData { value: i + 100 })
).collect();
for r in rs {
match r.await {
Ok(r) => println!("ok: {:?}", r),
Err(e) => println!("err: {}", e),
}
}
}
|
use crate::{event::Event, stream::VecStreamExt, transforms::Transform};
use futures::{
compat::Stream01CompatExt,
future,
stream::{self, BoxStream},
FutureExt, StreamExt, TryStreamExt,
};
use futures01::Stream;
use std::time::Duration;
/// A structure representing user-defined timer.
#[derive(Clone, Copy, Debug)]
pub struct Timer {
pub id: u32,
pub interval_seconds: u64,
}
/// A trait representing a runtime running user-defined code.
pub trait RuntimeTransform {
/// Call user-defined "init" hook.
fn hook_init<F>(&mut self, _emit_fn: F)
where
F: FnMut(Event),
{
}
/// Call user-defined "process" hook.
fn hook_process<F>(&mut self, event: Event, emit_fn: F)
where
F: FnMut(Event);
/// Call user-defined "shutdown" hook.
fn hook_shutdown<F>(&mut self, _emit_fn: F)
where
F: FnMut(Event),
{
}
/// Call user-defined timer handler.
fn timer_handler<F>(&mut self, _timer: Timer, _emit_fn: F)
where
F: FnMut(Event),
{
}
/// Return (static) list of user-defined timers.
fn timers(&self) -> Vec<Timer> {
Vec::new()
}
}
#[derive(Debug)]
enum Message {
Init,
Process(Event),
Shutdown,
Timer(Timer),
}
impl<T> Transform for T
where
T: RuntimeTransform + Send,
{
// used only in config tests (cannot be put behind `#[cfg(test)`])
fn transform(&mut self, event: Event) -> Option<Event> {
let mut out = Vec::new();
self.transform_into(&mut out, event);
assert!(out.len() <= 1);
out.into_iter().next()
}
// used only in config tests (cannot be put behind `#[cfg(test)]`)
fn transform_into(&mut self, output: &mut Vec<Event>, event: Event) {
self.hook_process(event, |event| output.push(event));
}
fn transform_stream(
mut self: Box<Self>,
input_rx: Box<dyn Stream<Item = Event, Error = ()> + Send>,
) -> Box<dyn Stream<Item = Event, Error = ()> + Send>
where
Self: 'static,
{
let timers = self.timers();
let mut is_shutdown: bool = false; // TODO: consider using an enum describing the state instead of a
// a single boolean variable.
// It is used to prevent timers to emit messages after the source
// stream stopped.
Box::new(
input_rx
.compat()
.map_ok(Message::Process)
.into_future()
.map(move |(first, rest)| {
// Option<Result<T, E>> -> Result<Option<T>>, E> -> Option<T>
let first = match first.transpose() {
Ok(first) => first,
Err(_) => return stream::once(future::ready(Err(()))).boxed(),
};
// The first message is always `Message::Init`.
let init_msg = stream::once(future::ready(Ok(Message::Init)));
// After it comes the first event, if any.
let first_event = first.map_or_else(
|| stream::empty().boxed(),
|msg| stream::once(future::ready(Ok(msg))).boxed(),
);
// Then all other events followed by `Message::Shutdown` message
let rest_events_and_shutdown_msg =
rest.chain(stream::once(future::ready(Ok(Message::Shutdown))));
// A stream of `Message::Timer(..)` events generated by timers.
let timer_msgs = make_timer_msgs_stream(timers);
init_msg
.chain(first_event)
.chain(
// We need to finish when `rest_events_and_shutdown_msg` finishes so
// not to hang on timers, but not finish when `timer_msgs` finishes
// as there may not be any timer.
rest_events_and_shutdown_msg
.select_weak(timer_msgs.chain(stream::pending())),
)
.boxed()
})
.into_stream()
.flatten()
.map(move |msg| {
let msg = match msg {
Ok(msg) => msg,
Err(_) => return stream::once(future::ready(Err(()))).boxed(),
};
let mut acc = Vec::new(); // TODO: create a stream adaptor to avoid buffering all events
if !is_shutdown {
match msg {
Message::Init => self.hook_init(|event| acc.push(Ok(event))),
Message::Process(event) => {
self.hook_process(event, |event| acc.push(Ok(event)))
}
Message::Shutdown => {
self.hook_shutdown(|event| acc.push(Ok(event)));
is_shutdown = true;
}
Message::Timer(timer) => {
self.timer_handler(timer, |event| acc.push(Ok(event)))
}
}
}
stream::iter(acc).boxed()
})
.flatten()
.boxed()
.compat(),
)
}
}
fn make_timer_msgs_stream(timers: Vec<Timer>) -> BoxStream<'static, Result<Message, ()>> {
let streams = timers.into_iter().map(|timer| {
let period = Duration::from_secs(timer.interval_seconds);
tokio::time::interval(period).map(move |_| Ok(Message::Timer(timer)))
});
stream::select_all(streams).boxed()
}
|
pub mod timeutil;
pub use timeutil::*;
pub mod strings;
pub use strings::*;
|
use crate::{
sabi_types::MaybeCmp,
std_types::utypeid::{no_utypeid, some_utypeid, UTypeId},
};
/// Passed to trait object constructors to make the
/// trait object downcast capable,
/// as opposed to [`TD_Opaque`](./struct.TD_Opaque.html).
///
/// [The `from_value`/`from_ptr`/`from_const` methods here
/// ](../../docs/sabi_trait_inherent/index.html#methods) take this type.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::Action_TO,
/// std_types::RBox,
/// type_level::downcasting::TD_CanDowncast,
/// };
///
/// // The type annotation is purely for the reader.
/// let mut object: Action_TO<'static, RBox<()>> =
/// Action_TO::from_value(100_usize, TD_CanDowncast);
///
/// assert_eq!(object.obj.downcast_as::<u8>().ok(), None);
/// assert_eq!(object.obj.downcast_as::<char>().ok(), None);
/// assert_eq!(object.obj.downcast_as::<usize>().ok(), Some(&100_usize));
///
/// ```
#[allow(non_camel_case_types)]
#[derive(Copy, Clone)]
pub struct TD_CanDowncast;
/// Passed to trait object constructors to make it impossible to downcast the
/// trait object,
/// as opposed to [`TD_CanDowncast`](./struct.TD_CanDowncast.html).
///
/// [The `from_value`/`from_ptr`/`from_const` methods here
/// ](../../docs/sabi_trait_inherent/index.html#methods) take this type.
///
/// # Example
///
/// ```rust
/// use abi_stable::{
/// sabi_trait::doc_examples::Action_TO,
/// std_types::RBox,
/// type_level::downcasting::TD_Opaque,
/// };
///
/// // The type annotation is purely for the reader.
/// let mut object: Action_TO<'static, RBox<()>> =
/// Action_TO::from_value(100_usize, TD_Opaque);
///
/// assert_eq!(object.obj.downcast_as::<u8>().ok(), None);
///
/// assert_eq!(object.obj.downcast_as::<char>().ok(), None);
///
/// // Because `Action_TO::from-value` was passed `TD_Opaque`,
/// // the trait object can't be downcasted
/// assert_eq!(object.obj.downcast_as::<usize>().ok(), None);
///
/// ```
#[allow(non_camel_case_types)]
#[derive(Copy, Clone)]
pub struct TD_Opaque;
/// Gets a function optionally returning the `UTypeId` of `T`.
///
/// Whether the function returns `MaybeCmp::Just(typeid)` is determined by implementors:
///
/// - `TD_CanDowncast`: the function always returns `MaybeCmp::Just(typeid)`.
///
/// - `TD_Opaque`: the function always returns `MaybeCmp::Nothing`.
pub trait GetUTID<T> {
/// the function.
const UID: extern "C" fn() -> MaybeCmp<UTypeId>;
}
impl<T> GetUTID<T> for TD_CanDowncast
where
T: 'static,
{
const UID: extern "C" fn() -> MaybeCmp<UTypeId> = some_utypeid::<T>;
}
impl<T> GetUTID<T> for TD_Opaque {
const UID: extern "C" fn() -> MaybeCmp<UTypeId> = no_utypeid;
}
|
pub mod common;
pub mod gql_schema;
pub mod schema;
pub mod state;
|
pub struct Solution;
impl Solution {
pub fn remove_duplicates(nums: &mut Vec<i32>) -> i32 {
let n = nums.len();
if n == 0 {
return 0;
}
let mut cnt = 1;
for i in 1..n {
if nums[i] != nums[cnt - 1] {
nums[cnt] = nums[i];
cnt += 1;
}
}
cnt as i32
}
}
#[test]
fn test0026() {
let mut nums = vec![1, 1, 2];
assert_eq!(Solution::remove_duplicates(&mut nums), 2);
assert_eq!(&nums[..2], &[1, 2]);
let mut nums = vec![0, 0, 1, 1, 1, 2, 2, 3, 3, 4];
assert_eq!(Solution::remove_duplicates(&mut nums), 5);
assert_eq!(&nums[..5], &[0, 1, 2, 3, 4]);
}
|
#![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 DeviceServicingDetails(pub ::windows::core::IInspectable);
impl DeviceServicingDetails {
pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Arguments(&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__)
}
}
#[cfg(feature = "Foundation")]
pub fn ExpectedDuration(&self) -> ::windows::core::Result<super::super::Foundation::TimeSpan> {
let this = self;
unsafe {
let mut result__: super::super::Foundation::TimeSpan = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::Foundation::TimeSpan>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for DeviceServicingDetails {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Background.DeviceServicingDetails;{4aabee29-2344-4ac4-8527-4a8ef6905645})");
}
unsafe impl ::windows::core::Interface for DeviceServicingDetails {
type Vtable = IDeviceServicingDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4aabee29_2344_4ac4_8527_4a8ef6905645);
}
impl ::windows::core::RuntimeName for DeviceServicingDetails {
const NAME: &'static str = "Windows.Devices.Background.DeviceServicingDetails";
}
impl ::core::convert::From<DeviceServicingDetails> for ::windows::core::IUnknown {
fn from(value: DeviceServicingDetails) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&DeviceServicingDetails> for ::windows::core::IUnknown {
fn from(value: &DeviceServicingDetails) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for DeviceServicingDetails {
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 DeviceServicingDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<DeviceServicingDetails> for ::windows::core::IInspectable {
fn from(value: DeviceServicingDetails) -> Self {
value.0
}
}
impl ::core::convert::From<&DeviceServicingDetails> for ::windows::core::IInspectable {
fn from(value: &DeviceServicingDetails) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for DeviceServicingDetails {
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 DeviceServicingDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for DeviceServicingDetails {}
unsafe impl ::core::marker::Sync for DeviceServicingDetails {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct DeviceUseDetails(pub ::windows::core::IInspectable);
impl DeviceUseDetails {
pub fn DeviceId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Arguments(&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__)
}
}
}
unsafe impl ::windows::core::RuntimeType for DeviceUseDetails {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Devices.Background.DeviceUseDetails;{7d565141-557e-4154-b994-e4f7a11fb323})");
}
unsafe impl ::windows::core::Interface for DeviceUseDetails {
type Vtable = IDeviceUseDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d565141_557e_4154_b994_e4f7a11fb323);
}
impl ::windows::core::RuntimeName for DeviceUseDetails {
const NAME: &'static str = "Windows.Devices.Background.DeviceUseDetails";
}
impl ::core::convert::From<DeviceUseDetails> for ::windows::core::IUnknown {
fn from(value: DeviceUseDetails) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&DeviceUseDetails> for ::windows::core::IUnknown {
fn from(value: &DeviceUseDetails) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for DeviceUseDetails {
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 DeviceUseDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<DeviceUseDetails> for ::windows::core::IInspectable {
fn from(value: DeviceUseDetails) -> Self {
value.0
}
}
impl ::core::convert::From<&DeviceUseDetails> for ::windows::core::IInspectable {
fn from(value: &DeviceUseDetails) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for DeviceUseDetails {
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 DeviceUseDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for DeviceUseDetails {}
unsafe impl ::core::marker::Sync for DeviceUseDetails {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IDeviceServicingDetails(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IDeviceServicingDetails {
type Vtable = IDeviceServicingDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x4aabee29_2344_4ac4_8527_4a8ef6905645);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDeviceServicingDetails_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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IDeviceUseDetails(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IDeviceUseDetails {
type Vtable = IDeviceUseDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x7d565141_557e_4154_b994_e4f7a11fb323);
}
#[repr(C)]
#[doc(hidden)]
pub struct IDeviceUseDetails_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 mod server;
pub mod client;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{ Duration, Instant };
use std::io::{ Error, ErrorKind };
use std::collections::HashMap;
use std::pin::Pin;
use std::rc::Rc;
use std::cell::RefCell;
use std::sync::Mutex;
use std::fmt::Debug;
use std::any::Any;
use async_std::task::*;
use async_std::net::UdpSocket;
use async_std::sync::{ channel, Sender, Receiver, RecvError };
use async_std::future;
use async_std::sync::Mutex as AsyncMutex;
use neqo_transport;
use neqo_common::Datagram;
use futures::io::{ AsyncWrite, AsyncRead };
pub type Version = neqo_transport::QuicVersion;
#[derive(Debug)]
pub enum QuicError {
NeqoError(neqo_transport::Error),
IoError(std::io::Error),
FatalError(Box<dyn Any + Send>)
}
impl From<std::io::Error> for QuicError {
fn from(e: std::io::Error) -> Self {
QuicError::IoError(e)
}
}
impl From<neqo_transport::Error> for QuicError {
fn from(e: neqo_transport::Error) -> Self {
QuicError::NeqoError(e)
}
}
impl From<Box<dyn Any + Send>> for QuicError {
fn from(e: Box<dyn Any + Send>) -> Self {
QuicError::FatalError(e)
}
}
unsafe impl Send for Connection { }
unsafe impl Sync for Connection { }
unsafe impl Send for InternalConnection { }
unsafe impl Sync for InternalConnection { }
pub struct Connection {
socket: Arc<UdpSocket>,
src_addr: SocketAddr,
dst_addr: SocketAddr,
data_tx: Sender<Option<Vec<u8>>>,
data_rx: Receiver<Option<Vec<u8>>>,
strm_tx: Sender<Option<u64>>,
strm_rx: Receiver<Option<u64>>,
internal: Arc<Mutex<InternalConnection>>,
}
impl Clone for Connection {
fn clone(&self) -> Self {
Connection {
socket: self.socket.clone(),
src_addr: self.src_addr.clone(),
dst_addr: self.dst_addr.clone(),
strm_tx: self.strm_tx.clone(),
strm_rx: self.strm_rx.clone(),
data_tx: self.data_tx.clone(),
data_rx: self.data_rx.clone(),
internal: self.internal.clone()
}
}
}
impl Connection {
pub fn get_src_addr(&self) -> SocketAddr {
self.src_addr
}
pub fn get_dst_addr(&self) -> SocketAddr {
self.dst_addr
}
pub fn try_send_packet(&self, packet: Option<Vec<u8>>) -> bool {
self.data_tx.try_send(packet).is_ok()
}
pub async fn send_packet(&self, packet: Option<Vec<u8>>) {
self.data_tx.send(packet).await;
}
pub async fn recv_packet(&self, timeout: Option<Duration>) -> Result<Option<Vec<u8>>, RecvError> {
if let Some(timeout) = timeout {
if let Ok(result) = future::timeout(timeout, self.data_rx.recv()).await {
return result;
}
return Ok(None);
}
else {
return self.data_rx.recv().await;
}
}
pub async fn create_stream_half(&self) -> Option<QuicSendStream> {
if let Ok(stream_id) = self.internal.lock().unwrap().quic.stream_create(neqo_transport::StreamType::UniDi) {
return Some(self.generate_stream(stream_id).0);
}
return None;
}
pub async fn create_stream_full(&self) -> Option<(QuicSendStream, QuicRecvStream)> {
if let Ok(stream_id) = self.internal.lock().unwrap().quic.stream_create(neqo_transport::StreamType::BiDi) {
return Some(self.generate_stream(stream_id));
}
return None;
}
pub async fn listen_stream(&self) -> Option<(QuicSendStream, QuicRecvStream)> {
if let Ok(Some(stream_id)) = self.strm_rx.recv().await {
return Some(self.generate_stream(stream_id));
}
return None;
}
pub fn close(&self, error: u64, msg: &str) {
let mut internal = self.internal.lock().unwrap();
internal.quic.close(Instant::now(), error, msg);
}
fn auth_ok(&self) {
let mut internal = self.internal.lock().unwrap();
assert!(internal.quic.role() != neqo_common::Role::Server);
internal.quic.authenticated(neqo_crypto::AuthenticationStatus::Ok, Instant::now());
}
fn generate_stream(&self, stream_id: u64) -> (QuicSendStream, QuicRecvStream) {
let send_strm = QuicSendStream {
send_closed: false,
stream_id,
conn: self.clone(),
error_code: Default::default()
};
let recv_strm = QuicRecvStream {
stream_id,
conn: self.clone(),
error_code: Default::default()
};
return (send_strm, recv_strm);
}
async fn process(&self, packet: Option<Vec<u8>>) -> Option<Duration> {
let mut outputs = Vec::new();
let timeout;
{
let mut internal = self.internal.lock().unwrap();
if let Some(packet) = packet {
internal.quic.process_input(Datagram::new(self.dst_addr, self.src_addr, packet), Instant::now());
}
loop {
match internal.quic.process_output(Instant::now()) {
neqo_transport::Output::None => {
timeout = None;
break;
}
neqo_transport::Output::Callback(duration) => {
timeout = Some(duration);
break;
}
neqo_transport::Output::Datagram(datagram) => {
outputs.push(datagram);
}
}
}
}
for packet in outputs {
self.socket.send_to(&packet, packet.destination()).await
.expect("failed to send packet to socket!");
}
return timeout;
}
async fn get_events(&self) -> impl Iterator<Item = neqo_transport::ConnectionEvent> {
let mut internal = self.internal.lock().unwrap();
internal.quic.events()
}
async fn wake_send_stream(&self, stream_id: u64) {
let mut internal = self.internal.lock().unwrap();
if let Some(waker) = internal.send_op_wakers.remove(&stream_id) {
waker.wake();
}
}
async fn wake_recv_stream(&self, stream_id: u64) {
let mut internal = self.internal.lock().unwrap();
if let Some(waker) = internal.recv_op_wakers.remove(&stream_id) {
waker.wake();
}
}
async fn internal_cleanup(&self) {
let mut internal = self.internal.lock().unwrap();
for (_, waker) in internal.send_op_wakers.drain() {
waker.wake();
}
for (_, waker) in internal.recv_op_wakers.drain() {
waker.wake();
}
}
fn stream_send_op(&self, stream_id: u64, waker: Waker, buffer: &[u8]) -> Result<usize, std::io::Error> {
let mut internal = self.internal.lock().unwrap();
match internal.quic.stream_send(stream_id, buffer) {
Ok (len) => {
if len == 0 {
internal.send_op_wakers.insert(stream_id, waker);
return Err(Error::new(ErrorKind::WouldBlock, "operation would block"));
}
self.try_send_packet(None);
return Ok(len);
}
Err(e) => {
if let neqo_transport::Error::InvalidStreamId | neqo_transport::Error::FinalSizeError = e {
return Err(Error::new(ErrorKind::BrokenPipe, "bad stream id!"));
}
}
}
unreachable!();
}
fn stream_recv_op(&self, stream_id: u64, waker: Waker, buffer: &mut [u8]) -> Result<usize, std::io::Error> {
let mut internal = self.internal.lock().unwrap();
match internal.quic.stream_recv(stream_id, buffer) {
Ok ((len, _)) => {
if len == 0 {
internal.recv_op_wakers.insert(stream_id, waker);
return Err(Error::new(ErrorKind::WouldBlock, "operation would block"));
}
self.try_send_packet(None);
return Ok(len);
}
Err(e) => {
if let neqo_transport::Error::InvalidStreamId | neqo_transport::Error::NoMoreData = e {
return Err(std::io::Error::new(std::io::ErrorKind::BrokenPipe, "bad stream id!"));
}
}
}
unreachable!();
}
fn stream_close(&self, stream_id: u64, waker: Waker) {
let mut internal = self.internal.lock().unwrap();
if let Err(neqo_transport::Error::InvalidStreamId) = internal.quic.stream_close_send(stream_id) {
waker.wake_by_ref();
}
}
fn stream_reset(&self, stream_id: u64, error: u64) {
let mut internal = self.internal.lock().unwrap();
internal.quic.stream_reset_send(stream_id, error).unwrap();
}
}
struct InternalConnection {
quic: neqo_transport::Connection,
send_op_wakers: HashMap<u64, Waker>,
recv_op_wakers: HashMap<u64, Waker>,
}
pub struct QuicSendStream {
send_closed: bool,
stream_id: u64,
conn: Connection,
error_code: Arc<Mutex<Option<u64>>>
}
pub struct QuicRecvStream {
stream_id: u64,
conn: Connection,
error_code: Arc<Mutex<Option<u64>>>
}
impl QuicSendStream {
pub fn get_stream_id(&self) -> u64 {
self.stream_id
}
pub async fn get_error_code(&self) -> Option<u64> {
*self.error_code.lock().unwrap()
}
}
impl AsyncWrite for QuicSendStream {
fn poll_write(self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &[u8]) -> Poll<Result<usize, Error>> {
let result = match self.conn.stream_send_op(self.stream_id, ctx.waker().clone(), buf) {
Err(e) if e.kind() == ErrorKind::WouldBlock => {
return Poll::Pending;
}
v => v,
};
return Poll::Ready(result);
}
fn poll_flush(self: Pin<&mut Self>, _: &mut Context<'_>) -> Poll<Result<(), Error>> {
unimplemented!("quic does not implements flush!");
}
fn poll_close(self: Pin<&mut Self>, ctx: &mut Context<'_>) -> Poll<Result<(), Error>> {
if self.send_closed {
return Poll::Ready(Ok(()));
}
self.conn.stream_close(self.stream_id, ctx.waker().clone());
self.get_mut().send_closed = true;
return Poll::Pending;
}
}
impl QuicSendStream {
pub fn reset(&mut self, error: u64) {
self.send_closed = true;
self.conn.stream_reset(self.stream_id, error);
}
}
impl QuicRecvStream {
pub fn get_stream_id(&self) -> u64 {
self.stream_id
}
pub async fn get_error_code(&self) -> Option<u64> {
*self.error_code.lock().unwrap()
}
}
impl AsyncRead for QuicRecvStream {
fn poll_read(self: Pin<&mut Self>, ctx: &mut Context<'_>, buf: &mut [u8]) -> Poll<Result<usize, Error>> {
let result = match self.conn.stream_recv_op(self.stream_id, ctx.waker().clone(), buf) {
Err(e) if e.kind() == ErrorKind::WouldBlock => {
return Poll::Pending;
}
v => v,
};
return Poll::Ready(result);
}
}
impl QuicRecvStream {
pub fn reset(&mut self, error: u64) {
self.conn.stream_reset(self.stream_id, error);
}
}
async fn dispatch_event(connection: &Connection, event: neqo_transport::ConnectionEvent) -> Result<(), Option<u64>> {
match event {
neqo_transport::ConnectionEvent::AuthenticationNeeded => {
connection.auth_ok();
log::info!("neqo-future | authentication requested");
}
// Peer has created new stream.
neqo_transport::ConnectionEvent::NewStream { stream_id } => {
let stream_id = stream_id.as_u64();
connection.strm_tx.send(Some(stream_id)).await;
log::info!("neqo-future | new stream (stream_id = {})", stream_id);
}
// If we have registered waker on table.
neqo_transport::ConnectionEvent::SendStreamWritable { stream_id } => {
let stream_id = stream_id.as_u64();
connection.wake_send_stream(stream_id).await;
log::info!("neqo-future | stream writable (stream_id = {})", stream_id);
}
neqo_transport::ConnectionEvent::RecvStreamReadable { stream_id } => {
connection.wake_recv_stream(stream_id).await;
log::info!("neqo-future | stream readable (stream_id = {})", stream_id);
}
// We've closed stream and sent all data.
neqo_transport::ConnectionEvent::SendStreamComplete { stream_id } => {
connection.wake_send_stream(stream_id).await;
log::info!("neqo-future | stream complate (stream_id = {})", stream_id);
}
// Peer has requested closed.
neqo_transport::ConnectionEvent::RecvStreamReset { stream_id, .. } => {
// We have to notify this is closed.
connection.wake_recv_stream(stream_id).await;
connection.wake_send_stream(stream_id).await;
log::info!("neqo-future | stream resetted (stream_id = {})", stream_id);
}
neqo_transport::ConnectionEvent::SendStreamStopSending { stream_id, .. } => {
connection.wake_send_stream(stream_id).await;
log::info!("neqo-future | stream stop send (stream_id = {})", stream_id);
}
neqo_transport::ConnectionEvent::StateChange(state) => {
log::info!("neqo-future | state changed => {:?}", state);
if let neqo_transport::State::Closing{..} = &state {
// Seems peer has been closed.
// so we are in closing state do not create more streams.
connection.strm_tx.send(None).await;
}
if let neqo_transport::State::Closed(err) = &state {
return Err(err.app_code());
}
connection.process(None).await;
}
_ => { }
}
return Ok(());
}
async fn dispatch_conn(connection: Connection) -> Option<u64> {
let mut timeout = connection.process(None).await;
let mut result = None;
'main: while let Ok(buf) = connection.recv_packet(timeout).await {
timeout = connection.process(buf).await;
for event in connection.get_events().await {
if let Err(err_code) = dispatch_event(&connection, event).await {
result = err_code;
break 'main;
}
}
};
// wake all stream wakers and cleans up.
connection.internal_cleanup().await;
return result;
} |
pub mod raft;
mod tonic;
|
/// Note: most of these tests are duplicated doc tests, but they're here so that
/// we can run them through miri and get a good idea of the soundness of our
/// implementations.
#[test]
fn test_channels_then_resize() {
let mut buffer = crate::Sequential::<f32>::new();
buffer.resize_channels(4);
buffer.resize(128);
let expected = vec![0.0; 128];
assert_eq!(Some(&expected[..]), buffer.get(0));
assert_eq!(Some(&expected[..]), buffer.get(1));
assert_eq!(Some(&expected[..]), buffer.get(2));
assert_eq!(Some(&expected[..]), buffer.get(3));
assert_eq!(None, buffer.get(4));
}
#[test]
fn test_resize_then_channels() {
let mut buffer = crate::Sequential::<f32>::new();
buffer.resize(128);
buffer.resize_channels(4);
let expected = vec![0.0; 128];
assert_eq!(buffer.get(0), Some(&expected[..]));
assert_eq!(buffer.get(1), Some(&expected[..]));
assert_eq!(buffer.get(2), Some(&expected[..]));
assert_eq!(buffer.get(3), Some(&expected[..]));
assert_eq!(buffer.get(4), None);
}
#[test]
fn test_empty_channels() {
let mut buffer = crate::Sequential::<f32>::new();
buffer.resize_channels(4);
assert_eq!(buffer.get(0), Some(&[][..]));
assert_eq!(buffer.get(1), Some(&[][..]));
assert_eq!(buffer.get(2), Some(&[][..]));
assert_eq!(buffer.get(3), Some(&[][..]));
assert_eq!(buffer.get(4), None);
}
#[test]
fn test_empty() {
let buffer = crate::Sequential::<f32>::new();
assert_eq!(buffer.frames(), 0);
assert_eq!(buffer.get(0), None);
}
#[test]
fn test_multiple_resizes() {
let mut buffer = crate::Sequential::<f32>::new();
buffer.resize_channels(4);
buffer.resize(128);
let expected = vec![0.0; 128];
assert_eq!(buffer.get(0), Some(&expected[..]));
assert_eq!(buffer.get(1), Some(&expected[..]));
assert_eq!(buffer.get(2), Some(&expected[..]));
assert_eq!(buffer.get(3), Some(&expected[..]));
assert_eq!(buffer.get(4), None);
}
#[test]
fn test_unaligned_resize() {
let mut buffer = crate::Sequential::<f32>::with_topology(2, 4);
buffer[0].copy_from_slice(&[1.0, 2.0, 3.0, 4.0]);
buffer[1].copy_from_slice(&[2.0, 3.0, 4.0, 5.0]);
buffer.resize(3);
assert_eq!(&buffer[0], &[1.0, 2.0, 3.0]);
assert_eq!(&buffer[1], &[2.0, 3.0, 4.0]);
buffer.resize(4);
assert_eq!(&buffer[0], &[1.0, 2.0, 3.0, 2.0]); // <- 2.0 is stale data.
assert_eq!(&buffer[1], &[2.0, 3.0, 4.0, 5.0]); // <- 5.0 is stale data.
}
#[test]
fn test_multiple_channel_resizes() {
let mut buffer = crate::Sequential::<f32>::new();
buffer.resize_channels(4);
buffer.resize(128);
let expected = (0..128).map(|v| v as f32).collect::<Vec<_>>();
for chan in buffer.iter_mut() {
for (s, v) in chan.iter_mut().zip(&expected) {
*s = *v;
}
}
assert_eq!(buffer.get(0), Some(&expected[..]));
assert_eq!(buffer.get(1), Some(&expected[..]));
assert_eq!(buffer.get(2), Some(&expected[..]));
assert_eq!(buffer.get(3), Some(&expected[..]));
assert_eq!(buffer.get(4), None);
buffer.resize_channels(2);
assert_eq!(buffer.get(0), Some(&expected[..]));
assert_eq!(buffer.get(1), Some(&expected[..]));
assert_eq!(buffer.get(2), None);
// shrink
buffer.resize(64);
assert_eq!(buffer.get(0), Some(&expected[..64]));
assert_eq!(buffer.get(1), Some(&expected[..64]));
assert_eq!(buffer.get(2), None);
// increase - this causes some weirdness.
buffer.resize(128);
let first_overlapping = expected[..64]
.iter()
.chain(expected[..64].iter())
.copied()
.collect::<Vec<_>>();
assert_eq!(buffer.get(0), Some(&first_overlapping[..]));
// Note: second channel matches perfectly up with an old channel that was
// masked out.
assert_eq!(buffer.get(1), Some(&expected[..]));
assert_eq!(buffer.get(2), None);
}
#[test]
fn test_drop_empty() {
let mut buffer = crate::Sequential::<f32>::new();
assert_eq!(buffer.frames(), 0);
buffer.resize(128);
assert_eq!(buffer.frames(), 128);
}
#[test]
fn test_stale_allocation() {
let mut buffer = crate::Sequential::<f32>::with_topology(4, 256);
assert_eq!(buffer[1][128], 0.0);
buffer[1][128] = 42.0;
buffer.resize(64);
assert!(buffer[1].get(128).is_none());
buffer.resize(256);
assert_eq!(buffer[1][128], 0.0);
}
#[test]
fn test_from_array() {
let _ = crate::dynamic![[0.0; 128]; 2];
}
|
use std::{convert::TryInto, num::TryFromIntError};
use crate::{Tile, TileRegionCoordinate, TileRegionPosition, TileRegionRect, TileWorldPosition};
use game_lib::{
bevy::{math::Vec2, prelude::*},
derive_more::{Display, Error},
};
use game_morton::Morton;
// TODO: implement Serialize/Deserialize, doesn't support const generics yet so
// array is a pain
// TODO: implement Reflect once support for arrays is added
#[derive(Clone, Debug)]
pub struct Region {
tiles: [Option<Tile>; Self::TILES],
}
impl Default for Region {
fn default() -> Self {
Region {
tiles: [None; Self::TILES],
}
}
}
impl Region {
pub const WIDTH: TileRegionCoordinate = 16;
pub const HEIGHT: TileRegionCoordinate = 16;
pub const TILES: usize = Self::WIDTH as usize * Self::HEIGHT as usize;
pub const BOUNDS: TileRegionRect = TileRegionRect::new(
TileRegionPosition::ZERO,
TileRegionPosition::new(Self::WIDTH, Self::HEIGHT),
);
pub fn get(&self, position: TileRegionPosition) -> Result<&Option<Tile>, RegionGetError> {
self.tiles
.get(Self::encode_pos(position)?)
.ok_or(RegionGetError::OutOfBounds(position))
}
pub fn get_mut(
&mut self,
position: TileRegionPosition,
) -> Result<&mut Option<Tile>, RegionGetError> {
self.tiles
.get_mut(Self::encode_pos(position)?)
.ok_or(RegionGetError::OutOfBounds(position))
}
fn encode_pos(position: TileRegionPosition) -> Result<usize, RegionGetError> {
if position.x >= Self::WIDTH || position.y >= Self::HEIGHT {
Err(RegionGetError::OutOfBounds(position))
} else {
Ok(Morton::encode_2d(position.x, position.y).into())
}
}
fn decode_pos(index: usize) -> Result<TileRegionPosition, TryFromIntError> {
let index = index.try_into()?;
let (x, y) = Morton::decode_2d(index);
Ok(TileRegionPosition::new(x, y))
}
pub fn iter(&self) -> impl Iterator<Item = (TileRegionPosition, &Option<Tile>)> {
self.tiles
.iter()
.enumerate()
.map(|(index, tile)| (Region::decode_pos(index).unwrap(), tile))
}
pub fn iter_mut(&mut self) -> impl Iterator<Item = (TileRegionPosition, &mut Option<Tile>)> {
self.tiles
.iter_mut()
.enumerate()
.map(|(index, tile)| (Region::decode_pos(index).unwrap(), tile))
}
pub fn iter_rect(
&self,
rect: TileRegionRect,
) -> impl Iterator<Item = (TileRegionPosition, Result<&Option<Tile>, RegionGetError>)> {
rect.iter_positions()
.map(move |position| (position, self.get(position)))
}
pub fn iter_intersecting(
&self,
bottom_left: Vec2,
top_right: Vec2,
) -> impl Iterator<Item = (TileRegionPosition, Result<&Option<Tile>, RegionGetError>)> {
let bottom_left: TileRegionPosition = bottom_left.max(Vec2::ZERO).floor().into();
let top_right: TileRegionPosition = top_right.max(Vec2::ZERO).ceil().into();
self.iter_rect(TileRegionRect::new(bottom_left, top_right - bottom_left))
}
}
#[derive(Clone, Debug, Display, Error)]
pub enum RegionGetError {
#[display(fmt = "coordinates are out of bounds: {}", _0)]
OutOfBounds(#[error(ignore)] TileRegionPosition),
#[display(fmt = "failed to encode tile coordinates into an index: {}", position)]
IntConversion {
position: TileRegionPosition,
#[error(source)]
source: TryFromIntError,
},
}
#[derive(Clone, Debug, Display, Error)]
pub enum GetTileError {
#[display(fmt = "coordinates are out of bounds: {}", _0)]
OutOfBounds(#[error(ignore)] TileWorldPosition),
#[display(fmt = "failed to encode tile coordinates into an index: {}", position)]
IntConversion {
position: TileWorldPosition,
#[error(source)]
source: TryFromIntError,
},
}
|
use composer::*;
#[test]
fn token_test() {
use tokenize::TokenKind;
assert!(TokenKind::Character('c').is_character());
assert!(TokenKind::Number(42).is_number());
assert!(TokenKind::BraceString("string".to_string()).is_brace_string());
}
#[test]
fn tokenize_test() {
use tokenize::*;
use TokenKind::*;
assert!(tokenize("Do some 焼き松茸").is_err());
assert!(tokenize("9999999999999999999999999999999999999999999999999").is_err());
assert_eq!(
tokenize("c256e16g4<CEG4{This Is String}"),
Ok(vec![
(1, Character('c')),
(2, Number(256)),
(5, Character('e')),
(6, Number(16)),
(8, Character('g')),
(9, Number(4)),
(10, Character('<')),
(11, Character('c')),
(12, Character('e')),
(13, Character('g')),
(14, Number(4)),
(15, BraceString("ThisIsString".to_string()))
])
);
assert_eq!(
tokenize("C e\n\rG"),
Ok(vec![
(1, Character('c')),
(3, Character('e')),
(6, Character('g')),
])
);
}
|
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
extern crate docker;
#[macro_use]
mod macros;
pub mod registry_v2;
pub mod errors;
pub mod middleware;
pub mod d2dregistry;
pub use registry_v2::*;
pub use d2dregistry::DockerToDockerRegistry;
pub use errors::*;
|
use game::*;
use std;
fn collide_rects(x1: i64, y1: i64, w1: i64, h1: i64, x2: i64, y2: i64, w2: i64, h2: i64)->bool{
if x1>x2+w2||x1+w1<x2 {return false};
if y1>y2+h2||y1+h1<y2 {return false};
true
}
const MOVER_DEFAULT_WIDTH: i64=40-3;
impl Mover{
pub fn default(x: f64, y: f64)->Self{
Mover{x: x, y: y, xspeed: 0.0, yspeed: 0.0, width: MOVER_DEFAULT_WIDTH, height: MOVER_DEFAULT_WIDTH, solid: true, disabled: false}
}
pub fn default_moving(x: f64, y: f64, xspeed: f64, yspeed: f64)->Self{
Mover{x: x, y: y, xspeed: xspeed, yspeed: yspeed, width: MOVER_DEFAULT_WIDTH, height: MOVER_DEFAULT_WIDTH, solid: true, disabled: false}
}
pub fn new(movers: &mut GVec<Mover>, x: f64, y: f64)->MoverID{
MoverID{id:movers.add(Self::default(x,y))}
}
pub fn new_moving(movers: &mut GVec<Mover>, x:f64, y: f64, xs:f64, ys: f64)->MoverID{
MoverID{id:movers.add(Mover{x: x, y: y, xspeed: xs, yspeed: ys, width:MOVER_DEFAULT_WIDTH, height:MOVER_DEFAULT_WIDTH, solid: true, disabled: false})}
}
pub fn collide(&self, other: &Mover)->bool{
collide_rects(self.x_corner(),self.y_corner(), self.width, self.height, other.x_corner(), other.y_corner(), other.width, other.height)
}
pub fn x_corner(&self)->i64{
self.x.round() as i64-self.width/2
}
pub fn y_corner(&self)->i64{
self.y.round() as i64-self.height/2
}
pub fn distance(&self, other: &Mover)->f64{
let dx=other.x-self.x;
let dy=other.y-self.y;
(dx*dx+dy*dy).sqrt()
}
pub fn random_radius<T: Rng>(&self, rand_gen: &mut T, min: f64, max: f64)->(f64,f64){
let radius=rand_gen.gen_range(min, max);
let angle: f64=rand_gen.gen_range(0.0,std::f64::consts::PI*2.0);
(self.x+radius*angle.cos(), self.y-radius*angle.sin())
}
pub fn snap_grid(&mut self){
self.x=self.x/SQUARE_SIZE;
self.x=self.x.floor();
self.x=self.x*SQUARE_SIZE;
self.y=self.y/SQUARE_SIZE;
self.y=self.y.floor();
self.y=self.y*SQUARE_SIZE;
self.x+=SQUARE_SIZE/2.0;
self.y+=SQUARE_SIZE/2.0;
}
pub fn terrain_adjustment(&self)->Self{
let mut ret: Self=(*self).clone();
ret.x=ret.x+SQUARE_SIZE/2.0;
ret.y=ret.y+SQUARE_SIZE/2.0;
ret
}
pub fn chunk_adjustment(&self)->Self{
let mut ret: Self=(*self).clone();
ret.x=ret.x+CHUNK_WIDTH_PIXELS/2.0;
ret.y=ret.y+CHUNK_WIDTH_PIXELS/2.0;
ret
}
pub fn remove(game: &mut Game1, id: MoverID)->Self{
game.movers.remove(id.id)
}
}
impl MoverBuilder{
pub fn new()->Self{
MoverBuilder{x: 0.0, y: 0.0, xspeed: 0.0, yspeed: 0.0, width: MOVER_DEFAULT_WIDTH, height: MOVER_DEFAULT_WIDTH, solid: true, disabled: false}
}
pub fn instantiate(self, movers: &mut GVec<Mover>)->MoverID{
MoverID{id:movers.add(Mover{x:self.x, y: self.y, xspeed: self.xspeed, yspeed: self.yspeed, width: self.width, height: self.height, solid: self.solid, disabled: self.disabled})}
}
}
impl Orbiter{
pub fn step(game: &mut Game1){
for orbiter in game.orbiters.iter_mut(){
let mut mover=game.movers[orbiter.mover_id.id].take().expect("Orbiter has no mover");
let orbiting=game.movers[orbiter.orbiting_id.id].take().expect("Orbiter has no target");
mover.x=orbiting.x+orbiter.radius*orbiter.angle.cos();
mover.y=orbiting.y-orbiter.radius*orbiter.angle.sin();
orbiter.angle+=orbiter.angular_velocity;
orbiter.angle=orbiter.angle%(2.0*std::f64::consts::PI);
game.movers[orbiter.mover_id.id]=Some(mover);
game.movers[orbiter.orbiting_id.id]=Some(orbiting);
}
}
pub fn remove(game: &mut Game1, id: usize){
game.orbiters.remove(id);
}
}
impl Timer{
pub fn new(timers: &mut GVec<Timer>)->usize{
timers.add(Timer{steps_passed:0})
}
pub fn remove(game: &mut Game1, id: usize){
game.timers.remove(id);
}
}
impl DisabledMover{
pub fn new(disabled_movers: &mut GVec<DisabledMover>, alpha_id: MoverID, beta_id: MoverID)->DisabledMoverID{
DisabledMoverID{id: disabled_movers.add(DisabledMover {alpha_id: alpha_id, beta_id: beta_id})}
}
pub fn step(game: &mut Game1){
for disabled_mover in game.disabled_movers.iter_mut(){
let mut alpha=game.movers[disabled_mover.alpha_id.id].take().expect("Disabled mover links to none");
let mut beta=game.movers[disabled_mover.beta_id.id].take().expect("Disabled mover links to none");
if alpha.disabled{
if beta.disabled{
beta.disabled=false;
}
else {
alpha.x=beta.x;
alpha.y=beta.y;
}
}
else{
if beta.disabled{
beta.x=alpha.x;
beta.y=alpha.y;
}
else {
beta.disabled=true;
}
}
game.movers[disabled_mover.alpha_id.id]=Some(alpha);
game.movers[disabled_mover.beta_id.id]=Some(beta);
}
}
pub fn remove(game: &mut Game1, id: DisabledMoverID){
game.disabled_movers.remove(id.id);
}
}
pub fn step_movers(game: &mut Game1){
for mover in game.movers.iter_mut(){
if mover.disabled {continue;}
let last_x=mover.x;
let last_y=mover.y;
mover.x+=mover.xspeed;
mover.y+=mover.yspeed;
if !mover.solid {continue;};
let mut collided=false;
'outer:for (&(cx,cy),ref chunk) in game.chunks.iter(){
let px=(cx as f64)*(CHUNK_WIDTH_PIXELS);
let py=(cy as f64)*(CHUNK_WIDTH_PIXELS);
let mut chunk_rect=Mover::default(px,py);
chunk_rect.width=CHUNK_WIDTH_PIXELS as i64;
chunk_rect.height=CHUNK_WIDTH_PIXELS as i64;
chunk_rect=chunk_rect.chunk_adjustment();
if !mover.collide(&chunk_rect) {continue};
let rx=(mover.x.round() as i64 - px as i64)/(SQUARE_SIZE as i64);
let ry=(mover.y.round() as i64 - py as i64)/(SQUARE_SIZE as i64);
for i in -1..2{
let x=rx+i;
if x<0 {continue};
if x>=CHUNK_WIDTH {break};
for j in -1..2{
let y=ry+j;
if y<0 {continue};
if y>=CHUNK_WIDTH {break};
if !(chunk.solid[y as usize][x as usize]>0) {continue};
let square_rect=Mover::default(px+(x as f64)*SQUARE_SIZE,py+(y as f64)*SQUARE_SIZE).terrain_adjustment();
if !mover.collide(&square_rect){continue};
collided=true;
break 'outer;
}
}
}
if collided{
mover.x=last_x;
mover.y=last_y;
}
};
}
pub fn step_timers(game: &mut Game1){
for timer in game.timers.iter_mut() {timer.steps_passed+=1;};
}
pub fn step_basics(game:&mut Game1){
step_movers(game);
step_timers(game);
DisabledMover::step(game);
Orbiter::step(game);
Damageable::step(game);
Damager::step(game);
}
|
use rltk::{Point, VirtualKeyCode};
use specs::prelude::*;
use crate::{console_log, Context, GameLog, Item, Map, RunState, WaitCause, WantsToMelee, WantsToMove, WantsToPickUp, WantsToWait};
use super::{CombatStats, Player, Position, State};
pub fn player_input(state: &mut State, context: &mut Context) -> RunState {
match context.rltk.key {
None => { return RunState::AwaitingInput; }
Some(key) => match key {
VirtualKeyCode::Left |
VirtualKeyCode::H => try_move_player(-1, 0, &mut state.ecs),
VirtualKeyCode::Right |
VirtualKeyCode::L => try_move_player(1, 0, &mut state.ecs),
VirtualKeyCode::Up |
VirtualKeyCode::J => try_move_player(0, -1, &mut state.ecs),
VirtualKeyCode::Down |
VirtualKeyCode::K => try_move_player(0, 1, &mut state.ecs),
VirtualKeyCode::G => get_item(&mut state.ecs),
VirtualKeyCode::I => return RunState::ShowInventory,
VirtualKeyCode::D => return RunState::ShowDropItem,
VirtualKeyCode::W => wait(&mut state.ecs),
VirtualKeyCode::PageUp => {
try_scroll_game_log(&mut state.ecs, 1);
return RunState::AwaitingInput;
}
VirtualKeyCode::PageDown => {
try_scroll_game_log(&mut state.ecs, -1);
return RunState::AwaitingInput;
}
VirtualKeyCode::Escape => return RunState::SaveGame,
_ => return RunState::AwaitingInput,
},
}
RunState::PlayerTurn
}
pub fn wait(ecs: &mut World) {
let players = ecs.read_storage::<Player>();
let mut wants_to_wait = ecs.write_storage::<WantsToWait>();
let entities = ecs.entities();
for (entity, _player) in (&entities, &players).join() {
wants_to_wait.insert(entity, WantsToWait { cause: WaitCause::Choice }).expect("Unable to insert intent");
}
}
pub fn try_move_player(delta_x: i32, delta_y: i32, ecs: &mut World) {
let mut positions = ecs.write_storage::<Position>();
let players = ecs.read_storage::<Player>();
let mut wants_to_melee = ecs.write_storage::<WantsToMelee>();
let mut wants_to_move = ecs.write_storage::<WantsToMove>();
let combat_stats = ecs.read_storage::<CombatStats>();
let entities = ecs.entities();
let map = ecs.fetch::<Map>();
for (entity, _player, pos) in (&entities, &players, &mut positions).join() {
let new_x = pos.x + delta_x;
let new_y = pos.y + delta_y;
let new_idx = map.xy_idx(new_x, new_y);
if !map.is_valid_idx(new_idx) {
console_log(format!("({}, {}) is not valid", new_x, new_y));
return;
}
let potential_targets = &map.tile_content[new_idx];
for potential_target in potential_targets.iter() {
let potential_target = *potential_target;
let target_or_none = combat_stats.get(potential_target);
let is_target = target_or_none.is_some();
if is_target {
wants_to_melee
.insert(entity, WantsToMelee { target: potential_target })
.expect("Unable to insert intent");
return;
}
}
wants_to_move
.insert(entity, WantsToMove { destination: Point::new(new_x, new_y) })
.expect("Unable to insert intent");
}
}
fn try_scroll_game_log(ecs: &mut World, delta: i32) {
let mut game_log = ecs.write_resource::<GameLog>();
game_log.move_index(delta);
}
fn get_item(ecs: &mut World) {
let player_position = ecs.fetch::<Point>();
let player_entity = ecs.fetch::<Entity>();
let entities = ecs.entities();
let items = ecs.read_storage::<Item>();
let positions = ecs.read_storage::<Position>();
let mut wants_to_pick_up = ecs.write_storage::<WantsToPickUp>();
let mut game_log = ecs.fetch_mut::<GameLog>();
let mut picked_up_item_or_none: Option<Entity> = None;
for (_item, entity, position) in (&items, &entities, &positions).join() {
if position.x == player_position.x && position.y == player_position.y {
picked_up_item_or_none = Some(entity);
break;
}
}
match picked_up_item_or_none {
None => game_log.add("There is nothing to pick up.".to_string()),
Some(entity) => {
wants_to_pick_up
.insert(entity, WantsToPickUp { collected_by: *player_entity, item: entity })
.expect("Unable to insert WantsToPickUp");
}
}
}
|
#![allow(clippy::comparison_chain)]
#![allow(clippy::collapsible_if)]
use std::cmp::Reverse;
use std::cmp::{max, min};
use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};
use std::fmt::Debug;
use itertools::Itertools;
use whiteread::parse_line;
const ten97: usize = 1000_000_007;
/// 2の逆元 mod ten97.割りたいときに使う
const inv2ten97: u128 = 500_000_004;
// 01bfs
// 方向転換を1,そのまま進むを0コストにしてやる
fn main() {
let (h, w): (usize, usize) = parse_line().unwrap();
let (rs, ss): (usize, usize) = parse_line().unwrap();
let (rs, ss) = (rs - 1, ss - 1);
let (rt, st): (usize, usize) = parse_line().unwrap();
let (rt, st) = (rt - 1, st - 1);
let mut map: Vec<Vec<char>> = vec![];
for _ in 0..h {
let line: String = parse_line().unwrap();
map.push(line.chars().collect_vec());
}
let mut dist = vec![vec![vec![std::usize::MAX; 4]; w]; h];
let mut already = vec![vec![vec![false; 4]; w]; h];
let mut queue = VecDeque::new();
for i in 0..4 {
already[rs][ss][i] = true;
queue.push_back((rs, ss, i));
dist[rs][ss][i] = 0;
}
// この段階で1は調査済みであるので,
// 1に対して処理すべきことは済ましておく
while !queue.is_empty() {
let (r, c, nowd) = queue.pop_front().unwrap();
// dbg!(r, c, nowd, dist[r][c][nowd]);
if r == rt && c == st {
println!("{}", dist[r][c][nowd]);
return;
}
for nextd in 0..4 {
if nowd == nextd {
// dbg!(
// nextd == 1
// && c < w - 1
// && map[r][c + 1] == '.'
// && !already.contains(&(r, c + 1, nextd))
// );
if nextd == 0 && r > 0 && map[r - 1][c] == '.' && !already[r - 1][c][nextd] {
already[r - 1][c][nextd] = true;
if dist[r - 1][c][nextd] > dist[r][c][nextd] {
queue.push_front((r - 1, c, nowd));
dist[r - 1][c][nextd] = dist[r][c][nextd];
}
} else if nextd == 1
&& c < w - 1
&& map[r][c + 1] == '.'
&& !already[r][c + 1][nextd]
{
already[r][c + 1][nextd] = true;
if dist[r][c + 1][nextd] > dist[r][c][nextd] {
queue.push_front((r, c + 1, nowd));
dist[r][c + 1][nextd] = dist[r][c][nextd];
}
} else if nextd == 2
&& r < h - 1
&& map[r + 1][c] == '.'
&& !already[r + 1][c][nextd]
{
already[r + 1][c][nextd] = true;
if dist[r + 1][c][nextd] > dist[r][c][nextd] {
dist[r + 1][c][nextd] = dist[r][c][nextd];
queue.push_front((r + 1, c, nowd));
}
} else if nextd == 3 && c > 0 && map[r][c - 1] == '.' && !already[r][c - 1][nextd] {
already[r][c - 1][nextd] = true;
if dist[r][c - 1][nextd] > dist[r][c][nextd] {
dist[r][c - 1][nextd] = dist[r][c][nextd];
queue.push_front((r, c - 1, nowd));
}
}
} else {
if !already[r][c][nextd] {
// push_backするのでpush_frontを遮らないようにフラグは建てない
if dist[r][c][nextd] > dist[r][c][nowd] + 1 {
dist[r][c][nextd] = dist[r][c][nowd] + 1;
queue.push_back((r, c, nextd));
}
}
}
}
}
}
|
use ds::relations;
use examples_shared::{self as es, anyhow, ds, tokio, tracing};
#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let client = es::make_client(ds::Subscriptions::RELATIONSHIPS).await;
let mut rel_events = client.wheel.relationships().0;
let relationships = client.discord.get_relationships().await?;
tracing::info!("got relationships: {:#?}", relationships);
let relationships = std::sync::Arc::new(relations::state::Relationships::new(relationships));
let rs = relationships.clone();
tokio::task::spawn(async move {
while let Ok(re) = rel_events.recv().await {
tracing::info!(event = ?re, "received relationship event");
rs.on_event(re);
}
});
tokio::task::spawn_blocking(move || {
let mut r = String::new();
let _ = std::io::stdin().read_line(&mut r);
})
.await
.expect("failed to spawn task");
tracing::info!("current relationship states: {:#?}", relationships);
client.discord.disconnect().await;
Ok(())
}
|
use seed::{prelude::*, *};
use std::borrow::Cow;
use std::fmt;
use std::rc::Rc;
pub struct FormGroup<'a, Ms: 'static> {
id: Cow<'a, str>,
label: Option<Cow<'a, str>>,
value: Option<Cow<'a, str>>,
input_event: Option<Rc<dyn Fn(String) -> Ms>>,
input_type: InputType,
is_invalid: bool,
invalid_feedback: Option<Cow<'a, str>>,
is_warning: bool,
warning_feedback: Option<Cow<'a, str>>,
help_text: Vec<Node<Ms>>,
group_attrs: Attrs,
input_attrs: Attrs,
}
impl<'a, Ms> FormGroup<'a, Ms> {
pub fn new(id: impl Into<Cow<'a, str>>) -> Self {
Self {
id: id.into(),
label: None,
value: None,
input_event: None,
input_type: InputType::Text,
is_invalid: false,
invalid_feedback: None,
is_warning: false,
warning_feedback: None,
help_text: Vec::new(),
group_attrs: Attrs::empty(),
input_attrs: Attrs::empty(),
}
}
pub fn label(mut self, label: impl Into<Cow<'a, str>>) -> Self {
self.label = Some(label.into());
self
}
pub fn value(mut self, value: impl Into<Cow<'a, str>>) -> Self {
self.value = Some(value.into());
self
}
pub fn on_input(mut self, input_event: impl Fn(String) -> Ms + Clone + 'static) -> Self {
self.input_event = Some(Rc::new(input_event));
self
}
pub fn text(mut self) -> Self {
self.input_type = InputType::Text;
self
}
pub fn number(mut self) -> Self {
self.input_type = InputType::Number;
self
}
pub fn password(mut self) -> Self {
self.input_type = InputType::Password;
self
}
pub fn textarea(mut self) -> Self {
self.input_type = InputType::Textarea;
self
}
pub fn checkbox(mut self) -> Self {
self.input_type = InputType::Checkbox;
self
}
pub fn select(mut self, options: Vec<(String, String)>, include_none_option: bool) -> Self {
self.input_type = InputType::Select {
options,
include_none_option,
};
self
}
pub fn invalid(mut self, is_invalid: bool) -> Self {
self.is_invalid = is_invalid;
self
}
pub fn invalid_feedback(mut self, invalid_feedback: Option<impl Into<Cow<'a, str>>>) -> Self {
self.invalid_feedback = invalid_feedback.map(|s| s.into());
self
}
pub fn warning(mut self, is_warning: bool) -> Self {
self.is_warning = is_warning;
self
}
pub fn warning_feedback(mut self, warning_feedback: Option<impl Into<Cow<'a, str>>>) -> Self {
self.warning_feedback = warning_feedback.map(|s| s.into());
self
}
pub fn help_text(mut self, help_text: impl Into<Cow<'static, str>>) -> Self {
self.help_text = Node::new_text(help_text).into_nodes();
self
}
pub fn help_nodes(mut self, help_nodes: impl IntoNodes<Ms>) -> Self {
self.help_text = help_nodes.into_nodes();
self
}
pub fn group_attrs(mut self, attrs: Attrs) -> Self {
self.group_attrs.merge(attrs);
self
}
pub fn input_attrs(mut self, attrs: Attrs) -> Self {
self.input_attrs.merge(attrs);
self
}
pub fn view(self) -> Node<Ms> {
if self.input_type == InputType::Checkbox {
self.view_checkbox()
} else {
self.view_textfield()
}
}
fn view_checkbox(self) -> Node<Ms> {
let is_checked = self
.value
.as_ref()
.map(|value| value == "true")
.unwrap_or(false);
let click_event_text = if is_checked {
"false".to_string()
} else {
"true".to_string()
};
div![
C!["form-group form-check"],
&self.group_attrs,
input![
C!["form-check-input", IF!(self.is_invalid => "is-invalid")],
&self.input_attrs,
id![&self.id],
attrs![
At::Type => "checkbox",
At::Value => "true",
At::Checked => is_checked.as_at_value()
],
self.input_event.clone().map(|input_event| {
input_ev(Ev::Input, move |_event| input_event(click_event_text))
})
],
self.label.as_ref().map(|label| {
label![
C!["form-check-label"],
attrs![
At::For => self.id
],
label
]
}),
if !self.help_text.is_empty() {
small![C!["form-text text-muted"], &self.help_text]
} else {
empty![]
},
self.invalid_feedback
.as_ref()
.filter(|_| self.is_invalid)
.map(|err| div![C!["invalid-feedback"], err]),
self.warning_feedback
.as_ref()
.filter(|_| self.is_warning)
.map(|err| small![C!["form-text text-warning"], err])
]
}
fn view_textfield(self) -> Node<Ms> {
div![
C!["form-group"],
&self.group_attrs,
self.label.as_ref().map(|label| {
label![
attrs![
At::For => self.id
],
label
]
}),
match &self.input_type {
InputType::Text | InputType::Number | InputType::Password => input![
C!["form-control", IF!(self.is_invalid => "is-invalid")],
&self.input_attrs,
id![&self.id],
attrs![
At::Type => &self.input_type,
],
self.value.as_ref().map(|value| attrs![At::Value => value]),
self.input_event.clone().map(|input_event| {
input_ev(Ev::Input, move |event| input_event(event))
})
],
InputType::Textarea => textarea![
C!["form-control", IF!(self.is_invalid => "is-invalid")],
&self.input_attrs,
id![&self.id],
self.value.as_ref().map(
|value| attrs![At::Value => value, At::Rows => value.split('\n').count(), At::Wrap => "off"]
),
self.input_event.clone().map(|input_event| {
input_ev(Ev::Input, move |event| input_event(event))
})
],
InputType::Select { options, include_none_option } => select![
C!["custom-select", IF!(self.is_invalid => "is-invalid")],
if *include_none_option { option![
attrs! {
At::Value => "",
At::Selected => self.value.is_none().as_at_value()
}
] } else { empty![] },
options.iter().map(|(key, display)| {
option![
attrs! {
At::Value => &key,
At::Selected => self.value.as_ref().map(|value| value == key).unwrap_or(false).as_at_value()
},
&display
]
}),
self.input_event.clone().map(|input_event| {
input_ev(Ev::Input, move |event| input_event(event))
})
],
InputType::Checkbox => empty![],
},
if !self.help_text.is_empty() { small![C!["form-text text-muted"], &self.help_text] } else { empty![] },
self.invalid_feedback
.as_ref()
.filter(|_| self.is_invalid)
.map(|err| div![C!["invalid-feedback"], err]),
self.warning_feedback
.as_ref()
.filter(|_| self.is_warning)
.map(|err| small![C!["form-text text-warning"], err])
]
}
}
impl<Ms> UpdateEl<Ms> for FormGroup<'_, Ms> {
fn update_el(self, el: &mut El<Ms>) {
self.view().update_el(el)
}
}
#[derive(PartialEq)]
enum InputType {
Text,
Number,
Password,
Textarea,
Checkbox,
Select {
options: Vec<(String, String)>,
include_none_option: bool,
},
}
impl fmt::Display for InputType {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
match self {
Self::Text => write!(f, "text"),
Self::Number => write!(f, "number"),
Self::Password => write!(f, "password"),
Self::Textarea => write!(f, "textarea"),
Self::Checkbox => write!(f, "checkbox"),
Self::Select { .. } => write!(f, "select"),
}
}
}
|
use domain_patterns::command::Command;
use domain_patterns::message::Message;
#[derive(Clone, Command)]
pub struct RemoveSurveyCommand {
pub id: String,
pub requesting_author: String,
}
|
// Copyright 2020 - 2021 Alex Dukhno
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod connection;
use crate::connection::{Connection, New, Securing};
use native_tls::{Identity, TlsStream};
use std::{
convert::TryInto,
io,
io::{Read, Write},
net::TcpStream,
str,
};
use wire_protocol_payload::{
Inbound, Outbound, BIND, CLOSE, DESCRIBE, EMPTY_QUERY_RESPONSE, EXECUTE, FLUSH, PARSE, QUERY, READY_FOR_QUERY,
SYNC, TERMINATE,
};
pub type WireResult = std::result::Result<Inbound, WireError>;
#[derive(Debug)]
pub struct WireError;
pub trait WireConnection {
fn receive(&mut self) -> io::Result<WireResult>;
fn send(&mut self, outbound: Outbound) -> io::Result<()>;
}
pub struct PgWireAcceptor<S: Securing<TcpStream, TlsStream<TcpStream>>> {
secured: Option<S>,
}
impl<S: Securing<TcpStream, TlsStream<TcpStream>>> PgWireAcceptor<S> {
pub fn new(secured: Option<S>) -> PgWireAcceptor<S> {
PgWireAcceptor { secured }
}
}
impl PgWireAcceptor<Identity> {
pub fn accept(&self, socket: TcpStream) -> io::Result<ConnectionOld> {
let connection: Connection<New, TcpStream, TlsStream<TcpStream>> = Connection::new(socket);
let connection = connection.hand_shake::<Identity>(self.secured.clone())?;
let connection = connection.authenticate("whatever")?;
let connection = connection.send_params(&[
("client_encoding", "UTF8"),
("DateStyle", "ISO"),
("integer_datetimes", "off"),
("server_version", "13.0"),
])?;
let connection = connection.send_backend_keys(1, 1)?;
let mut channel = connection.channel();
channel.write_all(&[READY_FOR_QUERY, 0, 0, 0, 5, EMPTY_QUERY_RESPONSE])?;
channel.flush()?;
Ok(ConnectionOld::from(channel))
}
}
pub struct ConnectionOld {
socket: connection::Channel<TcpStream, TlsStream<TcpStream>>,
}
impl From<connection::Channel<TcpStream, TlsStream<TcpStream>>> for ConnectionOld {
fn from(socket: connection::Channel<TcpStream, TlsStream<TcpStream>>) -> ConnectionOld {
ConnectionOld { socket }
}
}
impl ConnectionOld {
fn parse_client_request(&mut self) -> io::Result<Result<Inbound, ()>> {
let tag = self.read_tag()?;
let len = self.read_message_len()?;
let mut message = self.read_message(len)?;
match tag {
// Simple query flow.
QUERY => {
let sql = str::from_utf8(&message[0..message.len() - 1]).unwrap().to_owned();
Ok(Ok(Inbound::Query { sql }))
}
// Extended query flow.
BIND => {
let portal_name = if let Some(pos) = message.iter().position(|b| *b == 0) {
let portal_name = str::from_utf8(&message[0..pos]).unwrap().to_owned();
message = message[pos + 1..].to_vec();
portal_name
} else {
unimplemented!()
};
let statement_name = if let Some(pos) = message.iter().position(|b| *b == 0) {
let statement_name = str::from_utf8(&message[0..pos]).unwrap().to_owned();
message = message[pos + 1..].to_vec();
statement_name
} else {
unimplemented!()
};
let param_formats_len = i16::from_be_bytes(message[0..2].try_into().unwrap());
message = message[2..].to_vec();
let mut query_param_formats = vec![];
for _ in 0..param_formats_len {
query_param_formats.push(i16::from_be_bytes(message[0..2].try_into().unwrap()));
message = message[2..].to_vec();
}
let params_len = i16::from_be_bytes(message[0..2].try_into().unwrap());
let mut query_params = vec![];
message = message[2..].to_vec();
for _ in 0..params_len {
let len = i32::from_be_bytes(message[0..4].try_into().unwrap());
message = message[4..].to_vec();
if len == -1 {
// As a special case, -1 indicates a NULL parameter value.
query_params.push(None);
} else {
let value = message[0..(len as usize)].to_vec();
query_params.push(Some(value));
message = message[(len as usize)..].to_vec();
}
}
let result_value_formats_len = i16::from_be_bytes(message[0..2].try_into().unwrap());
let mut result_value_formats = vec![];
message = message[2..].to_vec();
for _ in 0..result_value_formats_len {
result_value_formats.push(i16::from_be_bytes(message[0..2].try_into().unwrap()));
message = message[2..].to_vec();
}
Ok(Ok(Inbound::Bind {
portal_name,
statement_name,
query_param_formats,
query_params,
result_value_formats,
}))
}
CLOSE => {
let first_char = message[0];
let name = str::from_utf8(&message[1..message.len() - 1]).unwrap().to_owned();
match first_char {
b'P' => Ok(Ok(Inbound::ClosePortal { name })),
b'S' => Ok(Ok(Inbound::CloseStatement { name })),
_other => unimplemented!(),
}
}
DESCRIBE => {
let first_char = message[0];
let name = str::from_utf8(&message[1..message.len() - 1]).unwrap().to_owned();
match first_char {
b'P' => Ok(Ok(Inbound::DescribePortal { name })),
b'S' => Ok(Ok(Inbound::DescribeStatement { name })),
_other => unimplemented!(),
}
}
EXECUTE => {
let portal_name = if let Some(pos) = message.iter().position(|b| *b == 0) {
let portal_name = str::from_utf8(&message[0..pos]).unwrap().to_owned();
message = message[pos + 1..].to_vec();
portal_name
} else {
unimplemented!()
};
let max_rows = i32::from_be_bytes(message[0..4].try_into().unwrap());
Ok(Ok(Inbound::Execute { portal_name, max_rows }))
}
FLUSH => Ok(Ok(Inbound::Flush)),
PARSE => {
let statement_name = if let Some(pos) = message.iter().position(|b| *b == 0) {
let statement_name = str::from_utf8(&message[0..pos]).unwrap().to_owned();
message = message[pos + 1..].to_vec();
statement_name
} else {
unimplemented!()
};
let sql = if let Some(pos) = message.iter().position(|b| *b == 0) {
let sql = str::from_utf8(&message[0..pos]).unwrap().to_owned();
message = message[pos + 1..].to_vec();
sql
} else {
unimplemented!()
};
let param_types_len = i16::from_be_bytes(message[0..2].try_into().unwrap());
let mut param_types = vec![];
message = message[2..].to_vec();
for _ in 0..param_types_len {
let pg_type = u32::from_be_bytes(message[0..4].try_into().unwrap());
param_types.push(pg_type);
message = message[4..].to_vec();
}
Ok(Ok(Inbound::Parse {
statement_name,
sql,
param_types,
}))
}
SYNC => Ok(Ok(Inbound::Sync)),
TERMINATE => Ok(Ok(Inbound::Terminate)),
_ => Ok(Err(())),
}
}
fn read_tag(&mut self) -> io::Result<u8> {
let buff = &mut [0u8; 1];
self.socket.read_exact(buff.as_mut())?;
Ok(buff[0])
}
fn read_message_len(&mut self) -> io::Result<usize> {
let buff = &mut [0u8; 4];
self.socket.read_exact(buff.as_mut())?;
Ok((i32::from_be_bytes(*buff) as usize) - 4)
}
fn read_message(&mut self, len: usize) -> io::Result<Vec<u8>> {
let mut message = vec![0; len];
self.socket.read_exact(&mut message)?;
Ok(message)
}
/// Receive client messages
pub fn receive(&mut self) -> io::Result<Result<Inbound, ()>> {
let request = match self.parse_client_request() {
Ok(Ok(request)) => request,
Ok(Err(_err)) => return Ok(Err(())),
Err(err) if err.kind() == io::ErrorKind::UnexpectedEof => {
// Client disconnected the socket immediately without sending a
// Terminate message. Considers it as a client Terminate to save
// resource and exit smoothly.
Inbound::Terminate
}
Err(err) => return Err(err),
};
Ok(Ok(request))
}
}
impl Sender for ConnectionOld {
fn flush(&mut self) -> io::Result<()> {
self.socket.flush()
}
fn send(&mut self, message: &[u8]) -> io::Result<()> {
self.socket.write_all(message)?;
self.socket.flush()
}
}
/// Trait to handle server to client query results for PostgreSQL Wire Protocol
/// connection
pub trait Sender {
/// Flushes the output stream.
fn flush(&mut self) -> io::Result<()>;
/// Sends response messages to client. Most of the time it is a single
/// message, select result one of the exceptional situation
fn send(&mut self, message: &[u8]) -> io::Result<()>;
}
|
// Copyright © 2016-2017 VMware, Inc. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
use std::convert::{From, Into};
use rand::{thread_rng, Rng};
use rabble::{self, Pid, CorrelationId, Envelope};
use time::SteadyTime;
use msg::Msg;
use vr::vr_fsm::{Transition, VrState, State};
use vr::vr_msg::{VrMsg, GetState, NewState};
use vr::vr_ctx::VrCtx;
use super::Backup;
/// When a backup realizes it's behind it enters state transfer
///
/// In this state, the backup is waiting for a `NewState` message
state!(StateTransfer {
ctx: VrCtx
});
impl Transition for StateTransfer {
fn handle(mut self,
msg: VrMsg,
from: Pid,
cid: CorrelationId,
output: &mut Vec<Envelope<Msg>>) -> VrState
{
match msg {
// Replicas only respond to state transfer requests in normal mode
// in the same epoch and view
VrMsg::NewState(msg) => self.become_backup(msg, output),
VrMsg::Prepare(msg) => {
up_to_date!(self, from, msg, cid, output);
self.into()
}
VrMsg::Commit(msg) => {
up_to_date!(self, from, msg, cid, output);
self.into()
}
VrMsg::StartViewChange(msg) => {
up_to_date!(self, from, msg, cid, output);
self.into()
}
VrMsg::DoViewChange(msg) => {
up_to_date!(self, from, msg, cid, output);
self.into()
}
VrMsg::StartView(msg) => {
up_to_date!(self, from, msg, cid, output);
self.into()
}
VrMsg::GetState(msg) => {
up_to_date!(self, from, msg, cid, output);
self.into()
},
VrMsg::Tick => {
if self.ctx.idle_timeout() {
self.send_get_state_to_random_replica(cid, output);
}
self.into()
},
_ => self.into()
}
}
}
impl StateTransfer {
pub fn new(ctx: VrCtx) -> StateTransfer {
StateTransfer {
ctx: ctx
}
}
/// Enter state transfer
pub fn enter(ctx: VrCtx) -> VrState {
StateTransfer::new(ctx).into()
}
pub fn become_backup(mut self, msg: NewState, output: &mut Vec<Envelope<Msg>>) -> VrState {
self.ctx.last_received_time = SteadyTime::now();
let NewState {view, op, commit_num, log_tail, ..} = msg;
self.ctx.view = view;
self.ctx.op = op;
for m in log_tail {
self.ctx.log.push(m);
}
let cid = CorrelationId::pid(self.ctx.pid.clone());
let mut backup = Backup::new(self.ctx);
backup.set_primary(output);
backup.send_prepare_ok(cid, output);
backup.commit(commit_num, output)
}
/// When a new replica starts after reconfiguration it needs to send a get state request to all
/// replicas to ensure it gets the latest state.
pub fn start_reconfiguration(self,
cid: CorrelationId,
output: &mut Vec<Envelope<Msg>>) -> VrState
{
{
let msg = self.get_state_msg();
let from = &self.ctx.pid;
output.extend(self.ctx.old_config
.replicas
.iter()
.cloned()
.chain(self.ctx.new_config.replicas.iter().cloned())
.filter(|pid| *pid != self.ctx.pid)
.map(|pid| Envelope::new(pid,
from.clone(),
msg.clone(),
Some(cid.clone()))));
}
self.into()
}
/// We missed the reconfiguration, and don't know what the new config looks like or if the
/// old replicas have shutdown. Therefore retrieve the config from the new primary.
pub fn start_epoch<S>(state: S,
primary: Pid,
cid: CorrelationId,
new_epoch: u64,
new_view: u64,
output: &mut Vec<Envelope<Msg>>) -> VrState
where S: State
{
let mut new_state = StateTransfer { ctx: state.ctx() };
new_state.ctx.last_received_time = SteadyTime::now();
new_state.ctx.epoch = new_epoch;
new_state.ctx.view = new_view;
new_state.ctx.op = new_state.ctx.commit_num;
let end = StateTransfer::truncation_point(&new_state.ctx);
new_state.ctx.log.truncate(end);
let from = new_state.ctx.pid.clone();
let msg = new_state.get_state_msg();
output.push(Envelope::new(primary, from, msg, Some(cid)));
new_state.into()
}
pub fn start_view<S>(state: S,
new_view: u64,
cid: CorrelationId,
output: &mut Vec<Envelope<Msg>>) -> VrState
where S: State
{
let mut new_state = StateTransfer { ctx: state.ctx() };
new_state.ctx.last_received_time = SteadyTime::now();
new_state.ctx.view = new_view;
new_state.ctx.op = new_state.ctx.commit_num;
let end = StateTransfer::truncation_point(&new_state.ctx);
new_state.ctx.log.truncate(end);
new_state.send_get_state_to_random_replica(cid, output);
new_state.into()
}
// Send a state transfer message
pub fn start_same_view(ctx: VrCtx,
cid: CorrelationId,
output: &mut Vec<Envelope<Msg>>) -> VrState
{
let mut new_state = StateTransfer { ctx: ctx };
new_state.send_get_state_to_random_replica(cid, output);
new_state.into()
}
pub fn send_new_state(ctx: &VrCtx,
op: u64,
to: Pid,
cid: CorrelationId,
output: &mut Vec<Envelope<Msg>>)
{
let msg = StateTransfer::new_state_msg(ctx, op);
output.push(Envelope::new(to, ctx.pid.clone(), msg, Some(cid)))
}
fn send_get_state_to_random_replica(&mut self,
cid: CorrelationId,
output: &mut Vec<Envelope<Msg>>) {
let msg = self.get_state_msg();
let mut rng = thread_rng();
let mut to = self.ctx.pid.clone();
while to == self.ctx.pid {
let index = rng.gen_range(0, self.ctx.new_config.replicas.len());
to = self.ctx.new_config.replicas[index].clone()
}
output.push(Envelope::new(to, self.ctx.pid.clone(), msg, Some(cid)));
}
fn get_state_msg(&self) -> rabble::Msg<Msg> {
GetState {
epoch: self.ctx.epoch,
view: self.ctx.view,
op: self.ctx.op
}.into()
}
fn new_state_msg(ctx: &VrCtx, op: u64) -> rabble::Msg<Msg> {
let start = (op - ctx.log_start) as usize;
let end = (ctx.op - ctx.log_start) as usize;
NewState {
epoch: ctx.epoch,
view: ctx.view,
op: ctx.op,
commit_num: ctx.commit_num,
log_tail: (&ctx.log[start..end]).to_vec()
}.into()
}
/// We don't want to truncate past the global_min_accept value. We also know that operations up
/// to the global_min_accept value cannot be reordered since they exist on all replicas.
/// Therefore if the global_min_accept > commit_num we only truncate to the global_min_accept
/// entry. Otherwise we truncate to the latest commited entry.
fn truncation_point(ctx: &VrCtx) -> usize {
if ctx.global_min_accept > ctx.commit_num {
return (ctx.global_min_accept - ctx.log_start) as usize;
}
(ctx.commit_num - ctx.log_start) as usize
}
}
|
#![allow(unused_imports)]
use std::os::unix::net::UnixStream;
use sodiumoxide::crypto::box_;
use std::io::{self, BufRead, BufReader, Write};
use std::str::from_utf8;
use common::SOCKET_PATH;
pub mod common;
fn main() {
let mut stream = UnixStream::connect(SOCKET_PATH).expect("Couldn't connect to the socket");
loop {
let mut input = String::new();
let mut buffer: Vec<u8> = Vec::new();
io::stdin().read_line(&mut input).expect("Failed to read from stdin");
stream.write(input.as_bytes()).expect("Failed to write to server");
let mut reader = BufReader::new(&stream);
reader.read_until(b'\n', &mut buffer).expect("Could not read into buffer");
print!("{}", from_utf8(&buffer).expect("Could not write buffer as string"));
//println!("{}", from_utf8(&buffer).unwrap());
}
}
|
/*
* Author: Dave Eddy <dave@daveeddy.com>
* Date: February 20, 2022
* License: MIT
*/
use anyhow::Result;
use assert_cmd::Command;
pub fn vsv() -> Result<Command> {
let mut cmd = Command::cargo_bin("vsv")?;
cmd.env_clear();
Ok(cmd)
}
|
pub mod energy;
/**
* Extractors index
*/
pub mod rms;
pub mod zcr;
pub mod amp_spectrum;
pub mod power_spectrum;
pub mod spectral_centroid;
pub mod spectral_flatness;
pub mod spectral_kurtosis;
pub mod spectral_rolloff;
pub mod bark_loudness;
|
use std::default::Default;
use std::time::Duration;
use aspect::Aspect;
use context::{Context, InternalContext};
use entity::Entity;
pub trait System {
type Aspect: Aspect;
fn process(&mut self, context: &mut impl Context, duration: Duration, entities: Vec<Entity>);
}
trait Executor {
fn execute(&mut self, context: &mut InternalContext, duration: Duration);
}
impl<T, K> Executor for K
where
T: Aspect,
K: System<Aspect = T>,
{
fn execute(&mut self, context: &mut InternalContext, duration: Duration) {
let entities = context.get_entities::<T>();
self.process(context, duration, entities)
}
}
#[derive(Default)]
pub(crate) struct SystemDispatcher<'a> {
systems: Vec<Box<Executor + 'a>>,
}
impl<'a> SystemDispatcher<'a> {
pub fn new() -> Self {
Default::default()
}
pub fn register(&mut self, system: impl System + 'a) {
self.systems.push(Box::new(system))
}
pub fn dispatch(&mut self, context: &mut InternalContext, duration: Duration) {
for system in self.systems.iter_mut() {
system.execute(context, duration);
}
}
}
#[cfg(test)]
mod tests {
use super::super::storage::VecStorage;
use super::*;
use aspect::{Aspect, Not};
use component::{Component, ComponentManager};
use entity::{Entity, EntityManager};
#[derive(Default)]
struct MyComponent;
impl Component for MyComponent {
type Storage = VecStorage<Self>;
}
#[derive(Default)]
struct AnotherComponent;
impl Component for AnotherComponent {
type Storage = VecStorage<Self>;
}
struct MySystem;
impl System for MySystem {
type Aspect = (MyComponent, Not<AnotherComponent>);
fn process(&mut self, context: &mut impl Context, duration: Duration, entities: Vec<Entity>) {
assert!(!entities.is_empty());
for entity in entities {
let editor = context.editor(entity);
assert!(editor.contains::<MyComponent>());
assert!(!editor.contains::<AnotherComponent>());
}
}
}
struct PanickingSystem;
impl System for PanickingSystem {
type Aspect = (MyComponent, Not<AnotherComponent>);
fn process(&mut self, context: &mut impl Context, duration: Duration, entities: Vec<Entity>) {
panic!("For testing!");
}
}
#[test]
fn get_aspect() {
let mut component_manager = ComponentManager::new();
component_manager.register::<MyComponent>();
component_manager.register::<AnotherComponent>();
// all good as long as this compiles
let (_req, _not) = (
<MySystem as System>::Aspect::req(&component_manager),
<MySystem as System>::Aspect::not(&component_manager),
);
}
#[test]
#[should_panic]
fn dispatch() {
let mut entity_manager = EntityManager::new();
entity_manager.component_manager.register::<MyComponent>();
entity_manager.component_manager.register::<AnotherComponent>();
let mut context = InternalContext::new(&mut entity_manager);
let mut dispatcher = SystemDispatcher::new();
dispatcher.register(PanickingSystem);
dispatcher.dispatch(&mut context, Duration::from_millis(100));
}
}
|
#[doc = "Reader of register DMAISR"]
pub type R = crate::R<u32, super::DMAISR>;
#[doc = "Reader of field `DC0IS`"]
pub type DC0IS_R = crate::R<bool, bool>;
#[doc = "Reader of field `MTLIS`"]
pub type MTLIS_R = crate::R<bool, bool>;
#[doc = "Reader of field `MACIS`"]
pub type MACIS_R = crate::R<bool, bool>;
impl R {
#[doc = "Bit 0 - DMA Channel Interrupt Status"]
#[inline(always)]
pub fn dc0is(&self) -> DC0IS_R {
DC0IS_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 16 - MTL Interrupt Status"]
#[inline(always)]
pub fn mtlis(&self) -> MTLIS_R {
MTLIS_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - MAC Interrupt Status"]
#[inline(always)]
pub fn macis(&self) -> MACIS_R {
MACIS_R::new(((self.bits >> 17) & 0x01) != 0)
}
}
|
use colored::*;
use std::fmt;
use std::io;
use std::string::{FromUtf8Error, String};
use utf8::BufReadDecoderError;
#[derive(Debug)]
pub enum Error {
IO(io::Error),
UTF8(),
PATH(Vec<u8>),
MANY(Vec<Error>),
CUSTOM(String),
PARSEFORMAT(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::IO(err) => write!(f, "{}: {}", "IO Error".red().bold(), err),
Error::UTF8() => write!(f, "{}", "UTF-8 Error".red().bold()),
Error::PATH(v) => write!(
f,
"{}: {}",
"Invalid Path".red().bold(),
String::from_utf8_lossy(v)
),
Error::MANY(errs) => write!(f, "{}: {:?}", "Errors".red().bold(), errs),
Error::CUSTOM(s) => write!(f, "{}: {}", "Error".red().bold(), s),
Error::PARSEFORMAT(s) => write!(f, "{}: {}", "Error Parsing --format".red().bold(), s),
}
}
}
impl From<io::Error> for Error {
fn from(err: io::Error) -> Error {
Error::IO(err)
}
}
impl From<Vec<Error>> for Error {
fn from(errs: Vec<Error>) -> Error {
Error::MANY(errs)
}
}
impl From<String> for Error {
fn from(msg: String) -> Error {
Error::CUSTOM(msg)
}
}
impl From<FromUtf8Error> for Error {
fn from(err: FromUtf8Error) -> Error {
Error::PATH(err.into_bytes())
}
}
impl<'a> From<BufReadDecoderError<'a>> for Error {
fn from(err: BufReadDecoderError<'a>) -> Error {
match err {
BufReadDecoderError::InvalidByteSequence(_) => Error::UTF8(),
BufReadDecoderError::Io(ioerr) => Error::IO(ioerr),
}
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::SSMUX2 {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct ADC_SSMUX2_MUX0R {
bits: u8,
}
impl ADC_SSMUX2_MUX0R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _ADC_SSMUX2_MUX0W<'a> {
w: &'a mut W,
}
impl<'a> _ADC_SSMUX2_MUX0W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 0);
self.w.bits |= ((value as u32) & 15) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct ADC_SSMUX2_MUX1R {
bits: u8,
}
impl ADC_SSMUX2_MUX1R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _ADC_SSMUX2_MUX1W<'a> {
w: &'a mut W,
}
impl<'a> _ADC_SSMUX2_MUX1W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 4);
self.w.bits |= ((value as u32) & 15) << 4;
self.w
}
}
#[doc = r"Value of the field"]
pub struct ADC_SSMUX2_MUX2R {
bits: u8,
}
impl ADC_SSMUX2_MUX2R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _ADC_SSMUX2_MUX2W<'a> {
w: &'a mut W,
}
impl<'a> _ADC_SSMUX2_MUX2W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 8);
self.w.bits |= ((value as u32) & 15) << 8;
self.w
}
}
#[doc = r"Value of the field"]
pub struct ADC_SSMUX2_MUX3R {
bits: u8,
}
impl ADC_SSMUX2_MUX3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _ADC_SSMUX2_MUX3W<'a> {
w: &'a mut W,
}
impl<'a> _ADC_SSMUX2_MUX3W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(15 << 12);
self.w.bits |= ((value as u32) & 15) << 12;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:3 - 1st Sample Input Select"]
#[inline(always)]
pub fn adc_ssmux2_mux0(&self) -> ADC_SSMUX2_MUX0R {
let bits = ((self.bits >> 0) & 15) as u8;
ADC_SSMUX2_MUX0R { bits }
}
#[doc = "Bits 4:7 - 2nd Sample Input Select"]
#[inline(always)]
pub fn adc_ssmux2_mux1(&self) -> ADC_SSMUX2_MUX1R {
let bits = ((self.bits >> 4) & 15) as u8;
ADC_SSMUX2_MUX1R { bits }
}
#[doc = "Bits 8:11 - 3rd Sample Input Select"]
#[inline(always)]
pub fn adc_ssmux2_mux2(&self) -> ADC_SSMUX2_MUX2R {
let bits = ((self.bits >> 8) & 15) as u8;
ADC_SSMUX2_MUX2R { bits }
}
#[doc = "Bits 12:15 - 4th Sample Input Select"]
#[inline(always)]
pub fn adc_ssmux2_mux3(&self) -> ADC_SSMUX2_MUX3R {
let bits = ((self.bits >> 12) & 15) as u8;
ADC_SSMUX2_MUX3R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:3 - 1st Sample Input Select"]
#[inline(always)]
pub fn adc_ssmux2_mux0(&mut self) -> _ADC_SSMUX2_MUX0W {
_ADC_SSMUX2_MUX0W { w: self }
}
#[doc = "Bits 4:7 - 2nd Sample Input Select"]
#[inline(always)]
pub fn adc_ssmux2_mux1(&mut self) -> _ADC_SSMUX2_MUX1W {
_ADC_SSMUX2_MUX1W { w: self }
}
#[doc = "Bits 8:11 - 3rd Sample Input Select"]
#[inline(always)]
pub fn adc_ssmux2_mux2(&mut self) -> _ADC_SSMUX2_MUX2W {
_ADC_SSMUX2_MUX2W { w: self }
}
#[doc = "Bits 12:15 - 4th Sample Input Select"]
#[inline(always)]
pub fn adc_ssmux2_mux3(&mut self) -> _ADC_SSMUX2_MUX3W {
_ADC_SSMUX2_MUX3W { w: self }
}
}
|
use std::fs::File;
use std::io::{self, prelude::*, BufReader};
use std::path::Path;
use reqwest;
// fn load_example_magnet_link() -> String {
// let file_path = Path::new("./src/data/example-magnet-link.txt");
// let file = File::open(file_path).expect("File not found");
// let mut reader = BufReader::new(file);
// let mut magnet_url = String::new();
// reader.read_to_string(&mut magnet_url).unwrap();
// magnet_url
// }
/// Loads a list of tracker data sources from a text file
///
/// Returns the list of tracker data sources as a vector of Strings
///
/// # Example
///
/// ```
/// use trackers::load_trackers_from_file;
///
/// let trackers = load_trackers_from_file();
///
/// println!("{}", trackers.len());
/// ```
fn load_sources_from_file() -> Vec<String> {
let file_path = Path::new("./src/data/links.txt");
let file = File::open(file_path).expect("File not found");
let reader = BufReader::new(file);
let mut trackers: Vec<String> = Vec::new();
for line in reader.lines() {
trackers.push(line.unwrap());
}
trackers
}
async fn build_list_of_trackers(sources: Vec<String>) -> Result<Vec<String>, reqwest::Error> {
let mut trackers: Vec<String> = Vec::new();
for source in sources {
let body = reqwest::get(source.as_str()).await?.text().await?;
let mut current_trackers = body
.lines()
.map(|l| String::from(l))
.collect::<Vec<String>>();
trackers.append(&mut current_trackers);
}
// Sort and remove duplicates just in case trackers are in multiple lists
trackers.sort();
trackers.dedup();
Ok(trackers)
}
fn remove_existing_trackers(magnet_url: &str, trackers: Vec<String>) -> Vec<String> {
// Collect existing trackers from magnet link
let existing_trackers = magnet_url
.split('&')
.filter(|p| p.contains("tr="))
.map(|p| p.replace("tr=", "").replace("\r\n", ""))
.collect::<Vec<String>>();
let filtered_trackers = trackers
.into_iter()
.filter(|t| !existing_trackers.contains(t))
.collect::<Vec<String>>();
filtered_trackers
}
/// Copies the provided magnet URL to the OS-level clipboard
fn copy_to_clipboard(magnet_url: String) {
use clipboard::ClipboardContext;
use clipboard::ClipboardProvider;
let mut ctx: ClipboardContext = ClipboardProvider::new().unwrap();
ctx.set_contents(magnet_url).unwrap();
}
#[tokio::main]
async fn main() -> Result<(), reqwest::Error> {
println!("\nLoading sources from file...");
let sources = load_sources_from_file();
println!(
"Downloading trackers from {} source{}...",
&sources.len(),
if sources.len() == 1 { "" } else { "s" }
);
let trackers = build_list_of_trackers(sources).await?;
println!("{} trackers downloaded!\n", &trackers.len());
println!("Enter the magnet URL:");
let mut magnet_url = String::new();
io::stdin()
.read_line(&mut magnet_url)
.expect("Unable to read user input");
println!("\nRemoving existing trackers from list...");
let trackers = remove_existing_trackers(&magnet_url, trackers);
println!("Adding {} trackers to magnet link...", &trackers.len());
for tracker in trackers {
let tracker = format!("&tr={}", tracker);
magnet_url = format!("{}{}", magnet_url, tracker);
}
copy_to_clipboard(magnet_url);
println!("Updated URL copied to clipboard!\n");
Ok(())
}
|
extern crate serde;
extern crate serde_xml_rs;
use serde::{Deserialize, Serialize};
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename = "designspace")]
pub struct Designspace {
pub format: i32,
pub axes: Axes,
pub sources: Sources,
pub instances: Option<Instances>,
// pub rules: Rules,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename = "axes")]
pub struct Axes {
pub axis: Vec<Axis>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename = "axes")]
pub struct Axis {
pub name: String,
pub tag: String,
pub minimum: i32,
pub maximum: i32,
pub default: i32,
pub hidden: Option<bool>,
pub labelname: Option<Vec<LabelName>>,
pub map: Option<Vec<Mapping>>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct LabelName {
pub lang: String,
#[serde(rename = "$value")]
pub value: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Mapping {
pub input: f32,
pub output: f32,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Sources {
pub source: Vec<Source>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Source {
pub familyname: Option<String>,
pub stylename: Option<String>,
pub name: String,
pub filename: String,
pub layer: Option<String>,
pub location: Vec<Location>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Location {
pub dimension: Vec<Dimension>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Dimension {
pub name: String,
pub xvalue: f32,
pub yvalue: Option<f32>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Instances {
pub instance: Vec<Instance>,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct Instance {
pub familyname: String,
pub stylename: String,
pub name: String,
pub filename: Option<String>,
pub postscriptfontname: Option<String>,
pub stylemapfamilyname: Option<String>,
pub stylemapstylename: Option<String>,
pub location: Vec<Location>,
}
#[cfg(test)]
mod tests {
use crate::Designspace;
use serde_xml_rs::from_reader;
#[test]
fn test_de() {
let s = r##"
<designspace format="2">
<axes>
<axis default="1" maximum="1000" minimum="0" name="weight" tag="wght">
<labelname xml:lang="fa-IR">قطر</labelname>
<labelname xml:lang="en">Wéíght</labelname>
</axis>
<axis default="100" maximum="200" minimum="50" name="width" tag="wdth">
<map input="50.0" output="10.0" />
<map input="100.0" output="66.0" />
<map input="200.0" output="990.0" />
</axis>
</axes>
<sources>
<source familyname="MasterFamilyName" filename="masters/masterTest1.ufo" name="master.ufo1" stylename="MasterStyleNameOne">
<lib copy="1" />
<features copy="1" />
<info copy="1" />
<glyph mute="1" name="A" />
<glyph mute="1" name="Z" />
<location>
<dimension name="width" xvalue="0.000000" />
<dimension name="weight" xvalue="0.000000" />
</location>
</source>
</sources>
<instances>
<instance familyname="InstanceFamilyName" filename="instances/instanceTest2.ufo" name="instance.ufo2" postscriptfontname="InstancePostscriptName" stylemapfamilyname="InstanceStyleMapFamilyName" stylemapstylename="InstanceStyleMapStyleName" stylename="InstanceStyleName">
<location>
<dimension name="width" xvalue="400" yvalue="300" />
<dimension name="weight" xvalue="66" />
</location>
<kerning />
<info />
<lib>
<dict>
<key>com.coolDesignspaceApp.specimenText</key>
<string>Hamburgerwhatever</string>
</dict>
</lib>
</instance>
</instances>
</designspace>
"##;
let designspace: Designspace = from_reader(s.as_bytes()).unwrap();
println!("{:#?}", designspace);
assert!(false);
}
}
|
use super::{Item, Value};
impl Item {
pub fn get_tagged<'a>(&'a self, tag: &str) -> Option<&'a Value> {
for arg in &self.args {
if let Some(ref inner_tag) = arg.tag {
if inner_tag == tag {
return Some(&arg.value);
}
}
}
None
}
pub fn get_num<'a>(&'a self, num: usize) -> Option<&'a Value> {
self.args.get(num).map(|v| &v.value)
}
pub fn validate(&self, untagged_count: usize, accepted: &[&str], required: &[&str])
-> Result<(), String> {
// Untagged
let mut is_head = true;
let mut num_leading = 0;
for arg in &self.args {
if is_head && arg.tag == None {
num_leading += 1;
} else if !is_head && arg.tag == None {
return Err(format!(
"untagged properties can only exist at the beginning"));
} else {
is_head = false;
}
}
if untagged_count != num_leading {
return Err(format!(
"item must have exactly {} untagged properties, got {}",
untagged_count, num_leading));
}
// Tagged
let mut required_found: Vec<&str> = Vec::new();
for arg in &self.args {
if let Some(ref tag) = arg.tag {
if !accepted.contains(&tag.as_str()) {
return Err(format!(
"{:?} is not an accepted tag for this item. (accepted: {:?})",
tag, accepted));
}
if required.contains(&tag.as_str()) {
if required_found.contains(&tag.as_str()) {
return Err(format!(
"tag {:?} provided more then once", tag));
}
required_found.push(tag);
}
}
}
if required.len() != required_found.len() {
return Err(format!(
"required tags {:?}, got only {:?}", required, required_found));
}
Ok(())
}
pub fn is_name_only(&self) -> bool {
self.args.len() == 0 && self.block.statements.len() == 0
}
}
#[cfg(test)]
mod tests {
use super::super::{Ident, Item, ItemArg, Value, Block};
macro_rules! test_constr_item_arg {
($tag:expr) => {
ItemArg {
tag: $tag,
value: Value::String {
string: "".into(),
is_block: false,
},
}
}
}
#[test]
fn tag_validators() {
let proper = Item {
name: Ident::Simple("".into()),
args: vec![
test_constr_item_arg!(None),
test_constr_item_arg!(None),
test_constr_item_arg!(None),
test_constr_item_arg!(Some("foo".into())),
test_constr_item_arg!(Some("bar".into())),
],
block: Block::empty(),
};
let improper = Item {
name: Ident::Simple("".into()),
args: vec![
test_constr_item_arg!(None),
test_constr_item_arg!(Some("foo".into())),
test_constr_item_arg!(None),
test_constr_item_arg!(Some("bar".into())),
],
block: Block::empty(),
};
assert!(proper.validate(
3,
&["foo", "bar", "baz"],
&["foo"]
).is_ok());
assert!(proper.validate(
3,
&["foo", "baz"],
&["foo"]
).is_err());
assert!(proper.validate(
3,
&["foo", "bar", "baz"],
&["baz"]
).is_err());
assert!(proper.validate(
2,
&["foo", "bar", "baz"],
&["foo"]
).is_err());
assert!(improper.validate(
1,
&["foo", "bar"],
&["foo"]
).is_err());
assert!(improper.validate(
2,
&["foo", "bar"],
&["foo"]
).is_err());
}
#[test]
fn tag_getters() {
let proper = Item {
name: Ident::Simple("".into()),
args: vec![
test_constr_item_arg!(None),
test_constr_item_arg!(None),
test_constr_item_arg!(None),
test_constr_item_arg!(Some("foo".into())),
test_constr_item_arg!(Some("bar".into())),
],
block: Block::empty(),
};
assert!(proper.get_num(1).is_some());
assert!(proper.get_num(4).is_some());
assert!(proper.get_num(8).is_none());
assert!(proper.get_tagged("foo").is_some());
assert!(proper.get_tagged("baz").is_none());
}
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u32,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u32,
}
impl super::SYSCONFIG {
#[doc = r"Modifies the contents of the register"]
#[inline(always)]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
self.register.set(f(&R { bits }, &mut W { bits }).bits);
}
#[doc = r"Reads the contents of the register"]
#[inline(always)]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r"Writes to the register"]
#[inline(always)]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
self.register.set(
f(&mut W {
bits: Self::reset_value(),
})
.bits,
);
}
#[doc = r"Reset value of the register"]
#[inline(always)]
pub const fn reset_value() -> u32 {
0
}
#[doc = r"Writes the reset value to the register"]
#[inline(always)]
pub fn reset(&self) {
self.register.set(Self::reset_value())
}
}
#[doc = r"Value of the field"]
pub struct AES_SYSCONFIG_SOFTRESETR {
bits: bool,
}
impl AES_SYSCONFIG_SOFTRESETR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_SYSCONFIG_SOFTRESETW<'a> {
w: &'a mut W,
}
impl<'a> _AES_SYSCONFIG_SOFTRESETW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 1);
self.w.bits |= ((value as u32) & 1) << 1;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_SYSCONFIG_DMA_REQ_DATA_IN_ENR {
bits: bool,
}
impl AES_SYSCONFIG_DMA_REQ_DATA_IN_ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_SYSCONFIG_DMA_REQ_DATA_IN_ENW<'a> {
w: &'a mut W,
}
impl<'a> _AES_SYSCONFIG_DMA_REQ_DATA_IN_ENW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 5);
self.w.bits |= ((value as u32) & 1) << 5;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_SYSCONFIG_DMA_REQ_DATA_OUT_ENR {
bits: bool,
}
impl AES_SYSCONFIG_DMA_REQ_DATA_OUT_ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_SYSCONFIG_DMA_REQ_DATA_OUT_ENW<'a> {
w: &'a mut W,
}
impl<'a> _AES_SYSCONFIG_DMA_REQ_DATA_OUT_ENW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 6);
self.w.bits |= ((value as u32) & 1) << 6;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENR {
bits: bool,
}
impl AES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENW<'a> {
w: &'a mut W,
}
impl<'a> _AES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 7);
self.w.bits |= ((value as u32) & 1) << 7;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_SYSCONFIG_DMA_REQ_CONTEXT_OUT_ENR {
bits: bool,
}
impl AES_SYSCONFIG_DMA_REQ_CONTEXT_OUT_ENR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_SYSCONFIG_DMA_REQ_CONTEXT_OUT_ENW<'a> {
w: &'a mut W,
}
impl<'a> _AES_SYSCONFIG_DMA_REQ_CONTEXT_OUT_ENW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 8);
self.w.bits |= ((value as u32) & 1) << 8;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_SYSCONFIG_MAP_CONTEXT_OUT_ON_DATA_OUTR {
bits: bool,
}
impl AES_SYSCONFIG_MAP_CONTEXT_OUT_ON_DATA_OUTR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_SYSCONFIG_MAP_CONTEXT_OUT_ON_DATA_OUTW<'a> {
w: &'a mut W,
}
impl<'a> _AES_SYSCONFIG_MAP_CONTEXT_OUT_ON_DATA_OUTW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 9);
self.w.bits |= ((value as u32) & 1) << 9;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_SYSCONFIG_KEYENCR {
bits: bool,
}
impl AES_SYSCONFIG_KEYENCR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_SYSCONFIG_KEYENCW<'a> {
w: &'a mut W,
}
impl<'a> _AES_SYSCONFIG_KEYENCW<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 11);
self.w.bits |= ((value as u32) & 1) << 11;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_SYSCONFIG_K3R {
bits: bool,
}
impl AES_SYSCONFIG_K3R {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r"Returns `true` if the bit is clear (0)"]
#[inline(always)]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r"Returns `true` if the bit is set (1)"]
#[inline(always)]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = r"Proxy"]
pub struct _AES_SYSCONFIG_K3W<'a> {
w: &'a mut W,
}
impl<'a> _AES_SYSCONFIG_K3W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 12);
self.w.bits |= ((value as u32) & 1) << 12;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 1 - Soft reset"]
#[inline(always)]
pub fn aes_sysconfig_softreset(&self) -> AES_SYSCONFIG_SOFTRESETR {
let bits = ((self.bits >> 1) & 1) != 0;
AES_SYSCONFIG_SOFTRESETR { bits }
}
#[doc = "Bit 5 - DMA Request Data In Enable"]
#[inline(always)]
pub fn aes_sysconfig_dma_req_data_in_en(&self) -> AES_SYSCONFIG_DMA_REQ_DATA_IN_ENR {
let bits = ((self.bits >> 5) & 1) != 0;
AES_SYSCONFIG_DMA_REQ_DATA_IN_ENR { bits }
}
#[doc = "Bit 6 - DMA Request Data Out Enable"]
#[inline(always)]
pub fn aes_sysconfig_dma_req_data_out_en(&self) -> AES_SYSCONFIG_DMA_REQ_DATA_OUT_ENR {
let bits = ((self.bits >> 6) & 1) != 0;
AES_SYSCONFIG_DMA_REQ_DATA_OUT_ENR { bits }
}
#[doc = "Bit 7 - DMA Request Context In Enable"]
#[inline(always)]
pub fn aes_sysconfig_dma_req_context_in_en(&self) -> AES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENR {
let bits = ((self.bits >> 7) & 1) != 0;
AES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENR { bits }
}
#[doc = "Bit 8 - DMA Request Context Out Enable"]
#[inline(always)]
pub fn aes_sysconfig_dma_req_context_out_en(&self) -> AES_SYSCONFIG_DMA_REQ_CONTEXT_OUT_ENR {
let bits = ((self.bits >> 8) & 1) != 0;
AES_SYSCONFIG_DMA_REQ_CONTEXT_OUT_ENR { bits }
}
#[doc = "Bit 9 - Map Context Out on Data Out Enable"]
#[inline(always)]
pub fn aes_sysconfig_map_context_out_on_data_out(
&self,
) -> AES_SYSCONFIG_MAP_CONTEXT_OUT_ON_DATA_OUTR {
let bits = ((self.bits >> 9) & 1) != 0;
AES_SYSCONFIG_MAP_CONTEXT_OUT_ON_DATA_OUTR { bits }
}
#[doc = "Bit 11 - Key Encoding"]
#[inline(always)]
pub fn aes_sysconfig_keyenc(&self) -> AES_SYSCONFIG_KEYENCR {
let bits = ((self.bits >> 11) & 1) != 0;
AES_SYSCONFIG_KEYENCR { bits }
}
#[doc = "Bit 12 - K3 Select"]
#[inline(always)]
pub fn aes_sysconfig_k3(&self) -> AES_SYSCONFIG_K3R {
let bits = ((self.bits >> 12) & 1) != 0;
AES_SYSCONFIG_K3R { bits }
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bit 1 - Soft reset"]
#[inline(always)]
pub fn aes_sysconfig_softreset(&mut self) -> _AES_SYSCONFIG_SOFTRESETW {
_AES_SYSCONFIG_SOFTRESETW { w: self }
}
#[doc = "Bit 5 - DMA Request Data In Enable"]
#[inline(always)]
pub fn aes_sysconfig_dma_req_data_in_en(&mut self) -> _AES_SYSCONFIG_DMA_REQ_DATA_IN_ENW {
_AES_SYSCONFIG_DMA_REQ_DATA_IN_ENW { w: self }
}
#[doc = "Bit 6 - DMA Request Data Out Enable"]
#[inline(always)]
pub fn aes_sysconfig_dma_req_data_out_en(&mut self) -> _AES_SYSCONFIG_DMA_REQ_DATA_OUT_ENW {
_AES_SYSCONFIG_DMA_REQ_DATA_OUT_ENW { w: self }
}
#[doc = "Bit 7 - DMA Request Context In Enable"]
#[inline(always)]
pub fn aes_sysconfig_dma_req_context_in_en(&mut self) -> _AES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENW {
_AES_SYSCONFIG_DMA_REQ_CONTEXT_IN_ENW { w: self }
}
#[doc = "Bit 8 - DMA Request Context Out Enable"]
#[inline(always)]
pub fn aes_sysconfig_dma_req_context_out_en(
&mut self,
) -> _AES_SYSCONFIG_DMA_REQ_CONTEXT_OUT_ENW {
_AES_SYSCONFIG_DMA_REQ_CONTEXT_OUT_ENW { w: self }
}
#[doc = "Bit 9 - Map Context Out on Data Out Enable"]
#[inline(always)]
pub fn aes_sysconfig_map_context_out_on_data_out(
&mut self,
) -> _AES_SYSCONFIG_MAP_CONTEXT_OUT_ON_DATA_OUTW {
_AES_SYSCONFIG_MAP_CONTEXT_OUT_ON_DATA_OUTW { w: self }
}
#[doc = "Bit 11 - Key Encoding"]
#[inline(always)]
pub fn aes_sysconfig_keyenc(&mut self) -> _AES_SYSCONFIG_KEYENCW {
_AES_SYSCONFIG_KEYENCW { w: self }
}
#[doc = "Bit 12 - K3 Select"]
#[inline(always)]
pub fn aes_sysconfig_k3(&mut self) -> _AES_SYSCONFIG_K3W {
_AES_SYSCONFIG_K3W { w: self }
}
}
|
// Copyright 2022 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::io::BufRead;
use std::io::Cursor;
use std::io::Seek;
use std::io::SeekFrom;
use bstr::ByteSlice;
use common_arrow::arrow::bitmap::MutableBitmap;
use common_exception::ErrorCode;
use common_exception::Result;
use common_expression::serialize::read_decimal_with_size;
use common_expression::serialize::uniform_date;
use common_expression::types::array::ArrayColumnBuilder;
use common_expression::types::date::check_date;
use common_expression::types::decimal::Decimal;
use common_expression::types::decimal::DecimalColumnBuilder;
use common_expression::types::decimal::DecimalSize;
use common_expression::types::nullable::NullableColumnBuilder;
use common_expression::types::number::Number;
use common_expression::types::string::StringColumnBuilder;
use common_expression::types::timestamp::check_timestamp;
use common_expression::types::AnyType;
use common_expression::types::NumberColumnBuilder;
use common_expression::with_decimal_type;
use common_expression::with_number_mapped_type;
use common_expression::ColumnBuilder;
use common_io::cursor_ext::BufferReadDateTimeExt;
use common_io::cursor_ext::ReadBytesExt;
use common_io::cursor_ext::ReadCheckPointExt;
use common_io::cursor_ext::ReadNumberExt;
use lexical_core::FromLexical;
use crate::field_decoder::FieldDecoder;
use crate::CommonSettings;
pub trait FieldDecoderRowBased: FieldDecoder {
fn common_settings(&self) -> &CommonSettings;
fn ignore_field_end<R: AsRef<[u8]>>(&self, reader: &mut Cursor<R>) -> bool;
fn match_bytes<R: AsRef<[u8]>>(&self, reader: &mut Cursor<R>, bs: &[u8]) -> bool {
let pos = reader.checkpoint();
if reader.ignore_bytes(bs) && self.ignore_field_end(reader) {
true
} else {
reader.rollback(pos);
false
}
}
fn read_field<R: AsRef<[u8]>>(
&self,
column: &mut ColumnBuilder,
reader: &mut Cursor<R>,
raw: bool,
) -> Result<()> {
match column {
ColumnBuilder::Null { len } => self.read_null(len, reader, raw),
ColumnBuilder::Nullable(c) => self.read_nullable(c, reader, raw),
ColumnBuilder::Boolean(c) => self.read_bool(c, reader, raw),
ColumnBuilder::Number(c) => with_number_mapped_type!(|NUM_TYPE| match c {
NumberColumnBuilder::NUM_TYPE(c) => {
if NUM_TYPE::FLOATING {
self.read_float(c, reader, raw)
} else {
self.read_int(c, reader, raw)
}
}
}),
ColumnBuilder::Decimal(c) => with_decimal_type!(|DECIMAL_TYPE| match c {
DecimalColumnBuilder::DECIMAL_TYPE(c, size) =>
self.read_decimal(c, *size, reader, raw),
}),
ColumnBuilder::Date(c) => self.read_date(c, reader, raw),
ColumnBuilder::Timestamp(c) => self.read_timestamp(c, reader, raw),
ColumnBuilder::String(c) => self.read_string(c, reader, raw),
ColumnBuilder::Array(c) => self.read_array(c, reader, raw),
ColumnBuilder::Map(c) => self.read_map(c, reader, raw),
ColumnBuilder::Tuple(fields) => self.read_tuple(fields, reader, raw),
ColumnBuilder::Variant(c) => self.read_variant(c, reader, raw),
_ => unimplemented!(),
}
}
fn read_bool<R: AsRef<[u8]>>(
&self,
column: &mut MutableBitmap,
reader: &mut Cursor<R>,
_raw: bool,
) -> Result<()> {
if self.match_bytes(reader, &self.common_settings().true_bytes) {
column.push(true);
Ok(())
} else if self.match_bytes(reader, &self.common_settings().false_bytes) {
column.push(false);
Ok(())
} else {
let err_msg = format!(
"Incorrect boolean value, expect {} or {}",
self.common_settings().true_bytes.to_str().unwrap(),
self.common_settings().false_bytes.to_str().unwrap()
);
Err(ErrorCode::BadBytes(err_msg))
}
}
fn read_null<R: AsRef<[u8]>>(
&self,
column_len: &mut usize,
_reader: &mut Cursor<R>,
_raw: bool,
) -> Result<()> {
*column_len += 1;
Ok(())
}
fn read_nullable<R: AsRef<[u8]>>(
&self,
column: &mut NullableColumnBuilder<AnyType>,
reader: &mut Cursor<R>,
raw: bool,
) -> Result<()> {
if reader.eof() {
column.push_null();
} else if self.match_bytes(reader, &self.common_settings().null_bytes)
&& self.ignore_field_end(reader)
{
column.push_null();
return Ok(());
} else {
self.read_field(&mut column.builder, reader, raw)?;
column.validity.push(true);
}
Ok(())
}
fn read_string_inner<R: AsRef<[u8]>>(
&self,
reader: &mut Cursor<R>,
out_buf: &mut Vec<u8>,
raw: bool,
) -> Result<()>;
fn read_int<T, R: AsRef<[u8]>>(
&self,
column: &mut Vec<T>,
reader: &mut Cursor<R>,
_raw: bool,
) -> Result<()>
where
T: Number + From<T::Native>,
T::Native: FromLexical,
{
let v: T::Native = reader.read_int_text()?;
column.push(v.into());
Ok(())
}
fn read_float<T, R: AsRef<[u8]>>(
&self,
column: &mut Vec<T>,
reader: &mut Cursor<R>,
_raw: bool,
) -> Result<()>
where
T: Number + From<T::Native>,
T::Native: FromLexical,
{
let v: T::Native = reader.read_float_text()?;
column.push(v.into());
Ok(())
}
fn read_decimal<R: AsRef<[u8]>, D: Decimal>(
&self,
column: &mut Vec<D>,
size: DecimalSize,
reader: &mut Cursor<R>,
_raw: bool,
) -> Result<()> {
let buf = reader.remaining_slice();
let (n, n_read) = read_decimal_with_size(buf, size, false)?;
column.push(n);
reader.consume(n_read);
Ok(())
}
fn read_string<R: AsRef<[u8]>>(
&self,
column: &mut StringColumnBuilder,
reader: &mut Cursor<R>,
_raw: bool,
) -> Result<()>;
fn read_date<R: AsRef<[u8]>>(
&self,
column: &mut Vec<i32>,
reader: &mut Cursor<R>,
raw: bool,
) -> Result<()> {
let mut buf = Vec::new();
self.read_string_inner(reader, &mut buf, raw)?;
let mut buffer_readr = Cursor::new(&buf);
let date = buffer_readr.read_date_text(&self.common_settings().timezone)?;
let days = uniform_date(date);
check_date(days as i64)?;
column.push(days);
Ok(())
}
fn read_timestamp<R: AsRef<[u8]>>(
&self,
column: &mut Vec<i64>,
reader: &mut Cursor<R>,
raw: bool,
) -> Result<()> {
let mut buf = Vec::new();
self.read_string_inner(reader, &mut buf, raw)?;
let mut buffer_readr = Cursor::new(&buf);
let pos = buffer_readr.position();
let ts_result = buffer_readr.read_num_text_exact();
let ts = match ts_result {
Err(_) => {
buffer_readr
.seek(SeekFrom::Start(pos))
.expect("buffer reader seek must success");
let t = buffer_readr.read_timestamp_text(&self.common_settings().timezone)?;
if !buffer_readr.eof() {
let data = buf.to_str().unwrap_or("not utf8");
let msg = format!(
"fail to deserialize timestamp, unexpected end at pos {} of {}",
buffer_readr.position(),
data
);
return Err(ErrorCode::BadBytes(msg));
}
t.timestamp_micros()
}
Ok(t) => t,
};
check_timestamp(ts)?;
column.push(ts);
Ok(())
}
fn read_variant<R: AsRef<[u8]>>(
&self,
column: &mut StringColumnBuilder,
reader: &mut Cursor<R>,
raw: bool,
) -> Result<()> {
self.read_string_inner(reader, &mut column.data, raw)?;
column.commit_row();
Ok(())
}
fn read_array<R: AsRef<[u8]>>(
&self,
column: &mut ArrayColumnBuilder<AnyType>,
reader: &mut Cursor<R>,
raw: bool,
) -> Result<()>;
fn read_map<R: AsRef<[u8]>>(
&self,
column: &mut ArrayColumnBuilder<AnyType>,
reader: &mut Cursor<R>,
raw: bool,
) -> Result<()>;
fn read_tuple<R: AsRef<[u8]>>(
&self,
fields: &mut Vec<ColumnBuilder>,
reader: &mut Cursor<R>,
raw: bool,
) -> Result<()>;
}
|
use std::{collections::HashMap, convert::Infallible, env, net::SocketAddr};
use axum::{handler::head, response::IntoResponse, Json, Router};
use dotenv::dotenv;
use futures::TryStreamExt;
use hyper::{
service::{make_service_fn, service_fn},
Body, Method, Request, Response, Server, StatusCode,
};
use serde_json::Value;
#[tokio::main]
async fn main() {
dotenv().ok();
// let key = env::var("KEY").unwrap();
// let token = env::var("TOKEN").unwrap();
// let board_id = env::var("BOARD_ID").unwrap();
// let url = format!(
// "https://api.trello.com/1/boards/{}?key={}&token={}",
// board_id, key, token
// );
let addr = SocketAddr::from(([127, 0, 0, 1], 3000));
let app = Router::new().route("/trello-callback", head(webhook_check).post(manage_webhook));
axum::Server::bind(&addr)
.serve(app.into_make_service())
.await
.unwrap();
}
async fn webhook_check() -> StatusCode {
StatusCode::OK
}
async fn manage_webhook(Json(payload): Json<HashMap<String, Value>>) -> StatusCode {
println!("ok ok ok \n{:#?}", payload);
StatusCode::OK
}
|
#[doc = "Reader of register MTLTxQDR"]
pub type R = crate::R<u32, super::MTLTXQDR>;
#[doc = "Writer for register MTLTxQDR"]
pub type W = crate::W<u32, super::MTLTXQDR>;
#[doc = "Register MTLTxQDR `reset()`'s with value 0"]
impl crate::ResetValue for super::MTLTXQDR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `STXSTSF`"]
pub type STXSTSF_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `STXSTSF`"]
pub struct STXSTSF_W<'a> {
w: &'a mut W,
}
impl<'a> STXSTSF_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 & !(0x07 << 20)) | (((value as u32) & 0x07) << 20);
self.w
}
}
#[doc = "Reader of field `PTXQ`"]
pub type PTXQ_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `PTXQ`"]
pub struct PTXQ_W<'a> {
w: &'a mut W,
}
impl<'a> PTXQ_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 & !(0x07 << 16)) | (((value as u32) & 0x07) << 16);
self.w
}
}
#[doc = "Reader of field `TXSTSFSTS`"]
pub type TXSTSFSTS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TXSTSFSTS`"]
pub struct TXSTSFSTS_W<'a> {
w: &'a mut W,
}
impl<'a> TXSTSFSTS_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 `TXQSTS`"]
pub type TXQSTS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TXQSTS`"]
pub struct TXQSTS_W<'a> {
w: &'a mut W,
}
impl<'a> TXQSTS_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 `TWCSTS`"]
pub type TWCSTS_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TWCSTS`"]
pub struct TWCSTS_W<'a> {
w: &'a mut W,
}
impl<'a> TWCSTS_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 `TRCSTS`"]
pub type TRCSTS_R = crate::R<u8, u8>;
#[doc = "Write proxy for field `TRCSTS`"]
pub struct TRCSTS_W<'a> {
w: &'a mut W,
}
impl<'a> TRCSTS_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 & !(0x03 << 1)) | (((value as u32) & 0x03) << 1);
self.w
}
}
#[doc = "Reader of field `TXQPAUSED`"]
pub type TXQPAUSED_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TXQPAUSED`"]
pub struct TXQPAUSED_W<'a> {
w: &'a mut W,
}
impl<'a> TXQPAUSED_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
}
}
impl R {
#[doc = "Bits 20:22 - Number of Status Words in Tx Status FIFO of Queue"]
#[inline(always)]
pub fn stxstsf(&self) -> STXSTSF_R {
STXSTSF_R::new(((self.bits >> 20) & 0x07) as u8)
}
#[doc = "Bits 16:18 - Number of Packets in the Transmit Queue"]
#[inline(always)]
pub fn ptxq(&self) -> PTXQ_R {
PTXQ_R::new(((self.bits >> 16) & 0x07) as u8)
}
#[doc = "Bit 5 - MTL Tx Status FIFO Full Status"]
#[inline(always)]
pub fn txstsfsts(&self) -> TXSTSFSTS_R {
TXSTSFSTS_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 4 - MTL Tx Queue Not Empty Status"]
#[inline(always)]
pub fn txqsts(&self) -> TXQSTS_R {
TXQSTS_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 3 - MTL Tx Queue Write Controller Status"]
#[inline(always)]
pub fn twcsts(&self) -> TWCSTS_R {
TWCSTS_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bits 1:2 - MTL Tx Queue Read Controller Status"]
#[inline(always)]
pub fn trcsts(&self) -> TRCSTS_R {
TRCSTS_R::new(((self.bits >> 1) & 0x03) as u8)
}
#[doc = "Bit 0 - Transmit Queue in Pause"]
#[inline(always)]
pub fn txqpaused(&self) -> TXQPAUSED_R {
TXQPAUSED_R::new((self.bits & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 20:22 - Number of Status Words in Tx Status FIFO of Queue"]
#[inline(always)]
pub fn stxstsf(&mut self) -> STXSTSF_W {
STXSTSF_W { w: self }
}
#[doc = "Bits 16:18 - Number of Packets in the Transmit Queue"]
#[inline(always)]
pub fn ptxq(&mut self) -> PTXQ_W {
PTXQ_W { w: self }
}
#[doc = "Bit 5 - MTL Tx Status FIFO Full Status"]
#[inline(always)]
pub fn txstsfsts(&mut self) -> TXSTSFSTS_W {
TXSTSFSTS_W { w: self }
}
#[doc = "Bit 4 - MTL Tx Queue Not Empty Status"]
#[inline(always)]
pub fn txqsts(&mut self) -> TXQSTS_W {
TXQSTS_W { w: self }
}
#[doc = "Bit 3 - MTL Tx Queue Write Controller Status"]
#[inline(always)]
pub fn twcsts(&mut self) -> TWCSTS_W {
TWCSTS_W { w: self }
}
#[doc = "Bits 1:2 - MTL Tx Queue Read Controller Status"]
#[inline(always)]
pub fn trcsts(&mut self) -> TRCSTS_W {
TRCSTS_W { w: self }
}
#[doc = "Bit 0 - Transmit Queue in Pause"]
#[inline(always)]
pub fn txqpaused(&mut self) -> TXQPAUSED_W {
TXQPAUSED_W { w: self }
}
}
|
pub type IFeed = *mut ::core::ffi::c_void;
pub type IFeed2 = *mut ::core::ffi::c_void;
pub type IFeedEnclosure = *mut ::core::ffi::c_void;
pub type IFeedEvents = *mut ::core::ffi::c_void;
pub type IFeedFolder = *mut ::core::ffi::c_void;
pub type IFeedFolderEvents = *mut ::core::ffi::c_void;
pub type IFeedItem = *mut ::core::ffi::c_void;
pub type IFeedItem2 = *mut ::core::ffi::c_void;
pub type IFeedsEnum = *mut ::core::ffi::c_void;
pub type IFeedsManager = *mut ::core::ffi::c_void;
pub type IWMPAudioRenderConfig = *mut ::core::ffi::c_void;
pub type IWMPCdrom = *mut ::core::ffi::c_void;
pub type IWMPCdromBurn = *mut ::core::ffi::c_void;
pub type IWMPCdromCollection = *mut ::core::ffi::c_void;
pub type IWMPCdromRip = *mut ::core::ffi::c_void;
pub type IWMPClosedCaption = *mut ::core::ffi::c_void;
pub type IWMPClosedCaption2 = *mut ::core::ffi::c_void;
pub type IWMPContentContainer = *mut ::core::ffi::c_void;
pub type IWMPContentContainerList = *mut ::core::ffi::c_void;
pub type IWMPContentPartner = *mut ::core::ffi::c_void;
pub type IWMPContentPartnerCallback = *mut ::core::ffi::c_void;
pub type IWMPControls = *mut ::core::ffi::c_void;
pub type IWMPControls2 = *mut ::core::ffi::c_void;
pub type IWMPControls3 = *mut ::core::ffi::c_void;
pub type IWMPConvert = *mut ::core::ffi::c_void;
pub type IWMPCore = *mut ::core::ffi::c_void;
pub type IWMPCore2 = *mut ::core::ffi::c_void;
pub type IWMPCore3 = *mut ::core::ffi::c_void;
pub type IWMPDVD = *mut ::core::ffi::c_void;
pub type IWMPDownloadCollection = *mut ::core::ffi::c_void;
pub type IWMPDownloadItem = *mut ::core::ffi::c_void;
pub type IWMPDownloadItem2 = *mut ::core::ffi::c_void;
pub type IWMPDownloadManager = *mut ::core::ffi::c_void;
pub type IWMPEffects = *mut ::core::ffi::c_void;
pub type IWMPEffects2 = *mut ::core::ffi::c_void;
pub type IWMPError = *mut ::core::ffi::c_void;
pub type IWMPErrorItem = *mut ::core::ffi::c_void;
pub type IWMPErrorItem2 = *mut ::core::ffi::c_void;
pub type IWMPEvents = *mut ::core::ffi::c_void;
pub type IWMPEvents2 = *mut ::core::ffi::c_void;
pub type IWMPEvents3 = *mut ::core::ffi::c_void;
pub type IWMPEvents4 = *mut ::core::ffi::c_void;
pub type IWMPFolderMonitorServices = *mut ::core::ffi::c_void;
pub type IWMPGraphCreation = *mut ::core::ffi::c_void;
pub type IWMPLibrary = *mut ::core::ffi::c_void;
pub type IWMPLibrary2 = *mut ::core::ffi::c_void;
pub type IWMPLibraryServices = *mut ::core::ffi::c_void;
pub type IWMPLibrarySharingServices = *mut ::core::ffi::c_void;
pub type IWMPMedia = *mut ::core::ffi::c_void;
pub type IWMPMedia2 = *mut ::core::ffi::c_void;
pub type IWMPMedia3 = *mut ::core::ffi::c_void;
pub type IWMPMediaCollection = *mut ::core::ffi::c_void;
pub type IWMPMediaCollection2 = *mut ::core::ffi::c_void;
pub type IWMPMediaPluginRegistrar = *mut ::core::ffi::c_void;
pub type IWMPMetadataPicture = *mut ::core::ffi::c_void;
pub type IWMPMetadataText = *mut ::core::ffi::c_void;
pub type IWMPNetwork = *mut ::core::ffi::c_void;
pub type IWMPNodeRealEstate = *mut ::core::ffi::c_void;
pub type IWMPNodeRealEstateHost = *mut ::core::ffi::c_void;
pub type IWMPNodeWindowed = *mut ::core::ffi::c_void;
pub type IWMPNodeWindowedHost = *mut ::core::ffi::c_void;
pub type IWMPNodeWindowless = *mut ::core::ffi::c_void;
pub type IWMPNodeWindowlessHost = *mut ::core::ffi::c_void;
pub type IWMPPlayer = *mut ::core::ffi::c_void;
pub type IWMPPlayer2 = *mut ::core::ffi::c_void;
pub type IWMPPlayer3 = *mut ::core::ffi::c_void;
pub type IWMPPlayer4 = *mut ::core::ffi::c_void;
pub type IWMPPlayerApplication = *mut ::core::ffi::c_void;
pub type IWMPPlayerServices = *mut ::core::ffi::c_void;
pub type IWMPPlayerServices2 = *mut ::core::ffi::c_void;
pub type IWMPPlaylist = *mut ::core::ffi::c_void;
pub type IWMPPlaylistArray = *mut ::core::ffi::c_void;
pub type IWMPPlaylistCollection = *mut ::core::ffi::c_void;
pub type IWMPPlugin = *mut ::core::ffi::c_void;
pub type IWMPPluginEnable = *mut ::core::ffi::c_void;
pub type IWMPPluginUI = *mut ::core::ffi::c_void;
pub type IWMPQuery = *mut ::core::ffi::c_void;
pub type IWMPRemoteMediaServices = *mut ::core::ffi::c_void;
pub type IWMPRenderConfig = *mut ::core::ffi::c_void;
pub type IWMPServices = *mut ::core::ffi::c_void;
pub type IWMPSettings = *mut ::core::ffi::c_void;
pub type IWMPSettings2 = *mut ::core::ffi::c_void;
pub type IWMPSkinManager = *mut ::core::ffi::c_void;
pub type IWMPStringCollection = *mut ::core::ffi::c_void;
pub type IWMPStringCollection2 = *mut ::core::ffi::c_void;
pub type IWMPSubscriptionService = *mut ::core::ffi::c_void;
pub type IWMPSubscriptionService2 = *mut ::core::ffi::c_void;
pub type IWMPSubscriptionServiceCallback = *mut ::core::ffi::c_void;
pub type IWMPSyncDevice = *mut ::core::ffi::c_void;
pub type IWMPSyncDevice2 = *mut ::core::ffi::c_void;
pub type IWMPSyncDevice3 = *mut ::core::ffi::c_void;
pub type IWMPSyncServices = *mut ::core::ffi::c_void;
pub type IWMPTranscodePolicy = *mut ::core::ffi::c_void;
pub type IWMPUserEventSink = *mut ::core::ffi::c_void;
pub type IWMPVideoRenderConfig = *mut ::core::ffi::c_void;
pub type IWMPWindowMessageSink = *mut ::core::ffi::c_void;
pub type IXFeed = *mut ::core::ffi::c_void;
pub type IXFeed2 = *mut ::core::ffi::c_void;
pub type IXFeedEnclosure = *mut ::core::ffi::c_void;
pub type IXFeedEvents = *mut ::core::ffi::c_void;
pub type IXFeedFolder = *mut ::core::ffi::c_void;
pub type IXFeedFolderEvents = *mut ::core::ffi::c_void;
pub type IXFeedItem = *mut ::core::ffi::c_void;
pub type IXFeedItem2 = *mut ::core::ffi::c_void;
pub type IXFeedsEnum = *mut ::core::ffi::c_void;
pub type IXFeedsManager = *mut ::core::ffi::c_void;
pub type _WMPOCXEvents = *mut ::core::ffi::c_void;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const CLSID_WMPMediaPluginRegistrar: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x5569e7f5_424b_4b93_89ca_79d17924689a);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const CLSID_WMPSkinManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xb2a7fd52_301f_4348_b93a_638c6de49229);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const CLSID_XFeedsManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xfe6b11c3_c72e_4061_86c6_9d163121f229);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_DELTA: u32 = 50u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_AsyncDownload: u32 = 24579u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_CancelAsyncDownload: u32 = 24580u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_DownloadMimeType: u32 = 24586u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_DownloadStatus: u32 = 24581u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_DownloadUrl: u32 = 24585u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_LastDownloadError: u32 = 24582u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_Length: u32 = 24578u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_LocalPath: u32 = 24583u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_Parent: u32 = 24584u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_RemoveFile: u32 = 24587u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_SetFile: u32 = 24588u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_Type: u32 = 24577u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDENCLOSURE_Url: u32 = 24576u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDEVENTS_Error: u32 = 32768u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDEVENTS_FeedDeleted: u32 = 32769u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDEVENTS_FeedDownloadCompleted: u32 = 32774u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDEVENTS_FeedDownloading: u32 = 32773u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDEVENTS_FeedItemCountChanged: u32 = 32775u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDEVENTS_FeedMoved: u32 = 32772u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDEVENTS_FeedRenamed: u32 = 32770u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDEVENTS_FeedUrlChanged: u32 = 32771u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_Error: u32 = 28672u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FeedAdded: u32 = 28679u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FeedDeleted: u32 = 28680u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FeedDownloadCompleted: u32 = 28686u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FeedDownloading: u32 = 28685u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FeedItemCountChanged: u32 = 28687u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FeedMovedFrom: u32 = 28683u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FeedMovedTo: u32 = 28684u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FeedRenamed: u32 = 28681u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FeedUrlChanged: u32 = 28682u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FolderAdded: u32 = 28673u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FolderDeleted: u32 = 28674u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FolderItemCountChanged: u32 = 28678u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FolderMovedFrom: u32 = 28676u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FolderMovedTo: u32 = 28677u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDEREVENTS_FolderRenamed: u32 = 28675u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_CreateFeed: u32 = 12290u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_CreateSubfolder: u32 = 12291u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_Delete: u32 = 12296u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_ExistsFeed: u32 = 12292u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_ExistsSubfolder: u32 = 12294u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_Feeds: u32 = 12288u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_GetFeed: u32 = 12293u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_GetSubfolder: u32 = 12295u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_GetWatcher: u32 = 12305u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_IsRoot: u32 = 12302u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_Move: u32 = 12300u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_Name: u32 = 12297u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_Parent: u32 = 12301u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_Path: u32 = 12299u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_Rename: u32 = 12298u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_Subfolders: u32 = 12289u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_TotalItemCount: u32 = 12304u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDFOLDER_TotalUnreadItemCount: u32 = 12303u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Author: u32 = 20487u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Comments: u32 = 20486u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Delete: u32 = 20492u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Description: u32 = 20484u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_DownloadUrl: u32 = 20493u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_EffectiveId: u32 = 20496u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Enclosure: u32 = 20488u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Guid: u32 = 20483u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_IsRead: u32 = 20489u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_LastDownloadTime: u32 = 20494u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Link: u32 = 20482u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_LocalId: u32 = 20490u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Modified: u32 = 20495u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Parent: u32 = 20491u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_PubDate: u32 = 20485u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Title: u32 = 20481u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDITEM_Xml: u32 = 20480u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDSENUM_Count: u32 = 8192u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDSENUM_Item: u32 = 8193u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_AsyncSyncAll: u32 = 4108u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_BackgroundSync: u32 = 4105u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_BackgroundSyncStatus: u32 = 4106u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_DefaultInterval: u32 = 4107u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_DeleteFeed: u32 = 4102u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_DeleteFolder: u32 = 4103u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_ExistsFeed: u32 = 4098u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_ExistsFolder: u32 = 4100u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_GetFeed: u32 = 4099u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_GetFeedByUrl: u32 = 4104u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_GetFolder: u32 = 4101u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_IsSubscribed: u32 = 4097u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_ItemCountLimit: u32 = 4110u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_Normalize: u32 = 4109u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEEDS_RootFolder: u32 = 4096u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_AsyncDownload: u32 = 16395u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_CancelAsyncDownload: u32 = 16396u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_ClearCredentials: u32 = 16428u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Copyright: u32 = 16411u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Delete: u32 = 16393u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Description: u32 = 16404u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Download: u32 = 16394u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_DownloadEnclosuresAutomatically: u32 = 16412u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_DownloadStatus: u32 = 16413u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_DownloadUrl: u32 = 16416u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_GetItem: u32 = 16402u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_GetItemByEffectiveId: u32 = 16423u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_GetWatcher: u32 = 16419u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Image: u32 = 16406u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Interval: u32 = 16397u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_IsList: u32 = 16417u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_ItemCount: u32 = 16421u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Items: u32 = 16401u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Language: u32 = 16410u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_LastBuildDate: u32 = 16407u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_LastDownloadError: u32 = 16414u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_LastDownloadTime: u32 = 16399u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_LastItemDownloadTime: u32 = 16424u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_LastWriteTime: u32 = 16392u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Link: u32 = 16405u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_LocalEnclosurePath: u32 = 16400u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_LocalId: u32 = 16388u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_MarkAllItemsRead: u32 = 16418u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_MaxItemCount: u32 = 16422u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Merge: u32 = 16415u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Move: u32 = 16390u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Name: u32 = 16385u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Parent: u32 = 16391u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Password: u32 = 16426u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Path: u32 = 16389u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_PubDate: u32 = 16408u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Rename: u32 = 16386u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_SetCredentials: u32 = 16427u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_SyncSetting: u32 = 16398u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Title: u32 = 16403u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Ttl: u32 = 16409u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_UnreadItemCount: u32 = 16420u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Url: u32 = 16387u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Username: u32 = 16425u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_FEED_Xml: u32 = 16384u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROMCOLLECTION_BASE: u32 = 300u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROMCOLLECTION_COUNT: u32 = 301u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROMCOLLECTION_GETBYDRIVESPECIFIER: u32 = 303u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROMCOLLECTION_ITEM: u32 = 302u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROMCOLLECTION_STARTMONITORINGCDROMS: u32 = 304u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROMCOLLECTION_STOPMONITORINGCDROMS: u32 = 305u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROM_BASE: u32 = 250u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROM_DRIVESPECIFIER: u32 = 251u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROM_EJECT: u32 = 253u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCDROM_PLAYLIST: u32 = 252u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION2_GETLANGCOUNT: u32 = 955u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION2_GETLANGID: u32 = 957u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION2_GETLANGNAME: u32 = 956u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION2_GETSTYLECOUNT: u32 = 958u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION2_GETSTYLENAME: u32 = 959u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION_BASE: u32 = 950u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION_CAPTIONINGID: u32 = 954u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION_SAMIFILENAME: u32 = 953u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION_SAMILANG: u32 = 952u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCLOSEDCAPTION_SAMISTYLE: u32 = 951u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS2_STEP: u32 = 64u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS3_AUDIOLANGUAGECOUNT: u32 = 65u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS3_CURRENTAUDIOLANGUAGE: u32 = 68u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS3_CURRENTAUDIOLANGUAGEINDEX: u32 = 69u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS3_CURRENTPOSITIONTIMECODE: u32 = 71u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS3_GETAUDIOLANGUAGEDESC: u32 = 67u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS3_GETAUDIOLANGUAGEID: u32 = 66u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS3_GETLANGUAGENAME: u32 = 70u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLSFAKE_TIMECOMPRESSION: u32 = 72u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_BASE: u32 = 50u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_CURRENTITEM: u32 = 60u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_CURRENTMARKER: u32 = 61u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_CURRENTPOSITION: u32 = 56u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_CURRENTPOSITIONSTRING: u32 = 57u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_FASTFORWARD: u32 = 54u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_FASTREVERSE: u32 = 55u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_ISAVAILABLE: u32 = 62u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_NEXT: u32 = 58u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_PAUSE: u32 = 53u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_PLAY: u32 = 51u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_PLAYITEM: u32 = 63u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_PREVIOUS: u32 = 59u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCONTROLS_STOP: u32 = 52u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE2_BASE: u32 = 39u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE2_DVD: u32 = 40u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE3_NEWMEDIA: u32 = 42u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE3_NEWPLAYLIST: u32 = 41u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_AUDIOLANGUAGECHANGE: u32 = 5102u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_BUFFERING: u32 = 5402u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_CDROMMEDIACHANGE: u32 = 5701u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_CURRENTITEMCHANGE: u32 = 5806u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_CURRENTMEDIAITEMAVAILABLE: u32 = 5803u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_CURRENTPLAYLISTCHANGE: u32 = 5804u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_CURRENTPLAYLISTITEMAVAILABLE: u32 = 5805u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_DISCONNECT: u32 = 5401u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_DOMAINCHANGE: u32 = 5822u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_DURATIONUNITCHANGE: u32 = 5204u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_ENDOFSTREAM: u32 = 5201u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_ERROR: u32 = 5501u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MARKERHIT: u32 = 5203u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACHANGE: u32 = 5802u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONATTRIBUTESTRINGADDED: u32 = 5808u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONATTRIBUTESTRINGCHANGED: u32 = 5820u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONATTRIBUTESTRINGREMOVED: u32 = 5809u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONCHANGE: u32 = 5807u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONCONTENTSCANADDEDITEM: u32 = 5813u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONCONTENTSCANPROGRESS: u32 = 5814u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONMEDIAADDED: u32 = 5825u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONMEDIAREMOVED: u32 = 5826u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONSEARCHCOMPLETE: u32 = 5817u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONSEARCHFOUNDITEM: u32 = 5815u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONSEARCHPROGRESS: u32 = 5816u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MEDIAERROR: u32 = 5821u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_MODECHANGE: u32 = 5819u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_NEWSTREAM: u32 = 5403u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_OPENPLAYLISTSWITCH: u32 = 5823u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_OPENSTATECHANGE: u32 = 5001u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_PLAYLISTCHANGE: u32 = 5801u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONCHANGE: u32 = 5810u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONPLAYLISTADDED: u32 = 5811u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONPLAYLISTREMOVED: u32 = 5812u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONPLAYLISTSETASDELETED: u32 = 5818u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_PLAYSTATECHANGE: u32 = 5101u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_POSITIONCHANGE: u32 = 5202u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_SCRIPTCOMMAND: u32 = 5301u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_STATUSCHANGE: u32 = 5002u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_STRINGCOLLECTIONCHANGE: u32 = 5824u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCOREEVENT_WARNING: u32 = 5601u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_BASE: u32 = 0u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_CDROMCOLLECTION: u32 = 14u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_CLOSE: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_CLOSEDCAPTION: u32 = 15u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_CONTROLS: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_CURRENTMEDIA: u32 = 6u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_CURRENTPLAYLIST: u32 = 13u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_ERROR: u32 = 17u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_ISONLINE: u32 = 16u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_LAST: u32 = 18u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_LAUNCHURL: u32 = 12u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_MAX: u32 = 1454u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_MEDIACOLLECTION: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_MIN: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_NETWORK: u32 = 7u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_OPENSTATE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_PLAYLISTCOLLECTION: u32 = 9u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_PLAYSTATE: u32 = 10u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_SETTINGS: u32 = 5u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_STATUS: u32 = 18u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_URL: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPCORE_VERSIONINFO: u32 = 11u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADCOLLECTION_BASE: u32 = 1200u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADCOLLECTION_CLEAR: u32 = 1206u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADCOLLECTION_COUNT: u32 = 1202u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADCOLLECTION_ID: u32 = 1201u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADCOLLECTION_ITEM: u32 = 1203u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADCOLLECTION_REMOVEITEM: u32 = 1205u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADCOLLECTION_STARTDOWNLOAD: u32 = 1204u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM2_BASE: u32 = 1300u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM2_GETITEMINFO: u32 = 1301u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM_BASE: u32 = 1250u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM_CANCEL: u32 = 1258u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM_DOWNLOADSTATE: u32 = 1255u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM_PAUSE: u32 = 1256u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM_PROGRESS: u32 = 1254u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM_RESUME: u32 = 1257u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM_SIZE: u32 = 1252u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM_SOURCEURL: u32 = 1251u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADITEM_TYPE: u32 = 1253u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADMANAGER_BASE: u32 = 1150u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADMANAGER_CREATEDOWNLOADCOLLECTION: u32 = 1152u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDOWNLOADMANAGER_GETDOWNLOADCOLLECTION: u32 = 1151u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDVD_BACK: u32 = 1005u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDVD_BASE: u32 = 1000u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDVD_DOMAIN: u32 = 1002u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDVD_ISAVAILABLE: u32 = 1001u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDVD_RESUME: u32 = 1006u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDVD_TITLEMENU: u32 = 1004u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPDVD_TOPMENU: u32 = 1003u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERRORITEM2_CONDITION: u32 = 906u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERRORITEM_BASE: u32 = 900u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERRORITEM_CUSTOMURL: u32 = 905u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERRORITEM_ERRORCODE: u32 = 901u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERRORITEM_ERRORCONTEXT: u32 = 903u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERRORITEM_ERRORDESCRIPTION: u32 = 902u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERRORITEM_REMEDY: u32 = 904u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERROR_BASE: u32 = 850u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERROR_CLEARERRORQUEUE: u32 = 851u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERROR_ERRORCOUNT: u32 = 852u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERROR_ITEM: u32 = 853u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPERROR_WEBHELP: u32 = 854u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA2_ERROR: u32 = 768u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA3_GETATTRIBUTECOUNTBYTYPE: u32 = 769u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA3_GETITEMINFOBYTYPE: u32 = 770u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION2_BASE: u32 = 1400u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION2_CREATEQUERY: u32 = 1401u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION2_GETBYATTRANDMEDIATYPE: u32 = 1404u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION2_GETPLAYLISTBYQUERY: u32 = 1402u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION2_GETSTRINGCOLLBYQUERY: u32 = 1403u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_ADD: u32 = 452u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_BASE: u32 = 450u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_FREEZECOLLECTIONCHANGE: u32 = 474u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_GETALL: u32 = 453u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_GETATTRIBUTESTRINGCOLLECTION: u32 = 461u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_GETBYALBUM: u32 = 457u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_GETBYATTRIBUTE: u32 = 458u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_GETBYAUTHOR: u32 = 456u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_GETBYGENRE: u32 = 455u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_GETBYNAME: u32 = 454u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_GETBYQUERYDESCRIPTION: u32 = 473u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_GETMEDIAATOM: u32 = 470u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_ISDELETED: u32 = 472u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_NEWQUERY: u32 = 462u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_POSTCOLLECTIONCHANGE: u32 = 476u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_REMOVE: u32 = 459u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_SETDELETED: u32 = 471u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_STARTCONTENTSCAN: u32 = 465u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_STARTMONITORING: u32 = 463u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_STARTSEARCH: u32 = 467u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_STOPCONTENTSCAN: u32 = 466u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_STOPMONITORING: u32 = 464u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_STOPSEARCH: u32 = 468u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_UNFREEZECOLLECTIONCHANGE: u32 = 475u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIACOLLECTION_UPDATEMETADATA: u32 = 469u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_ATTRIBUTECOUNT: u32 = 759u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_BASE: u32 = 750u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_DURATION: u32 = 757u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_DURATIONSTRING: u32 = 758u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_GETATTRIBUTENAME: u32 = 760u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_GETITEMINFO: u32 = 761u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_GETITEMINFOBYATOM: u32 = 765u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_GETMARKERNAME: u32 = 756u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_GETMARKERTIME: u32 = 755u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_IMAGESOURCEHEIGHT: u32 = 753u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_IMAGESOURCEWIDTH: u32 = 752u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_ISIDENTICAL: u32 = 763u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_ISMEMBEROF: u32 = 766u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_ISREADONLYITEM: u32 = 767u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_MARKERCOUNT: u32 = 754u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_NAME: u32 = 764u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_SETITEMINFO: u32 = 762u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMEDIA_SOURCEURL: u32 = 751u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMETADATA_BASE: u32 = 1050u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMETADATA_PICTURE_DESCRIPTION: u32 = 1053u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMETADATA_PICTURE_MIMETYPE: u32 = 1051u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMETADATA_PICTURE_PICTURETYPE: u32 = 1052u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMETADATA_PICTURE_URL: u32 = 1054u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMETADATA_TEXT_DESCRIPTION: u32 = 1056u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPMETADATA_TEXT_TEXT: u32 = 1055u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_BANDWIDTH: u32 = 801u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_BASE: u32 = 800u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_BITRATE: u32 = 812u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_BUFFERINGCOUNT: u32 = 807u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_BUFFERINGPROGRESS: u32 = 808u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_BUFFERINGTIME: u32 = 809u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_DOWNLOADPROGRESS: u32 = 824u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_ENCODEDFRAMERATE: u32 = 825u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_FRAMERATE: u32 = 810u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_FRAMESSKIPPED: u32 = 826u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_GETPROXYBYPASSFORLOCAL: u32 = 821u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_GETPROXYEXCEPTIONLIST: u32 = 819u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_GETPROXYNAME: u32 = 815u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_GETPROXYPORT: u32 = 817u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_GETPROXYSETTINGS: u32 = 813u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_LOSTPACKETS: u32 = 805u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_MAXBANDWIDTH: u32 = 823u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_MAXBITRATE: u32 = 811u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_RECEIVEDPACKETS: u32 = 804u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_RECEPTIONQUALITY: u32 = 806u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_RECOVEREDPACKETS: u32 = 802u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_SETPROXYBYPASSFORLOCAL: u32 = 822u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_SETPROXYEXCEPTIONLIST: u32 = 820u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_SETPROXYNAME: u32 = 816u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_SETPROXYPORT: u32 = 818u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_SETPROXYSETTINGS: u32 = 814u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPNETWORK_SOURCEPROTOCOL: u32 = 803u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX2_BASE: u32 = 23u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX2_STRETCHTOFIT: u32 = 24u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX2_WINDOWLESSVIDEO: u32 = 25u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX4_ISREMOTE: u32 = 26u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX4_OPENPLAYER: u32 = 28u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX4_PLAYERAPPLICATION: u32 = 27u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_CDROMBURNERROR: u32 = 6523u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_CDROMBURNMEDIAERROR: u32 = 6522u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_CDROMBURNSTATECHANGE: u32 = 6521u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_CDROMRIPMEDIAERROR: u32 = 6520u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_CDROMRIPSTATECHANGE: u32 = 6519u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_CLICK: u32 = 6505u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_CREATEPARTNERSHIPCOMPLETE: u32 = 6518u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_DEVICECONNECT: u32 = 6513u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_DEVICEDISCONNECT: u32 = 6514u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_DEVICEESTIMATION: u32 = 6527u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_DEVICESTATUSCHANGE: u32 = 6515u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_DEVICESYNCERROR: u32 = 6517u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_DEVICESYNCSTATECHANGE: u32 = 6516u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_DOUBLECLICK: u32 = 6506u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_FOLDERSCANSTATECHANGE: u32 = 6526u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_KEYDOWN: u32 = 6507u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_KEYPRESS: u32 = 6508u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_KEYUP: u32 = 6509u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_LIBRARYCONNECT: u32 = 6524u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_LIBRARYDISCONNECT: u32 = 6525u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_MOUSEDOWN: u32 = 6510u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_MOUSEMOVE: u32 = 6511u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_MOUSEUP: u32 = 6512u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_PLAYERDOCKEDSTATECHANGE: u32 = 6503u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_PLAYERRECONNECT: u32 = 6504u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_SWITCHEDTOCONTROL: u32 = 6502u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCXEVENT_SWITCHEDTOPLAYERAPPLICATION: u32 = 6501u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX_BASE: u32 = 18u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX_ENABLECONTEXTMENU: u32 = 22u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX_ENABLED: u32 = 19u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX_FULLSCREEN: u32 = 21u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX_LAST: u32 = 23u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX_TRANSPARENTATSTART: u32 = 20u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPOCX_UIMODE: u32 = 23u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYERAPP_BASE: u32 = 1100u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYERAPP_HASDISPLAY: u32 = 1104u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYERAPP_PLAYERDOCKED: u32 = 1103u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYERAPP_REMOTESTATUS: u32 = 1105u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYERAPP_SWITCHTOCONTROL: u32 = 1102u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYERAPP_SWITCHTOPLAYERAPPLICATION: u32 = 1101u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTARRAY_BASE: u32 = 500u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTARRAY_COUNT: u32 = 501u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTARRAY_ITEM: u32 = 502u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_BASE: u32 = 550u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_GETALL: u32 = 553u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_GETBYNAME: u32 = 554u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_GETBYQUERYDESCRIPTION: u32 = 555u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_IMPORTPLAYLIST: u32 = 562u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_ISDELETED: u32 = 561u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_NEWPLAYLIST: u32 = 552u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_NEWQUERY: u32 = 557u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_REMOVE: u32 = 556u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_SETDELETED: u32 = 560u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_STARTMONITORING: u32 = 558u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLISTCOLLECTION_STOPMONITORING: u32 = 559u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_APPENDITEM: u32 = 207u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_ATTRIBUTECOUNT: u32 = 210u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_ATTRIBUTENAME: u32 = 211u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_BASE: u32 = 200u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_CLEAR: u32 = 205u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_COUNT: u32 = 201u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_GETITEMINFO: u32 = 203u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_INSERTITEM: u32 = 206u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_ISIDENTICAL: u32 = 213u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_ITEM: u32 = 212u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_MOVEITEM: u32 = 209u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_NAME: u32 = 202u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_REMOVEITEM: u32 = 208u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPPLAYLIST_SETITEMINFO: u32 = 204u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPQUERY_ADDCONDITION: u32 = 1351u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPQUERY_BASE: u32 = 1350u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPQUERY_BEGINNEXTGROUP: u32 = 1352u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS2_DEFAULTAUDIOLANGUAGE: u32 = 114u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS2_LIBRARYACCESSRIGHTS: u32 = 115u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS2_REQUESTLIBRARYACCESSRIGHTS: u32 = 116u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_AUTOSTART: u32 = 101u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_BALANCE: u32 = 102u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_BASE: u32 = 100u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_BASEURL: u32 = 108u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_DEFAULTFRAME: u32 = 109u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_ENABLEERRORDIALOGS: u32 = 112u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_GETMODE: u32 = 110u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_INVOKEURLS: u32 = 103u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_ISAVAILABLE: u32 = 113u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_MUTE: u32 = 104u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_PLAYCOUNT: u32 = 105u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_RATE: u32 = 106u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_SETMODE: u32 = 111u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSETTINGS_VOLUME: u32 = 107u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSTRINGCOLLECTION2_BASE: u32 = 1450u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSTRINGCOLLECTION2_GETATTRCOUNTBYTYPE: u32 = 1453u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSTRINGCOLLECTION2_GETITEMINFO: u32 = 1452u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSTRINGCOLLECTION2_GETITEMINFOBYTYPE: u32 = 1454u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSTRINGCOLLECTION2_ISIDENTICAL: u32 = 1451u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSTRINGCOLLECTION_BASE: u32 = 400u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSTRINGCOLLECTION_COUNT: u32 = 401u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const DISPID_WMPSTRINGCOLLECTION_ITEM: u32 = 402u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const EFFECT2_FULLSCREENEXCLUSIVE: u32 = 16u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const EFFECT_CANGOFULLSCREEN: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const EFFECT_HASPROPERTYPAGE: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const EFFECT_VARIABLEFREQSTEP: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const EFFECT_WINDOWEDONLY: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FeedFolderWatcher: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x281001ed_7765_4cb0_84af_e9b387af01ff);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FeedWatcher: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x18a6737b_f433_4687_89bc_a1b4dfb9f123);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FeedsManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xfaeb54c4_f66f_4806_83a0_805299f5e3ad);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const IOCTL_WMP_DEVICE_CAN_SYNC: u32 = 844123479u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const IOCTL_WMP_METADATA_ROUND_TRIP: u32 = 827346263u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_ALL_MEDIASENDTO: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("MediaSendTo");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_ALL_PLAYLISTSENDTO: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("PlaylistSendTo");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_FLAGS_ACCEPTSMEDIA: u32 = 268435456u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_FLAGS_ACCEPTSPLAYLISTS: u32 = 134217728u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_FLAGS_HASPRESETS: u32 = 67108864u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_FLAGS_HASPROPERTYPAGE: u32 = 2147483648u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_FLAGS_HIDDEN: u32 = 33554432u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_FLAGS_INSTALLAUTORUN: u32 = 1073741824u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_FLAGS_LAUNCHPROPERTYPAGE: u32 = 536870912u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_INSTALLREGKEY: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("Software\\Microsoft\\MediaPlayer\\UIPlugins");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_INSTALLREGKEY_CAPABILITIES: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("Capabilities");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_INSTALLREGKEY_DESCRIPTION: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("Description");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_INSTALLREGKEY_FRIENDLYNAME: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("FriendlyName");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_INSTALLREGKEY_UNINSTALL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("UninstallPath");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_MISC_CURRENTPRESET: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CurrentPreset");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_MISC_PRESETCOUNT: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("PresetCount");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_MISC_PRESETNAMES: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("PresetNames");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_MISC_QUERYDESTROY: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("QueryDestroy");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_SEPARATEWINDOW_DEFAULTHEIGHT: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("DefaultHeight");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_SEPARATEWINDOW_DEFAULTWIDTH: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("DefaultWidth");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_SEPARATEWINDOW_MAXHEIGHT: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("MaxHeight");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_SEPARATEWINDOW_MAXWIDTH: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("MaxWidth");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_SEPARATEWINDOW_MINHEIGHT: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("MinHeight");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_SEPARATEWINDOW_MINWIDTH: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("MinWidth");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_SEPARATEWINDOW_RESIZABLE: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("Resizable");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_TYPE_BACKGROUND: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_TYPE_DISPLAYAREA: u32 = 3u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_TYPE_METADATAAREA: u32 = 5u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_TYPE_SEPARATEWINDOW: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const PLUGIN_TYPE_SETTINGSAREA: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SA_BUFFER_SIZE: u32 = 1024u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_CAP_ALLOWCDBURN: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_CAP_ALLOWPDATRANSFER: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_CAP_ALLOWPLAY: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_CAP_ALTLOGIN: u32 = 128u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_CAP_BACKGROUNDPROCESSING: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_CAP_DEVICEAVAILABLE: u32 = 16u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_CAP_IS_CONTENTPARTNER: u32 = 64u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_CAP_PREPAREFORSYNC: u32 = 32u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_CAP_UILESSMODE_ALLOWPLAY: u32 = 256u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const SUBSCRIPTION_V1_CAPS: u32 = 15u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPCOREEVENT_BASE: u32 = 5000u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPCOREEVENT_CDROM_BASE: u32 = 5700u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPCOREEVENT_CONTENT_BASE: u32 = 5300u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPCOREEVENT_CONTROL_BASE: u32 = 5100u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPCOREEVENT_ERROR_BASE: u32 = 5500u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPCOREEVENT_NETWORK_BASE: u32 = 5400u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPCOREEVENT_PLAYLIST_BASE: u32 = 5800u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPCOREEVENT_SEEK_BASE: u32 = 5200u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPCOREEVENT_WARNING_BASE: u32 = 5600u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPGC_FLAGS_ALLOW_PREROLL: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPGC_FLAGS_DISABLE_PLUGINS: u32 = 8u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPGC_FLAGS_IGNORE_AV_SYNC: u32 = 4u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPGC_FLAGS_SUPPRESS_DIALOGS: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPGC_FLAGS_USE_CUSTOM_GRAPH: u32 = 16u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPLib: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x6bf52a50_394a_11d3_b153_00c04f79faa6);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPOCXEVENT_BASE: u32 = 6500u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPRemoteMediaServices: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xdf333473_2cf7_4be2_907f_9aad5661364f);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPUE_EC_USER: u32 = 33024u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMP_MDRT_FLAGS_UNREPORTED_ADDED_ITEMS: u32 = 2u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMP_MDRT_FLAGS_UNREPORTED_DELETED_ITEMS: u32 = 1u32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMP_PLUGINTYPE_DSP: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x6434baea_4954_498d_abd5_2b07123e1f04);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMP_PLUGINTYPE_DSP_OUTOFPROC: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xef29b174_c347_44cc_9a4f_2399118ff38c);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMP_PLUGINTYPE_RENDERING: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xa8554541_115d_406a_a4c7_51111c330183);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMP_SUBSCR_DL_TYPE_BACKGROUND: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("background");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMP_SUBSCR_DL_TYPE_REALTIME: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("real time");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_100Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x8f99ddd8_6684_456b_a0a3_33e1316895f0);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_128Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x93ddbe12_13dc_4e32_a35e_40378e34279a);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_16AMRadio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0f4be81f_d57d_41e1_b2e3_2fad986bfec2);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_1MBVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xb4482a4c_cc17_4b07_a94e_9818d5e0f13f);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_250Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x541841c3_9339_4f7b_9a22_b11540894e42);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_2856100MBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x5a1c2206_dc5e_4186_beb2_4c5a994b132e);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_288FMRadioMono: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x7fa57fc8_6ea4_4645_8abf_b6e5a8f814a1);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_288FMRadioStereo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x22fcf466_aa40_431f_a289_06d0ea1a1e40);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_288VideoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xac617f2d_6cbe_4e84_8e9a_ce151a12a354);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_288VideoVoice: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xbb2bc274_0eb6_4da9_b550_ecf7f2b9948f);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_288VideoWebServer: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xabf2f00d_d555_4815_94ce_8275f3a70bfe);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_3MBVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x55374ac0_309b_4396_b88f_e6e292113f28);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_512Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x70440e6d_c4ef_4f84_8cd0_d5c28686e784);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_56DialUpStereo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xe8026f87_e905_4594_a3c7_00d00041d1d9);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_56DialUpVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xe21713bb_652f_4dab_99de_71e04400270f);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_56DialUpVideoWebServer: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xb756ff10_520f_4749_a399_b780e2fc9250);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_64Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x4820b3f7_cbec_41dc_9391_78598714c8e5);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_6VoiceAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xd508978a_11a0_4d15_b0da_acdc99d4f890);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_96Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0efa0ee3_9e64_41e2_837f_3c0038f327ba);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_DialUpMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xfd7f47f1_72a6_45a4_80f0_3aecefc32c07);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V40_IntranetMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x82cd3321_a94a_4ffc_9c2b_092c10ca16e7);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_100Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xd9f3c932_5ea9_4c6d_89b4_2686e515426e);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_128Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xc64cf5da_df45_40d3_8027_de698d68dc66);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_1500FilmContentVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xf6a5f6df_ee3f_434c_a433_523ce55f516b);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_1500Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0b89164a_5490_4686_9e37_5a80884e5146);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_150VideoPDA: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0f472967_e3c6_4797_9694_f0304c5e2f17);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_2000Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xaa980124_bf10_4e4f_9afd_4329a7395cff);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_225VideoPDA: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xf55ea573_4c02_42b5_9026_a8260c438a9f);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_256Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xafe69b3a_403f_4a1b_8007_0e21cfb3df84);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_2856100MBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x07df7a25_3fe2_4a5b_8b1e_348b0721ca70);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_288FMRadioMono: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xc012a833_a03b_44a5_96dc_ed95cc65582d);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_288FMRadioStereo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xe96d67c9_1a39_4dc4_b900_b1184dc83620);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_288VideoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x58bba0ee_896a_4948_9953_85b736f83947);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_288VideoVoice: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xb952f38e_7dbc_4533_a9ca_b00b1c6e9800);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_288VideoWebServer: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x70a32e2b_e2df_4ebd_9105_d9ca194a2d50);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_384Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xf3d45fbb_8782_44df_97c6_8678e2f9b13d);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_56DialUpStereo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x674ee767_0949_4fac_875e_f4c9c292013b);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_56VideoWebServer: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xdef99e40_57bc_4ab3_b2d1_b6e3caf64257);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_64Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xb29cffc6_f131_41db_b5e8_99d8b0b945f4);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_64AudioISDN: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x91dea458_9d60_4212_9c59_d40919c939e4);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_64VideoISDN: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xc2b7a7e9_7b8e_4992_a1a1_068217a3b311);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_6VoiceAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xeaba9fbf_b64f_49b3_aa0c_73fbdd150ad0);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_700FilmContentVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x7a747920_2449_4d76_99cb_fdb0c90484d4);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_768Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0326ebb6_f76e_4964_b0db_e729978d35ee);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_96Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xa9d4b819_16cc_4a59_9f37_693dbb0302d6);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_DialUpMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x5b16e74b_4068_45b5_b80e_7bf8c80d2c2f);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V70_IntranetMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x045880dc_34b6_4ca9_a326_73557ed143f3);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_100768VideoMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x5bdb5a0e_979e_47d3_9596_73b386392a55);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_100Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xa2e300b4_c2d4_4fc0_b5dd_ecbd948dc0df);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_128StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x407b9450_8bdc_4ee5_88b8_6f527bd941f2);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_1400NTSCVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x931d1bee_617a_4bcd_9905_ccd0786683ee);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_150VideoPDA: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xaee16dfa_2c14_4a2f_ad3f_a3034031784f);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_255VideoPDA: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xfeedbcdf_3fac_4c93_ac0d_47941ec72c0b);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_256Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xbbc75500_33d2_4466_b86b_122b201cc9ae);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_288100VideoMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xd8722c69_2419_4b36_b4e0_6e17b60564e5);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_28856VideoMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xd66920c4_c21f_4ec8_a0b4_95cf2bd57fc4);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_288MonoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x7ea3126d_e1ba_4716_89af_f65cee0c0c67);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_288StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x7e4cab5c_35dc_45bb_a7c0_19b28070d0cc);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_288Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x3df678d9_1352_4186_bbf8_74f0c19b6ae2);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_288VideoOnly: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x8c45b4c7_4aeb_4f78_a5ec_88420b9dadef);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_32StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x60907f9f_b352_47e5_b210_0ef1f47e9f9d);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_384PALVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x9227c692_ae62_4f72_a7ea_736062d0e21e);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_384Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x29b00c2b_09a9_48bd_ad09_cdae117d1da7);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_48StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x5ee06be5_492b_480a_8a8f_12f373ecf9d4);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_56Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x254e8a96_2612_405c_8039_f0bf725ced7d);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_56VideoOnly: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x6e2a6955_81df_4943_ba50_68a986a708f6);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_64StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x09bb5bc4_3176_457f_8dd6_3cd919123e2d);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_700NTSCVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xc8c2985f_e5d9_4538_9e23_9b21bf78f745);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_700PALVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0xec298949_639b_45e2_96fd_4ab32d5919c2);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_768Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x74d01102_e71a_4820_8f0d_13d2ec1e4872);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_96StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x1fc81930_61f2_436f_9d33_349f2a1c0f10);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_BESTVBRVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x048439ba_309c_440e_9cb4_3dcca3756423);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_FAIRVBRVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x3510a862_5850_4886_835f_d78ec6a64042);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMProfile_V80_HIGHVBRVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x0f10d9d3_3b04_4fb0_a3d3_88d4ac854acc);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WindowsMediaPlayer: ::windows_sys::core::GUID = ::windows_sys::core::GUID::from_u128(0x6bf52a52_394a_11d3_b153_00c04f79faa6);
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllAuthors: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllAuthors");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllCPAlbumIDs: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllCPAlbumIDs");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllCPAlbumSubGenreIDs: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllCPAlbumSubGenreIDs");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllCPArtistIDs: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllCPArtistIDs");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllCPGenreIDs: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllCPGenreIDs");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllCPListIDs: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllCPListIDs");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllCPRadioIDs: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllCPRadioIDs");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllCPTrackIDs: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllCPTrackIDs");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllReleaseDateYears: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllReleaseDateYears");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllUserEffectiveRatingStarss: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllUserEffectiveRatingStarss");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAllWMParentalRatings: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AllWMParentalRatings");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szAuthor: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("Author");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szCPAlbumID: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPAlbumID");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szCPAlbumSubGenreID: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPAlbumSubGenreID");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szCPArtistID: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPArtistID");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szCPGenreID: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPGenreID");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szCPListID: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPListID");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szCPRadioID: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPRadioID");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szCPTrackID: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPTrackID");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPartnerInfo_AccountBalance: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AccountBalance");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPartnerInfo_AccountType: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AccountType");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPartnerInfo_HasCachedCredentials: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("HasCachedCredentials");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPartnerInfo_LicenseRefreshAdvanceWarning: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("LicenseRefreshAdvanceWarning");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPartnerInfo_LoginState: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("LoginState");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPartnerInfo_MaximumTrackPurchasePerPurchase: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("MaximumNumberOfTracksPerPurchase");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPartnerInfo_MediaPlayerAccountType: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("MediaPlayerAccountType");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPartnerInfo_PurchasedTrackRequiresReDownload: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("PurchasedTrackRequiresReDownload");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPartnerInfo_UserName: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("UserName");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPrice_CannotBuy: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("PriceCannotBuy");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPrice_Free: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("PriceFree");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szContentPrice_Unknown: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("PriceUnknown");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szFlyoutMenu: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("FlyoutMenu");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_ALTLoginCaption: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ALTLoginCaption");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_ALTLoginURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ALTLoginURL");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_AlbumArtURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AlbumArt");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_ArtistArtURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ArtistArt");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_AuthenticationSuccessURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("AuthenticationSuccessURL");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_CreateAccountURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CreateAccount");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_ErrorDescription: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPErrorDescription");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_ErrorURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPErrorURL");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_ErrorURLLinkText: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPErrorURLLinkText");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_ForgetPasswordURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ForgotPassword");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_GenreArtURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("GenreArt");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_HTMLViewURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("HTMLViewURL");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_ListArtURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ListArt");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_LoginFailureURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("LoginFailureURL");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_PopupCaption: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("PopupCaption");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_PopupURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("Popup");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_RadioArtURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("RadioArt");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_SubGenreArtURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("SubGenreArt");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szItemInfo_TreeListIconURL: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("CPListIDIcon");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szMediaPlayerTask_Browse: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("Browse");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szMediaPlayerTask_Burn: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("Burn");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szMediaPlayerTask_Sync: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("Sync");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szOnlineStore: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("OnlineStore");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szRefreshLicenseBurn: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("RefreshForBurn");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szRefreshLicensePlay: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("RefreshForPlay");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szRefreshLicenseSync: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("RefreshForSync");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szReleaseDateYear: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ReleaseDateYear");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szRootLocation: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("RootLocation");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szStationEvent_Complete: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("TrackComplete");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szStationEvent_Skipped: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("TrackSkipped");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szStationEvent_Started: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("TrackStarted");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szUnknownLocation: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("UnknownLocation");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szUserEffectiveRatingStars: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("UserEffectiveRatingStars");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szUserPlaylist: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("UserPlaylist");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szVerifyPermissionSync: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("VerifyPermissionSync");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szVideoRecent: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("VideoRecent");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szVideoRoot: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("VideoRoot");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szViewMode_Details: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ViewModeDetails");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szViewMode_Icon: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ViewModeIcon");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szViewMode_OrderedList: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ViewModeOrderedList");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szViewMode_Report: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ViewModeReport");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szViewMode_Tile: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("ViewModeTile");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const g_szWMParentalRating: ::windows_sys::core::PCWSTR = ::windows_sys::core::w!("WMParentalRating");
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const kfltTimedLevelMaximumFrequency: f32 = 22050f32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const kfltTimedLevelMinimumFrequency: f32 = 20f32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_BACKGROUNDSYNC_ACTION = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FBSA_DISABLE: FEEDS_BACKGROUNDSYNC_ACTION = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FBSA_ENABLE: FEEDS_BACKGROUNDSYNC_ACTION = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FBSA_RUNNOW: FEEDS_BACKGROUNDSYNC_ACTION = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_BACKGROUNDSYNC_STATUS = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FBSS_DISABLED: FEEDS_BACKGROUNDSYNC_STATUS = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FBSS_ENABLED: FEEDS_BACKGROUNDSYNC_STATUS = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_DOWNLOAD_ERROR = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_NONE: FEEDS_DOWNLOAD_ERROR = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_DOWNLOAD_FAILED: FEEDS_DOWNLOAD_ERROR = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_INVALID_FEED_FORMAT: FEEDS_DOWNLOAD_ERROR = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_NORMALIZATION_FAILED: FEEDS_DOWNLOAD_ERROR = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_PERSISTENCE_FAILED: FEEDS_DOWNLOAD_ERROR = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_DOWNLOAD_BLOCKED: FEEDS_DOWNLOAD_ERROR = 5i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_CANCELED: FEEDS_DOWNLOAD_ERROR = 6i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_UNSUPPORTED_AUTH: FEEDS_DOWNLOAD_ERROR = 7i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_BACKGROUND_DOWNLOAD_DISABLED: FEEDS_DOWNLOAD_ERROR = 8i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_NOT_EXIST: FEEDS_DOWNLOAD_ERROR = 9i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_UNSUPPORTED_MSXML: FEEDS_DOWNLOAD_ERROR = 10i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_UNSUPPORTED_DTD: FEEDS_DOWNLOAD_ERROR = 11i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_DOWNLOAD_SIZE_LIMIT_EXCEEDED: FEEDS_DOWNLOAD_ERROR = 12i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_ACCESS_DENIED: FEEDS_DOWNLOAD_ERROR = 13i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_AUTH_FAILED: FEEDS_DOWNLOAD_ERROR = 14i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDE_INVALID_AUTH: FEEDS_DOWNLOAD_ERROR = 15i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_DOWNLOAD_STATUS = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDS_NONE: FEEDS_DOWNLOAD_STATUS = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDS_PENDING: FEEDS_DOWNLOAD_STATUS = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDS_DOWNLOADING: FEEDS_DOWNLOAD_STATUS = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDS_DOWNLOADED: FEEDS_DOWNLOAD_STATUS = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FDS_DOWNLOAD_FAILED: FEEDS_DOWNLOAD_STATUS = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_ERROR_CODE = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FEC_E_ERRORBASE: FEEDS_ERROR_CODE = -1073479168i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FEC_E_INVALIDMSXMLPROPERTY: FEEDS_ERROR_CODE = -1073479168i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FEC_E_DOWNLOADSIZELIMITEXCEEDED: FEEDS_ERROR_CODE = -1073479167i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_EVENTS_ITEM_COUNT_FLAGS = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FEICF_READ_ITEM_COUNT_CHANGED: FEEDS_EVENTS_ITEM_COUNT_FLAGS = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FEICF_UNREAD_ITEM_COUNT_CHANGED: FEEDS_EVENTS_ITEM_COUNT_FLAGS = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_EVENTS_MASK = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FEM_FOLDEREVENTS: FEEDS_EVENTS_MASK = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FEM_FEEDEVENTS: FEEDS_EVENTS_MASK = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_EVENTS_SCOPE = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FES_ALL: FEEDS_EVENTS_SCOPE = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FES_SELF_ONLY: FEEDS_EVENTS_SCOPE = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FES_SELF_AND_CHILDREN_ONLY: FEEDS_EVENTS_SCOPE = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_SYNC_SETTING = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FSS_DEFAULT: FEEDS_SYNC_SETTING = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FSS_INTERVAL: FEEDS_SYNC_SETTING = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FSS_MANUAL: FEEDS_SYNC_SETTING = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FSS_SUGGESTED: FEEDS_SYNC_SETTING = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_XML_FILTER_FLAGS = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXFF_ALL: FEEDS_XML_FILTER_FLAGS = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXFF_UNREAD: FEEDS_XML_FILTER_FLAGS = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXFF_READ: FEEDS_XML_FILTER_FLAGS = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_XML_INCLUDE_FLAGS = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXIF_NONE: FEEDS_XML_INCLUDE_FLAGS = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXIF_CF_EXTENSIONS: FEEDS_XML_INCLUDE_FLAGS = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_XML_SORT_ORDER = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXSO_NONE: FEEDS_XML_SORT_ORDER = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXSO_ASCENDING: FEEDS_XML_SORT_ORDER = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXSO_DESCENDING: FEEDS_XML_SORT_ORDER = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type FEEDS_XML_SORT_PROPERTY = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXSP_NONE: FEEDS_XML_SORT_PROPERTY = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXSP_PUBDATE: FEEDS_XML_SORT_PROPERTY = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const FXSP_DOWNLOADTIME: FEEDS_XML_SORT_PROPERTY = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type PlayerState = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const stop_state: PlayerState = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const pause_state: PlayerState = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const play_state: PlayerState = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPAccountType = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpatBuyOnly: WMPAccountType = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpatSubscription: WMPAccountType = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpatJanus: WMPAccountType = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPBurnFormat = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbfAudioCD: WMPBurnFormat = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbfDataCD: WMPBurnFormat = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPBurnState = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsUnknown: WMPBurnState = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsBusy: WMPBurnState = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsReady: WMPBurnState = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsWaitingForDisc: WMPBurnState = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsRefreshStatusPending: WMPBurnState = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsPreparingToBurn: WMPBurnState = 5i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsBurning: WMPBurnState = 6i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsStopped: WMPBurnState = 7i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsErasing: WMPBurnState = 8i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpbsDownloading: WMPBurnState = 9i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPCallbackNotification = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpcnLoginStateChange: WMPCallbackNotification = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpcnAuthResult: WMPCallbackNotification = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpcnLicenseUpdated: WMPCallbackNotification = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpcnNewCatalogAvailable: WMPCallbackNotification = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpcnNewPluginAvailable: WMPCallbackNotification = 5i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpcnDisableRadioSkipping: WMPCallbackNotification = 6i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPDeviceStatus = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpdsUnknown: WMPDeviceStatus = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpdsPartnershipExists: WMPDeviceStatus = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpdsPartnershipDeclined: WMPDeviceStatus = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpdsPartnershipAnother: WMPDeviceStatus = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpdsManualDevice: WMPDeviceStatus = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpdsNewDevice: WMPDeviceStatus = 5i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpdsLast: WMPDeviceStatus = 6i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPFolderScanState = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpfssUnknown: WMPFolderScanState = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpfssScanning: WMPFolderScanState = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpfssUpdating: WMPFolderScanState = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpfssStopped: WMPFolderScanState = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPLibraryType = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpltUnknown: WMPLibraryType = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpltAll: WMPLibraryType = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpltLocal: WMPLibraryType = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpltRemote: WMPLibraryType = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpltDisc: WMPLibraryType = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpltPortableDevice: WMPLibraryType = 5i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPOpenState = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposUndefined: WMPOpenState = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposPlaylistChanging: WMPOpenState = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposPlaylistLocating: WMPOpenState = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposPlaylistConnecting: WMPOpenState = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposPlaylistLoading: WMPOpenState = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposPlaylistOpening: WMPOpenState = 5i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposPlaylistOpenNoMedia: WMPOpenState = 6i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposPlaylistChanged: WMPOpenState = 7i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposMediaChanging: WMPOpenState = 8i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposMediaLocating: WMPOpenState = 9i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposMediaConnecting: WMPOpenState = 10i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposMediaLoading: WMPOpenState = 11i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposMediaOpening: WMPOpenState = 12i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposMediaOpen: WMPOpenState = 13i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposBeginCodecAcquisition: WMPOpenState = 14i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposEndCodecAcquisition: WMPOpenState = 15i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposBeginLicenseAcquisition: WMPOpenState = 16i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposEndLicenseAcquisition: WMPOpenState = 17i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposBeginIndividualization: WMPOpenState = 18i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposEndIndividualization: WMPOpenState = 19i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposMediaWaiting: WMPOpenState = 20i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmposOpeningUnknownURL: WMPOpenState = 21i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPPartnerNotification = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsnBackgroundProcessingBegin: WMPPartnerNotification = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsnBackgroundProcessingEnd: WMPPartnerNotification = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsnCatalogDownloadFailure: WMPPartnerNotification = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsnCatalogDownloadComplete: WMPPartnerNotification = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPPlayState = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsUndefined: WMPPlayState = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsStopped: WMPPlayState = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsPaused: WMPPlayState = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsPlaying: WMPPlayState = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsScanForward: WMPPlayState = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsScanReverse: WMPPlayState = 5i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsBuffering: WMPPlayState = 6i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsWaiting: WMPPlayState = 7i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsMediaEnded: WMPPlayState = 8i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsTransitioning: WMPPlayState = 9i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsReady: WMPPlayState = 10i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsReconnecting: WMPPlayState = 11i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmppsLast: WMPPlayState = 12i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPPlaylistChangeEventType = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcUnknown: WMPPlaylistChangeEventType = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcClear: WMPPlaylistChangeEventType = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcInfoChange: WMPPlaylistChangeEventType = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcMove: WMPPlaylistChangeEventType = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcDelete: WMPPlaylistChangeEventType = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcInsert: WMPPlaylistChangeEventType = 5i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcAppend: WMPPlaylistChangeEventType = 6i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcPrivate: WMPPlaylistChangeEventType = 7i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcNameChange: WMPPlaylistChangeEventType = 8i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcMorph: WMPPlaylistChangeEventType = 9i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcSort: WMPPlaylistChangeEventType = 10i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmplcLast: WMPPlaylistChangeEventType = 11i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPPlugin_Caps = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPPlugin_Caps_CannotConvertFormats: WMPPlugin_Caps = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPRipState = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmprsUnknown: WMPRipState = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmprsRipping: WMPRipState = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmprsStopped: WMPRipState = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPServices_StreamState = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPServices_StreamState_Stop: WMPServices_StreamState = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPServices_StreamState_Pause: WMPServices_StreamState = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const WMPServices_StreamState_Play: WMPServices_StreamState = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPStreamingType = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpstUnknown: WMPStreamingType = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpstMusic: WMPStreamingType = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpstVideo: WMPStreamingType = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpstRadio: WMPStreamingType = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPStringCollectionChangeEventType = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsccetUnknown: WMPStringCollectionChangeEventType = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsccetInsert: WMPStringCollectionChangeEventType = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsccetChange: WMPStringCollectionChangeEventType = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsccetDelete: WMPStringCollectionChangeEventType = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsccetClear: WMPStringCollectionChangeEventType = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsccetBeginUpdates: WMPStringCollectionChangeEventType = 5i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsccetEndUpdates: WMPStringCollectionChangeEventType = 6i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPSubscriptionDownloadState = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsdlsDownloading: WMPSubscriptionDownloadState = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsdlsPaused: WMPSubscriptionDownloadState = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsdlsProcessing: WMPSubscriptionDownloadState = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsdlsCompleted: WMPSubscriptionDownloadState = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsdlsCancelled: WMPSubscriptionDownloadState = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPSubscriptionServiceEvent = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsseCurrentBegin: WMPSubscriptionServiceEvent = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsseCurrentEnd: WMPSubscriptionServiceEvent = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsseFullBegin: WMPSubscriptionServiceEvent = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpsseFullEnd: WMPSubscriptionServiceEvent = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPSyncState = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpssUnknown: WMPSyncState = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpssSynchronizing: WMPSyncState = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpssStopped: WMPSyncState = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpssEstimating: WMPSyncState = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpssLast: WMPSyncState = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPTaskType = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpttBrowse: WMPTaskType = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpttSync: WMPTaskType = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpttBurn: WMPTaskType = 3i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpttCurrent: WMPTaskType = 4i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPTemplateSize = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmptsSmall: WMPTemplateSize = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmptsMedium: WMPTemplateSize = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmptsLarge: WMPTemplateSize = 2i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub type WMPTransactionType = i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpttNoTransaction: WMPTransactionType = 0i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpttDownload: WMPTransactionType = 1i32;
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub const wmpttBuy: WMPTransactionType = 2i32;
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub struct TimedLevel {
pub frequency: [u8; 2048],
pub waveform: [u8; 2048],
pub state: i32,
pub timeStamp: i64,
}
impl ::core::marker::Copy for TimedLevel {}
impl ::core::clone::Clone for TimedLevel {
fn clone(&self) -> Self {
*self
}
}
#[repr(C)]
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub struct WMPContextMenuInfo {
pub dwID: u32,
pub bstrMenuText: ::windows_sys::core::BSTR,
pub bstrHelpText: ::windows_sys::core::BSTR,
}
impl ::core::marker::Copy for WMPContextMenuInfo {}
impl ::core::clone::Clone for WMPContextMenuInfo {
fn clone(&self) -> Self {
*self
}
}
#[repr(C, packed(1))]
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub struct WMP_WMDM_METADATA_ROUND_TRIP_DEVICE2PC {
pub dwCurrentTransactionID: u32,
pub dwReturnedObjectCount: u32,
pub dwUnretrievedObjectCount: u32,
pub dwDeletedObjectStartingOffset: u32,
pub dwFlags: u32,
pub wsObjectPathnameList: [u16; 1],
}
impl ::core::marker::Copy for WMP_WMDM_METADATA_ROUND_TRIP_DEVICE2PC {}
impl ::core::clone::Clone for WMP_WMDM_METADATA_ROUND_TRIP_DEVICE2PC {
fn clone(&self) -> Self {
*self
}
}
#[repr(C, packed(1))]
#[doc = "*Required features: `\"Win32_Media_MediaPlayer\"`*"]
pub struct WMP_WMDM_METADATA_ROUND_TRIP_PC2DEVICE {
pub dwChangesSinceTransactionID: u32,
pub dwResultSetStartingIndex: u32,
}
impl ::core::marker::Copy for WMP_WMDM_METADATA_ROUND_TRIP_PC2DEVICE {}
impl ::core::clone::Clone for WMP_WMDM_METADATA_ROUND_TRIP_PC2DEVICE {
fn clone(&self) -> Self {
*self
}
}
|
// Copyright 2013 Google Inc. All Rights Reserved.
// Copyright 2017 The Ninja-rs Project Developers. All Rights Reserved.
//
// 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.
pub const NINJA_VERSION: &'static str = "1.8.2-rs-git";
pub fn parse_version(version: &str) -> (u8, u8) {
let mut split = version.split('.');
let (major, minor) = (split.next(), split.next());
let major = major.and_then(|s| s.parse::<u8>().ok()).unwrap_or(0);
let minor = minor.and_then(|s| s.parse::<u8>().ok()).unwrap_or(0);
(major, minor)
}
pub fn check_ninja_version(version: &str) {
let (bin_major, bin_minor) = parse_version(NINJA_VERSION);
let (file_major, file_minor) = parse_version(version);
if bin_major > file_major {
warning!(
concat!(
"ninja executable version ({}) greater than build file ",
"ninja_required_version ({}); versions may be incompatible."
),
NINJA_VERSION,
version
);
return;
}
if (bin_major == file_major && bin_minor < file_minor) || bin_major < file_major {
fatal!(
concat!(
"ninja version ({}) incompatible with build file ",
"ninja_required_version version ({})."
),
NINJA_VERSION,
version
);
}
}
#[test]
fn test_parse_version() {
assert_eq!(parse_version(""), (0, 0));
assert_eq!(parse_version("1"), (1, 0));
assert_eq!(parse_version("1.2"), (1, 2));
assert_eq!(parse_version("1.2.3"), (1, 2));
assert_eq!(parse_version("1.2.3.git"), (1, 2));
assert_eq!(parse_version("1.2.3-git"), (1, 2));
}
|
use crate::structures::*;
pub fn create(l : usize) -> Assignation {
(0..l).map(|_| false).collect()
}
pub fn grow(ass : Assignation) -> Option<Assignation> {
if ass.iter().all(|x| *x) { return None };
Some(add_one(ass))
}
fn add_one(ass : Assignation) -> Assignation {
let (f, t) : (&bool, &[bool]) = ass.split_first().unwrap();
match f {
false => {
let mut a : Vec<bool> = vec![true];
a.append(&mut t.to_vec());
a
},
true => {
let mut a = vec![false];
a.append(&mut add_one(t.to_vec()));
a
}
}
}
|
mod handler;
mod upgrade;
pub use upgrade::Context;
|
use regex::Regex;
use std::collections::HashMap;
use std::fs;
use std::str::Lines;
fn part_1(lines: Lines) {
let mut memory = HashMap::new();
let reg = Regex::new(r"^mem\[(\d+)\] = (\d+)").unwrap();
let mut or_mask = 0;
let mut and_mask: u64 = 2u64.pow(36) - 1;
for line in lines {
if line.starts_with("mask = ") {
or_mask = 0;
and_mask = 2u64.pow(36) - 1;
let sub = &line[7..];
for i in 0..sub.len() {
let bit = sub.chars().nth(sub.len() - 1 - i).unwrap();
match bit {
'1' => or_mask += 2u64.pow(i as u32),
'0' => and_mask -= 2u64.pow(i as u32),
_ => (),
}
}
}
if line.starts_with("mem") {
let groups = reg.captures(line).unwrap();
let value = groups[2].parse::<u64>().unwrap();
let mem_index = groups[1].parse::<usize>().unwrap();
let masked_value = value & and_mask | or_mask;
memory.insert(mem_index, masked_value);
}
}
let sum = memory.iter().fold(0, |acc, (_, mem_value)| acc + mem_value);
println!("Part 1 : {}", sum);
}
fn part_2(lines: Lines) {
let mut memory = HashMap::new();
let reg = Regex::new(r"^mem\[(\d+)\] = (\d+)").unwrap();
let mut mask: String = String::new();
for line in lines {
if line.starts_with("mask = ") {
let sub = &line[7..];
mask = String::from(sub);
}
if line.starts_with("mem") {
let groups = reg.captures(line).unwrap();
let value = groups[2].parse::<u64>().unwrap();
let mem_index = groups[1].parse::<u64>().unwrap();
let mem_index_as_bin = format!("{:0width$b}", mem_index, width = mask.len());
let mem_index_with_mask: String = mask
.clone()
.chars()
.enumerate()
.map(|(i, c)| match c {
'0' => mem_index_as_bin.chars().nth(i).unwrap(),
_ => c,
})
.collect();
let nb_floating = mem_index_with_mask.chars().filter(|x| x == &'X').count();
let nb_addr = 2usize.pow(nb_floating as u32);
for i in 0..nb_addr {
let as_bin = format!("{:0width$b}", i, width = nb_floating);
let mut new_addr = String::from(&mem_index_with_mask);
for j in 0..as_bin.len() {
let new_bit = as_bin.chars().nth(j).unwrap().to_string();
new_addr = new_addr.replacen('X', new_bit.as_str(), 1);
}
let new_addr_dec = u64::from_str_radix(&new_addr, 2).unwrap();
//println!("new address {} (decimal {})", new_mask, new_mask_dec);
memory.insert(new_addr_dec, value);
}
}
}
let sum = memory.iter().fold(0, |acc, (_, mem_value)| acc + mem_value);
println!("Part 2: {}", sum);
}
fn main() {
let path = "src/input.txt";
let file_content = fs::read_to_string(path).unwrap();
let lines = file_content.lines();
part_1(lines);
let lines = file_content.lines();
part_2(lines);
}
|
use crate::core::{Oracle, ShellCmd};
pub struct Price {}
impl Price {
pub fn new() -> Price {
Price {}
}
}
impl Oracle for Price {
type T = f32;
fn as_cmd(&self) -> ShellCmd {
ShellCmd::new("curl", &["https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD"])
}
fn from_cmd_output(&self, output: String) -> Option<f32> {
let parsed = json::parse(&output).ok()?;
parsed["USD"].as_f32()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_as_cmd() {
assert_eq!(
Price::new().as_cmd(),
ShellCmd::new(
"curl",
&["https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD"]
)
);
}
#[test]
fn test_from_cmd_ok() {
assert_eq!(Price::new().from_cmd_output(r#"{"USD":100.0}"#.into()), Some(100.0));
}
#[test]
fn test_from_cmd_not_ok() {
assert_eq!(Price::new().from_cmd_output(r#"{}"#.into()), None);
}
}
|
// use failure::Error;
// use std::error::Error;
use crate::error::KvsError;
use std::result;
/// Using failure::Error as error type
pub type Result<T> = result::Result<T, KvsError>;
/// Define the storage interface
pub trait KvsEngine: Clone + Send + 'static {
/// Set the value of a string key to a string
fn set(&self, key: String, value: String) -> Result<()>;
/// Get the string value of a string key. If the key does not exist, return None
fn get(&self, key: String) -> Result<Option<String>>;
/// Remove a given string key
fn remove(&self, key: String) -> Result<()>;
}
/// A simple kv store using hash map store key/value
pub mod simple_kvs;
/// A kv store using the `sled` library
pub mod sled_kvs;
|
#![cfg_attr(feature = "bench", feature(test))]
#![allow(non_snake_case)]
#![allow(unused)]
#[macro_use]
extern crate jsontests_derive;
use bigint::{Address, Gas};
use evm::{EmbeddedAccountPatch, Patch, Precompiled, EMBEDDED_PRECOMPILEDS};
// Shifting opcodes tests
#[derive(JsonTests)]
#[directory = "jsontests/res/files/eth/VMTests/vmEIP215"]
#[test_with = "jsontests::util::run_test"]
#[cfg_attr(feature = "bench", bench_with = "jsontests::util::run_bench")]
struct EIP215;
// EXTCODEHASH tests
#[derive(JsonTests)]
#[directory = "jsontests/res/files/eth/VMTests/vmEIP1052"]
#[test_with = "jsontests::util::run_test"]
#[cfg_attr(feature = "bench", bench_with = "jsontests::util::run_bench")]
struct EIP1052;
// CREATE2 tests
#[derive(JsonTests)]
#[directory = "jsontests/res/files/eth/VMTests/vmEIP1014"]
#[test_with = "jsontests::util::run_test"]
#[cfg_attr(feature = "bench", bench_with = "jsontests::util::run_bench")]
struct EIP1014;
// Gas metering changes tests
#[derive(JsonTests)]
#[directory = "jsontests/res/files/eth/VMTests/vmEIP1283"]
#[test_with = "jsontests::util::run_test"]
#[patch = "crate::EIP1283Patch"]
#[cfg_attr(feature = "bench", bench_with = "jsontests::util::run_bench")]
struct EIP1283;
#[derive(Copy, Clone, Default)]
struct EIP1283Patch(pub EmbeddedAccountPatch);
#[rustfmt::skip]
impl Patch for EIP1283Patch {
type Account = EmbeddedAccountPatch;
fn account_patch(&self) -> &Self::Account { &self.0 }
fn code_deposit_limit(&self) -> Option<usize> { None }
fn callstack_limit(&self) -> usize { 2 }
fn gas_extcode(&self) -> Gas { Gas::from(20usize) }
fn gas_balance(&self) -> Gas { Gas::from(20usize) }
fn gas_sload(&self) -> Gas { Gas::from(50usize) }
fn gas_suicide(&self) -> Gas { Gas::from(0usize) }
fn gas_suicide_new_account(&self) -> Gas { Gas::from(0usize) }
fn gas_call(&self) -> Gas { Gas::from(40usize) }
fn gas_expbyte(&self) -> Gas { Gas::from(10usize) }
fn gas_transaction_create(&self) -> Gas { Gas::from(0usize) }
fn force_code_deposit(&self) -> bool { true }
fn has_delegate_call(&self) -> bool { true }
fn has_static_call(&self) -> bool { true }
fn has_revert(&self) -> bool { true }
fn has_return_data(&self) -> bool { true }
fn has_bitwise_shift(&self) -> bool { true }
fn has_create2(&self) -> bool { true }
fn has_extcodehash(&self) -> bool { true }
fn has_reduced_sstore_gas_metering(&self) -> bool { true }
fn err_on_call_with_more_gas(&self) -> bool { true }
fn call_create_l64_after_gas(&self) -> bool { false }
fn memory_limit(&self) -> usize { usize::max_value() }
fn is_precompiled_contract_enabled(&self, address: &Address) -> bool {
match address.low_u64() {
0x1 | 0x2 | 0x3 | 0x4 => true,
_ => false,
}
}
fn precompileds(&self) -> &'static [(Address, Option<&'static [u8]>, &'static Precompiled)] {
&EMBEDDED_PRECOMPILEDS
}
}
|
pub(crate) mod dev;
pub(crate) mod local;
pub(crate) mod testnet;
use sp_consensus_aura::sr25519::AuthorityId as AuraId;
use sp_core::{crypto::Ss58Codec, Pair, Public};
use sp_finality_grandpa::AuthorityId as GrandpaId;
use sp_runtime::traits::{IdentifyAccount, Verify};
use vln_commons::runtime::{AccountId, Signature};
use vln_runtime::{
AuraConfig, GenesisConfig, GrandpaConfig, SudoConfig, SystemConfig, TokensConfig,
};
type AccountPublic = <Signature as Verify>::Signer;
pub(crate) type ChainSpec = sc_service::GenericChainSpec<GenesisConfig>;
struct GenesisConfigBuilder<'a> {
initial_authorities: &'a [(AuraId, GrandpaId)],
sudo_key: AccountId,
wasm_binary: &'a [u8],
}
impl GenesisConfigBuilder<'_> {
fn build(self) -> GenesisConfig {
GenesisConfig {
frame_system: Some(SystemConfig {
code: self.wasm_binary.to_vec(),
changes_trie_config: Default::default(),
}),
orml_tokens: Some(TokensConfig {
endowed_accounts: vec![],
}),
pallet_aura: Some(AuraConfig {
authorities: self
.initial_authorities
.iter()
.map(|x| (x.0.clone()))
.collect(),
}),
pallet_grandpa: Some(GrandpaConfig {
authorities: self
.initial_authorities
.iter()
.map(|x| (x.1.clone(), 1))
.collect(),
}),
pallet_membership: Some(pallet_membership::GenesisConfig {
members: vec![],
phantom: Default::default(),
}),
pallet_sudo: Some(SudoConfig { key: self.sudo_key }),
}
}
}
fn account_id_from_ss58<T: Public>(ss58: &str) -> Result<AccountId, String>
where
AccountPublic: From<T>,
{
Ok(AccountPublic::from(public_key_from_ss58(ss58)?).into_account())
}
fn authority_keys_from_seed(s: &str) -> (AuraId, GrandpaId) {
(get_from_seed::<AuraId>(s), get_from_seed::<GrandpaId>(s))
}
fn get_account_id_from_seed<T: Public>(seed: &str) -> AccountId
where
AccountPublic: From<<T::Pair as Pair>::Public>,
{
AccountPublic::from(get_from_seed::<T>(seed)).into_account()
}
fn get_from_seed<T: Public>(seed: &str) -> <T::Pair as Pair>::Public {
T::Pair::from_string(&format!("//{}", seed), None)
.expect("static values are valid; qed")
.public()
}
fn public_key_from_ss58<T: Public>(ss58: &str) -> Result<T, String> {
Ss58Codec::from_string(ss58).map_err(|_| "Couldn't generate public key from ss58 string".into())
}
|
use input_i_scanner::InputIScanner;
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
macro_rules! scan {
(($($t: ty),+)) => {
($(scan!($t)),+)
};
($t: ty) => {
_i_i.scan::<$t>() as $t
};
(($($t: ty),+); $n: expr) => {
std::iter::repeat_with(|| scan!(($($t),+))).take($n).collect::<Vec<_>>()
};
($t: ty; $n: expr) => {
std::iter::repeat_with(|| scan!($t)).take($n).collect::<Vec<_>>()
};
}
let _n = scan!(usize);
let s = scan!(String);
let mut last = '?';
let mut len = 0usize;
let mut a = Vec::new();
for ch in s.chars() {
if last == ch {
len += 1;
} else {
a.push(len);
len = 1;
}
last = ch;
}
a.push(len);
let mut ans = 0;
for len in a {
if len >= 2 {
ans += len * (len - 1) / 2;
}
}
println!("{}", ans);
}
|
use std::hash::{Hash, Hasher};
use protobuf_iter::*;
use delta::DeltaEncodedIter;
use super::primitive_block::PrimitiveBlock;
use super::info::Info;
use super::tags::TagsIter;
#[derive(Debug, Clone)]
pub struct Way<'a> {
pub id: u64,
pub info: Option<Info<'a>>,
tags_iter: TagsIter<'a>,
refs_iter: DeltaEncodedIter<'a, PackedVarint, i64>,
}
impl<'a> Way<'a> {
pub fn parse(primitive_block: &'a PrimitiveBlock<'a>, data: &'a [u8]) -> Self {
let mut way = Way {
id: 0,
info: None,
tags_iter: TagsIter::new(&primitive_block.stringtable),
refs_iter: DeltaEncodedIter::new(ParseValue::LengthDelimited(&[])),
};
let iter = MessageIter::new(data);
for m in iter.clone() {
match m.tag {
1 =>
way.id = Into::into(m.value),
2 =>
way.tags_iter.set_keys(*m.value),
3 =>
way.tags_iter.set_values(*m.value),
4 =>
way.info = Some(Info::parse(&primitive_block.stringtable, *m.value)),
8 =>
way.refs_iter = DeltaEncodedIter::new(m.value),
_ => ()
}
}
way
}
pub fn tags(&self) -> TagsIter<'a> {
self.tags_iter.clone()
}
pub fn refs(&self) -> DeltaEncodedIter<'a, PackedVarint, i64> {
self.refs_iter.clone()
}
}
impl<'a> Hash for Way<'a> {
fn hash<H>(&self, state: &mut H)
where
H: Hasher,
{
self.id.hash(state)
}
}
impl<'a> Eq for Way<'a> {}
impl<'a> PartialEq for Way<'a> {
fn eq(&self, other: &Self) -> bool {
self.id == other.id
}
}
|
use legion::systems::{
Builder,
CommandBuffer,
};
use legion::{
component,
maybe_changed,
Entity,
};
use nalgebra::Matrix3;
use sourcerenderer_core::{
Matrix4,
Quaternion,
Vec3,
};
use super::GlobalTransform;
use crate::game::{
TickDelta,
TickDuration,
};
pub struct PreviousGlobalTransform(pub Matrix4);
pub struct InterpolatedTransform(pub Matrix4);
pub fn install(fixed_rate_systems: &mut Builder, systems: &mut Builder) {
fixed_rate_systems.add_system(update_previous_global_transform_system());
systems.add_system(interpolate_transform_system());
systems.add_system(interpolate_new_transform_system());
systems.flush();
}
#[system(for_each)]
#[filter(maybe_changed::<GlobalTransform>())]
fn update_previous_global_transform(
transform: &GlobalTransform,
entity: &Entity,
command_buffer: &mut CommandBuffer,
) {
command_buffer.add_component(*entity, PreviousGlobalTransform(transform.0));
}
#[system(for_each)]
fn interpolate_transform(
transform: &GlobalTransform,
previous_transform: &PreviousGlobalTransform,
interpolated_transform: &mut InterpolatedTransform,
#[resource] tick_duration: &TickDuration,
#[resource] tick_delta: &TickDelta,
) {
if interpolated_transform.0 == transform.0 {
return;
}
let frac = tick_delta.0.as_secs_f32() / tick_duration.0.as_secs_f32();
let interpolated = interpolate_transform_matrix(&previous_transform.0, &transform.0, frac);
*interpolated_transform.0 = *interpolated;
}
#[system(for_each)]
#[filter(!component::<PreviousGlobalTransform>())]
fn interpolate_new_transform(
transform: &GlobalTransform,
entity: &Entity,
command_buffer: &mut CommandBuffer,
) {
command_buffer.add_component(*entity, InterpolatedTransform(transform.0));
}
pub(crate) fn deconstruct_transform(transform_mat: &Matrix4) -> (Vec3, Quaternion, Vec3) {
let scale = Vec3::new(
transform_mat.column(0).xyz().magnitude(),
transform_mat.column(1).xyz().magnitude(),
transform_mat.column(2).xyz().magnitude(),
);
let translation: Vec3 = transform_mat.column(3).xyz();
let rotation = Quaternion::from_matrix(&Matrix3::<f32>::from_columns(&[
transform_mat.column(0).xyz() / scale.x,
transform_mat.column(1).xyz() / scale.y,
transform_mat.column(2).xyz() / scale.z,
]));
(translation, rotation, scale)
}
fn interpolate_transform_matrix(from: &Matrix4, to: &Matrix4, frac: f32) -> Matrix4 {
let (from_position, from_rotation, from_scale) = deconstruct_transform(from);
let (to_position, to_rotation, to_scale) = deconstruct_transform(to);
let position = from_position.lerp(&to_position, frac);
let rotation: Quaternion = Quaternion::from_quaternion(from_rotation.lerp(&to_rotation, frac));
let scale = from_scale.lerp(&to_scale, frac);
Matrix4::new_translation(&position)
* Matrix4::new_rotation(
rotation
.axis_angle()
.map_or(Vec3::new(0.0f32, 0.0f32, 0.0f32), |(axis, amount)| {
*axis * amount
}),
)
* Matrix4::new_nonuniform_scaling(&scale)
}
|
pub use morgan_runtime::genesis_utils::{
create_genesis_block_with_leader, GenesisBlockInfo, BOOTSTRAP_LEADER_DIFS,
};
use morgan_interface::pubkey::Pubkey;
// same as genesis_block::create_genesis_block, but with bootstrap_leader staking logic
// for the core crate tests
pub fn create_genesis_block(mint_difs: u64) -> GenesisBlockInfo {
create_genesis_block_with_leader(
mint_difs,
&Pubkey::new_rand(),
BOOTSTRAP_LEADER_DIFS,
)
}
|
// https://docs.microsoft.com/en-us/windows/desktop/power/power-management-portal
mod device;
mod ffi;
mod iterator;
mod manager;
pub use self::device::PowerDevice;
pub use self::iterator::PowerIterator;
pub use self::manager::PowerManager;
|
use ws::{connect, CloseCode};
use std::rc::Rc;
use std::cell::Cell;
use serde_json::{Value};
use crate::base::misc::util::downcast_to_string;
use crate::api::config::Config;
use crate::api::fee_info::data::{
RequestBrokerageCommand,
RequestBrokerageResponse,
BrokerageSideKick
};
pub fn request<F>(config: Config, account: String, op: F)
where F: Fn(Result<RequestBrokerageResponse, BrokerageSideKick>) {
let info = Rc::new(Cell::new(String::new()));
let account_rc = Rc::new(Cell::new(account));
connect(config.addr, |out| {
let copy = info.clone();
let account = account_rc.clone();
if let Ok(command) = RequestBrokerageCommand::with_params(account.take()).to_string() {
out.send(command).unwrap();
}
move |msg: ws::Message| {
let c = msg.as_text()?;
copy.set(c.to_string());
out.close(CloseCode::Normal)
}
}).unwrap();
let resp = downcast_to_string(info);
if let Ok(x) = serde_json::from_str(&resp) as Result<Value, serde_json::error::Error> {
if let Some(status) = x["status"].as_str() {
if status == "success" {
let x: String = x["result"].to_string();
if let Ok(v) = serde_json::from_str(&x) as Result<RequestBrokerageResponse, serde_json::error::Error> {
op(Ok(v))
}
} else {
if let Ok(v) = serde_json::from_str(&x.to_string()) as Result<BrokerageSideKick, serde_json::error::Error> {
op(Err(v))
}
}
}
}
}
|
use clap::Arg;
pub fn account_arg<'a>() -> Arg<'a, 'a> {
Arg::with_name("account")
.long("account")
.short("a")
.help("Selects a specific account")
.value_name("STRING")
}
|
//! Test integration between different policies.
use std::{collections::HashMap, sync::Arc, time::Duration};
use iox_time::{MockProvider, Time};
use parking_lot::Mutex;
use rand::rngs::mock::StepRng;
use test_helpers::maybe_start_logging;
use tokio::{runtime::Handle, sync::Notify};
use crate::{
backend::{
policy::refresh::test_util::{backoff_cfg, NotifyExt},
CacheBackend,
},
loader::test_util::TestLoader,
resource_consumption::{test_util::TestSize, ResourceEstimator},
};
use super::{
lru::{LruPolicy, ResourcePool},
refresh::{test_util::TestRefreshDurationProvider, RefreshPolicy},
remove_if::{RemoveIfHandle, RemoveIfPolicy},
ttl::{test_util::TestTtlProvider, TtlPolicy},
PolicyBackend,
};
#[tokio::test]
async fn test_refresh_can_prevent_expiration() {
let TestStateTtlAndRefresh {
mut backend,
refresh_duration_provider,
ttl_provider,
time_provider,
loader,
notify_idle,
..
} = TestStateTtlAndRefresh::new();
loader.mock_next(1, String::from("foo"));
refresh_duration_provider.set_refresh_in(
1,
String::from("a"),
Some(backoff_cfg(Duration::from_secs(1))),
);
ttl_provider.set_expires_in(1, String::from("a"), Some(Duration::from_secs(2)));
refresh_duration_provider.set_refresh_in(1, String::from("foo"), None);
ttl_provider.set_expires_in(1, String::from("foo"), Some(Duration::from_secs(2)));
backend.set(1, String::from("a"));
// perform refresh
time_provider.inc(Duration::from_secs(1));
notify_idle.notified_with_timeout().await;
// no expired because refresh resets the timer
time_provider.inc(Duration::from_secs(1));
assert_eq!(backend.get(&1), Some(String::from("foo")));
// we don't request a 2nd refresh (refresh duration is None), so this finally expires
time_provider.inc(Duration::from_secs(1));
assert_eq!(backend.get(&1), None);
}
#[tokio::test]
async fn test_refresh_sets_new_expiration_after_it_finishes() {
let TestStateTtlAndRefresh {
mut backend,
refresh_duration_provider,
ttl_provider,
time_provider,
loader,
notify_idle,
..
} = TestStateTtlAndRefresh::new();
let barrier = loader.block_next(1, String::from("foo"));
refresh_duration_provider.set_refresh_in(
1,
String::from("a"),
Some(backoff_cfg(Duration::from_secs(1))),
);
ttl_provider.set_expires_in(1, String::from("a"), Some(Duration::from_secs(3)));
refresh_duration_provider.set_refresh_in(1, String::from("foo"), None);
ttl_provider.set_expires_in(1, String::from("foo"), Some(Duration::from_secs(3)));
backend.set(1, String::from("a"));
// perform refresh
time_provider.inc(Duration::from_secs(1));
notify_idle.notified_with_timeout().await;
time_provider.inc(Duration::from_secs(1));
barrier.wait().await;
notify_idle.notified_with_timeout().await;
assert_eq!(backend.get(&1), Some(String::from("foo")));
// no expired because refresh resets the timer after it was ready (now), not when it started (1s ago)
time_provider.inc(Duration::from_secs(2));
assert_eq!(backend.get(&1), Some(String::from("foo")));
// we don't request a 2nd refresh (refresh duration is None), so this finally expires
time_provider.inc(Duration::from_secs(1));
assert_eq!(backend.get(&1), None);
}
#[tokio::test]
async fn test_refresh_does_not_update_lru_time() {
let TestStateLruAndRefresh {
mut backend,
refresh_duration_provider,
size_estimator,
time_provider,
loader,
notify_idle,
pool,
..
} = TestStateLruAndRefresh::new();
size_estimator.mock_size(1, String::from("a"), TestSize(4));
size_estimator.mock_size(1, String::from("foo"), TestSize(4));
size_estimator.mock_size(2, String::from("b"), TestSize(4));
size_estimator.mock_size(3, String::from("c"), TestSize(4));
refresh_duration_provider.set_refresh_in(
1,
String::from("a"),
Some(backoff_cfg(Duration::from_secs(1))),
);
refresh_duration_provider.set_refresh_in(1, String::from("foo"), None);
refresh_duration_provider.set_refresh_in(2, String::from("b"), None);
refresh_duration_provider.set_refresh_in(3, String::from("c"), None);
let barrier = loader.block_next(1, String::from("foo"));
backend.set(1, String::from("a"));
pool.wait_converged().await;
// trigger refresh
time_provider.inc(Duration::from_secs(1));
time_provider.inc(Duration::from_secs(1));
backend.set(2, String::from("b"));
pool.wait_converged().await;
time_provider.inc(Duration::from_secs(1));
notify_idle.notified_with_timeout().await;
barrier.wait().await;
notify_idle.notified_with_timeout().await;
// add a third item to the cache, forcing LRU to evict one of the items
backend.set(3, String::from("c"));
pool.wait_converged().await;
// Should evict `1` even though it was refreshed after `2` was added
assert_eq!(backend.get(&1), None);
}
#[tokio::test]
async fn test_if_refresh_to_slow_then_expire() {
let TestStateTtlAndRefresh {
mut backend,
refresh_duration_provider,
ttl_provider,
time_provider,
loader,
notify_idle,
..
} = TestStateTtlAndRefresh::new();
let barrier = loader.block_next(1, String::from("foo"));
refresh_duration_provider.set_refresh_in(
1,
String::from("a"),
Some(backoff_cfg(Duration::from_secs(1))),
);
ttl_provider.set_expires_in(1, String::from("a"), Some(Duration::from_secs(2)));
backend.set(1, String::from("a"));
// perform refresh
time_provider.inc(Duration::from_secs(1));
notify_idle.notified_with_timeout().await;
time_provider.inc(Duration::from_secs(1));
notify_idle.not_notified().await;
assert_eq!(backend.get(&1), None);
// late loader finish will NOT bring the entry back
barrier.wait().await;
notify_idle.notified_with_timeout().await;
assert_eq!(backend.get(&1), None);
}
#[tokio::test]
async fn test_refresh_can_trigger_lru_eviction() {
maybe_start_logging();
let TestStateLRUAndRefresh {
mut backend,
refresh_duration_provider,
loader,
size_estimator,
time_provider,
notify_idle,
pool,
..
} = TestStateLRUAndRefresh::new();
assert_eq!(pool.limit(), TestSize(10));
loader.mock_next(1, String::from("b"));
refresh_duration_provider.set_refresh_in(
1,
String::from("a"),
Some(backoff_cfg(Duration::from_secs(1))),
);
refresh_duration_provider.set_refresh_in(1, String::from("b"), None);
refresh_duration_provider.set_refresh_in(2, String::from("c"), None);
refresh_duration_provider.set_refresh_in(3, String::from("d"), None);
size_estimator.mock_size(1, String::from("a"), TestSize(1));
size_estimator.mock_size(1, String::from("b"), TestSize(9));
size_estimator.mock_size(2, String::from("c"), TestSize(1));
size_estimator.mock_size(3, String::from("d"), TestSize(1));
backend.set(1, String::from("a"));
backend.set(2, String::from("c"));
backend.set(3, String::from("d"));
pool.wait_converged().await;
assert_eq!(backend.get(&2), Some(String::from("c")));
assert_eq!(backend.get(&3), Some(String::from("d")));
time_provider.inc(Duration::from_millis(1));
assert_eq!(backend.get(&1), Some(String::from("a")));
// refresh
time_provider.inc(Duration::from_secs(10));
notify_idle.notified_with_timeout().await;
pool.wait_converged().await;
// needed to evict 2->"c"
assert_eq!(backend.get(&1), Some(String::from("b")));
assert_eq!(backend.get(&2), None);
assert_eq!(backend.get(&3), Some(String::from("d")));
}
#[tokio::test]
async fn test_lru_learns_about_ttl_evictions() {
let TestStateTtlAndLRU {
mut backend,
ttl_provider,
size_estimator,
time_provider,
pool,
..
} = TestStateTtlAndLRU::new().await;
assert_eq!(pool.limit(), TestSize(10));
ttl_provider.set_expires_in(1, String::from("a"), Some(Duration::from_secs(1)));
ttl_provider.set_expires_in(2, String::from("b"), None);
ttl_provider.set_expires_in(3, String::from("c"), None);
size_estimator.mock_size(1, String::from("a"), TestSize(4));
size_estimator.mock_size(2, String::from("b"), TestSize(4));
size_estimator.mock_size(3, String::from("c"), TestSize(4));
backend.set(1, String::from("a"));
backend.set(2, String::from("b"));
assert_eq!(pool.current(), TestSize(8));
// evict
time_provider.inc(Duration::from_secs(1));
assert_eq!(backend.get(&1), None);
// now there's space for 3->"c"
assert_eq!(pool.current(), TestSize(4));
backend.set(3, String::from("c"));
assert_eq!(pool.current(), TestSize(8));
assert_eq!(backend.get(&1), None);
assert_eq!(backend.get(&2), Some(String::from("b")));
assert_eq!(backend.get(&3), Some(String::from("c")));
}
#[tokio::test]
async fn test_remove_if_check_does_not_extend_lifetime() {
let TestStateLruAndRemoveIf {
mut backend,
size_estimator,
time_provider,
remove_if_handle,
pool,
..
} = TestStateLruAndRemoveIf::new().await;
size_estimator.mock_size(1, String::from("a"), TestSize(4));
size_estimator.mock_size(2, String::from("b"), TestSize(4));
size_estimator.mock_size(3, String::from("c"), TestSize(4));
backend.set(1, String::from("a"));
pool.wait_converged().await;
time_provider.inc(Duration::from_secs(1));
backend.set(2, String::from("b"));
pool.wait_converged().await;
time_provider.inc(Duration::from_secs(1));
// Checking remove_if should not count as a "use" of 1
// for the "least recently used" calculation
remove_if_handle.remove_if(&1, |_| false);
backend.set(3, String::from("c"));
pool.wait_converged().await;
// adding "c" totals 12 size, but backend has room for only 10
// so "least recently used" (in this case 1, not 2) should be removed
assert_eq!(backend.get(&1), None);
assert!(backend.get(&2).is_some());
}
/// Test setup that integrates the TTL policy with a refresh.
struct TestStateTtlAndRefresh {
backend: PolicyBackend<u8, String>,
ttl_provider: Arc<TestTtlProvider>,
refresh_duration_provider: Arc<TestRefreshDurationProvider>,
time_provider: Arc<MockProvider>,
loader: Arc<TestLoader<u8, (), String>>,
notify_idle: Arc<Notify>,
}
impl TestStateTtlAndRefresh {
fn new() -> Self {
let refresh_duration_provider = Arc::new(TestRefreshDurationProvider::new());
let ttl_provider = Arc::new(TestTtlProvider::new());
let time_provider = Arc::new(MockProvider::new(Time::MIN));
let metric_registry = metric::Registry::new();
let loader = Arc::new(TestLoader::default());
let notify_idle = Arc::new(Notify::new());
// set up "RNG" that always generates the maximum, so we can test things easier
let rng_overwrite = StepRng::new(u64::MAX, 0);
let mut backend = PolicyBackend::hashmap_backed(Arc::clone(&time_provider) as _);
backend.add_policy(RefreshPolicy::new_inner(
Arc::clone(&time_provider) as _,
Arc::clone(&refresh_duration_provider) as _,
Arc::clone(&loader) as _,
"my_cache",
&metric_registry,
Arc::clone(¬ify_idle),
&Handle::current(),
Some(rng_overwrite),
));
backend.add_policy(TtlPolicy::new(
Arc::clone(&ttl_provider) as _,
"my_cache",
&metric_registry,
));
Self {
backend,
refresh_duration_provider,
ttl_provider,
time_provider,
loader,
notify_idle,
}
}
}
/// Test setup that integrates the LRU policy with a refresh.
struct TestStateLRUAndRefresh {
backend: PolicyBackend<u8, String>,
size_estimator: Arc<TestSizeEstimator>,
refresh_duration_provider: Arc<TestRefreshDurationProvider>,
time_provider: Arc<MockProvider>,
loader: Arc<TestLoader<u8, (), String>>,
pool: Arc<ResourcePool<TestSize>>,
notify_idle: Arc<Notify>,
}
impl TestStateLRUAndRefresh {
fn new() -> Self {
let refresh_duration_provider = Arc::new(TestRefreshDurationProvider::new());
let size_estimator = Arc::new(TestSizeEstimator::default());
let time_provider = Arc::new(MockProvider::new(Time::MIN));
let metric_registry = Arc::new(metric::Registry::new());
let loader = Arc::new(TestLoader::default());
let notify_idle = Arc::new(Notify::new());
// set up "RNG" that always generates the maximum, so we can test things easier
let rng_overwrite = StepRng::new(u64::MAX, 0);
let mut backend = PolicyBackend::hashmap_backed(Arc::clone(&time_provider) as _);
backend.add_policy(RefreshPolicy::new_inner(
Arc::clone(&time_provider) as _,
Arc::clone(&refresh_duration_provider) as _,
Arc::clone(&loader) as _,
"my_cache",
&metric_registry,
Arc::clone(¬ify_idle),
&Handle::current(),
Some(rng_overwrite),
));
let pool = Arc::new(ResourcePool::new(
"my_pool",
TestSize(10),
Arc::clone(&metric_registry),
&Handle::current(),
));
backend.add_policy(LruPolicy::new(
Arc::clone(&pool),
"my_cache",
Arc::clone(&size_estimator) as _,
));
Self {
backend,
refresh_duration_provider,
size_estimator,
time_provider,
loader,
pool,
notify_idle,
}
}
}
/// Test setup that integrates the TTL policy with LRU.
struct TestStateTtlAndLRU {
backend: PolicyBackend<u8, String>,
ttl_provider: Arc<TestTtlProvider>,
time_provider: Arc<MockProvider>,
size_estimator: Arc<TestSizeEstimator>,
pool: Arc<ResourcePool<TestSize>>,
}
impl TestStateTtlAndLRU {
async fn new() -> Self {
let ttl_provider = Arc::new(TestTtlProvider::new());
let time_provider = Arc::new(MockProvider::new(Time::MIN));
let metric_registry = Arc::new(metric::Registry::new());
let size_estimator = Arc::new(TestSizeEstimator::default());
let mut backend = PolicyBackend::hashmap_backed(Arc::clone(&time_provider) as _);
backend.add_policy(TtlPolicy::new(
Arc::clone(&ttl_provider) as _,
"my_cache",
&metric_registry,
));
let pool = Arc::new(ResourcePool::new(
"my_pool",
TestSize(10),
Arc::clone(&metric_registry),
&Handle::current(),
));
backend.add_policy(LruPolicy::new(
Arc::clone(&pool),
"my_cache",
Arc::clone(&size_estimator) as _,
));
Self {
backend,
ttl_provider,
time_provider,
size_estimator,
pool,
}
}
}
/// Test setup that integrates the LRU policy with RemoveIf and max size of 10
struct TestStateLruAndRemoveIf {
backend: PolicyBackend<u8, String>,
time_provider: Arc<MockProvider>,
size_estimator: Arc<TestSizeEstimator>,
remove_if_handle: RemoveIfHandle<u8, String>,
pool: Arc<ResourcePool<TestSize>>,
}
impl TestStateLruAndRemoveIf {
async fn new() -> Self {
let time_provider = Arc::new(MockProvider::new(Time::MIN));
let metric_registry = Arc::new(metric::Registry::new());
let size_estimator = Arc::new(TestSizeEstimator::default());
let mut backend = PolicyBackend::hashmap_backed(Arc::clone(&time_provider) as _);
let pool = Arc::new(ResourcePool::new(
"my_pool",
TestSize(10),
Arc::clone(&metric_registry),
&Handle::current(),
));
backend.add_policy(LruPolicy::new(
Arc::clone(&pool),
"my_cache",
Arc::clone(&size_estimator) as _,
));
let (constructor, remove_if_handle) =
RemoveIfPolicy::create_constructor_and_handle("my_cache", &metric_registry);
backend.add_policy(constructor);
Self {
backend,
time_provider,
size_estimator,
remove_if_handle,
pool,
}
}
}
/// Test setup that integrates the LRU policy with a refresh.
struct TestStateLruAndRefresh {
backend: PolicyBackend<u8, String>,
size_estimator: Arc<TestSizeEstimator>,
refresh_duration_provider: Arc<TestRefreshDurationProvider>,
time_provider: Arc<MockProvider>,
loader: Arc<TestLoader<u8, (), String>>,
notify_idle: Arc<Notify>,
pool: Arc<ResourcePool<TestSize>>,
}
impl TestStateLruAndRefresh {
fn new() -> Self {
let refresh_duration_provider = Arc::new(TestRefreshDurationProvider::new());
let size_estimator = Arc::new(TestSizeEstimator::default());
let time_provider = Arc::new(MockProvider::new(Time::MIN));
let metric_registry = Arc::new(metric::Registry::new());
let loader = Arc::new(TestLoader::default());
let notify_idle = Arc::new(Notify::new());
// set up "RNG" that always generates the maximum, so we can test things easier
let rng_overwrite = StepRng::new(u64::MAX, 0);
let mut backend = PolicyBackend::hashmap_backed(Arc::clone(&time_provider) as _);
backend.add_policy(RefreshPolicy::new_inner(
Arc::clone(&time_provider) as _,
Arc::clone(&refresh_duration_provider) as _,
Arc::clone(&loader) as _,
"my_cache",
&metric_registry,
Arc::clone(¬ify_idle),
&Handle::current(),
Some(rng_overwrite),
));
let pool = Arc::new(ResourcePool::new(
"my_pool",
TestSize(10),
Arc::clone(&metric_registry),
&Handle::current(),
));
backend.add_policy(LruPolicy::new(
Arc::clone(&pool),
"my_cache",
Arc::clone(&size_estimator) as _,
));
Self {
backend,
refresh_duration_provider,
size_estimator,
time_provider,
loader,
notify_idle,
pool,
}
}
}
#[derive(Debug, Default)]
struct TestSizeEstimator {
sizes: Mutex<HashMap<(u8, String), TestSize>>,
}
impl TestSizeEstimator {
fn mock_size(&self, k: u8, v: String, s: TestSize) {
self.sizes.lock().insert((k, v), s);
}
}
impl ResourceEstimator for TestSizeEstimator {
type K = u8;
type V = String;
type S = TestSize;
fn consumption(&self, k: &Self::K, v: &Self::V) -> Self::S {
*self.sizes.lock().get(&(*k, v.clone())).unwrap()
}
}
|
use crate::client::Client;
use crate::config::Config;
use crate::market::Market;
#[allow(clippy::all)]
pub enum API {
SerumRest(Rest),
SerumWebSocket(WebSocket),
}
pub enum Rest {
Pairs,
Trades(String),
AddressTrade(String),
AllRecentTrades,
Volumes(String),
OrderBooks(String),
}
pub enum WebSocket {
Socket,
Subscribe,
UnSubscribe,
}
impl From<API> for String {
fn from(item: API) -> Self {
match item {
API::SerumRest(route) => match route {
Rest::Pairs => "/pairs".to_string(),
Rest::Trades(market_name) => format!("{}{}", "/trades/", market_name),
Rest::AddressTrade(market_address) => {
format!("{}{}", "/trades/address/", market_address)
}
Rest::AllRecentTrades => "/trades/all/recent".to_string(),
Rest::Volumes(market_name) => format!("{}{}", "/volumes/", market_name),
Rest::OrderBooks(market_name) => format!("{}{}", "/orderbooks/", market_name),
},
API::SerumWebSocket(route) => String::from(match route {
WebSocket::Socket => "/ws",
WebSocket::UnSubscribe => "/unsubscribe",
WebSocket::Subscribe => "/subscribe",
}),
}
}
}
pub trait Bonfida {
fn new() -> Self;
fn new_with_config(config: &Config) -> Self;
}
impl Bonfida for Market {
fn new() -> Self {
Self::new_with_config(&Config::default())
}
fn new_with_config(config: &Config) -> Self {
Market {
client: Client::new(config.rest_api_endpoint.clone()),
}
}
}
|
use std::fmt;
use std::num;
use std::io;
use std::str::Utf8Error;
use std::string::FromUtf8Error;
use rmp::decode::{DecodeStringError, ValueReadError, MarkerReadError};
use rmp::encode::ValueWriteError;
#[derive(Debug)]
pub enum BsonErr {
ParseError(String),
ParseIntError(Box<num::ParseIntError>),
DecodeIntUnknownByte,
IOErr(Box<io::Error>),
UTF8Error(Box<Utf8Error>),
FromUTF8Error(Box<FromUtf8Error>),
TypeNotComparable(String, String),
RmpWriteError(Box<ValueWriteError>),
RmpReadError(Box<ValueReadError>),
RmpMarkerReadError(Box<MarkerReadError>),
DecodeStringErr(String),
}
pub mod parse_error_reason {
pub static OBJECT_ID_LEN: &str = "length of ObjectId should be 12";
pub static OBJECT_ID_HEX_DECODE_ERROR: &str = "decode error failed for ObjectID";
pub static UNEXPECTED_DOCUMENT_FLAG: &str = "unexpected flag for document";
pub static UNEXPECTED_PAGE_HEADER: &str = "unexpected page header";
pub static UNEXPECTED_PAGE_TYPE: &str = "unexpected page type";
pub static UNEXPECTED_HEADER_FOR_BTREE_PAGE: &str = "unexpected header for btree page";
pub static KEY_TY_SHOULD_NOT_BE_ZERO: &str = "type name of KEY should not be zero";
}
impl fmt::Display for BsonErr {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
BsonErr::ParseError(reason) => write!(f, "ParseError: {}", reason),
BsonErr::ParseIntError(parse_int_err) => parse_int_err.fmt(f),
BsonErr::DecodeIntUnknownByte => write!(f, "DecodeIntUnknownByte"),
BsonErr::IOErr(io_err) => std::fmt::Display::fmt(&io_err, f),
BsonErr::UTF8Error(utf8_err) => std::fmt::Display::fmt(&utf8_err, f),
BsonErr::TypeNotComparable(expected, actual) =>
write!(f, "TypeNotComparable(expected: {}, actual: {})", expected, actual),
BsonErr::FromUTF8Error(err) => write!(f, "{}", err),
BsonErr::RmpWriteError(err) => write!(f, "{}", err),
BsonErr::RmpReadError(err) => write!(f, "{}", err),
BsonErr::DecodeStringErr(err) => write!(f, "{}", err),
BsonErr::RmpMarkerReadError(_err) => write!(f, "RmpMarkerReadError"),
}
}
}
impl From<io::Error> for BsonErr {
fn from(error: io::Error) -> Self {
BsonErr::IOErr(Box::new(error))
}
}
impl From<Utf8Error> for BsonErr {
fn from(error: Utf8Error) -> Self {
BsonErr::UTF8Error(Box::new(error))
}
}
impl From<num::ParseIntError> for BsonErr {
fn from(error: num::ParseIntError) -> Self {
BsonErr::ParseIntError(Box::new(error))
}
}
impl From<FromUtf8Error> for BsonErr {
fn from(error: FromUtf8Error) -> Self {
BsonErr::FromUTF8Error(Box::new(error))
}
}
impl From<ValueWriteError> for BsonErr {
fn from(error: ValueWriteError) -> Self {
BsonErr::RmpWriteError(Box::new(error))
}
}
impl From<ValueReadError> for BsonErr {
fn from(error: ValueReadError) -> Self {
BsonErr::RmpReadError(Box::new(error))
}
}
impl<'a> From<DecodeStringError<'a>> for BsonErr {
fn from(err: DecodeStringError<'a>) -> Self {
BsonErr::DecodeStringErr(err.to_string())
}
}
impl From<MarkerReadError> for BsonErr {
fn from(err: MarkerReadError) -> Self {
BsonErr::RmpMarkerReadError(Box::new(err))
}
}
impl std::error::Error for BsonErr {
}
|
use core::fmt;
use crate::device::{ Device, UsingDevice };
use crate::command::{ FlushTx, ReadRxPayload, ReadRxPayloadWidth, WriteTxPayload };
use crate::rxtx::{ Received, SendReceiveResult };
use crate::registers::{ FifoStatus, Status };
use crate::config::Configuration;
/// In PTX mode, the device transmits packets immediately, and receives packets
/// only as acknowledge payloads. It's the complement to PRX mode
pub struct PtxMode<D: Device> {
device: D,
}
impl<D: Device> fmt::Debug for PtxMode<D> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "TxMode")
}
}
impl <D: Device> UsingDevice<D> for PtxMode<D> {
fn device(&mut self) -> &mut D {
&mut self.device
}
}
impl <D: Device> Configuration<D> for PtxMode<D> {
}
impl<D: Device> PtxMode<D> {
/// Send asynchronously
pub fn send_receive(
&mut self,
send: Option<&[u8]>
) -> Result<SendReceiveResult, D::Error> {
let (status, fifo_status) = self.device.read_register::<FifoStatus>()?;
let dropped = match status.max_rt() {
true => {
self.device.send_command(&FlushTx)?;
let mut clear_max_rt = Status(0);
clear_max_rt.set_max_rt(true);
self.device.write_register(clear_max_rt)?;
true
},
false => false
};
let sent = match (fifo_status.tx_full(), send) {
(true, _) => false,
(false, None) => false,
(false, Some(payload)) => {
self.device.send_command(&WriteTxPayload::new(payload))?;
self.device.ce_enable();
true
}
};
let received = match fifo_status.rx_empty() {
true => None,
false => {
let (_, payload_width) = self.device.send_command(&ReadRxPayloadWidth)?;
let (_, payload) = self.device.send_command(&ReadRxPayload::new(payload_width as usize))?;
Some(Received { pipe: status.rx_p_no(), payload: payload})
}
};
Ok(SendReceiveResult { sent, received, dropped })
}
}
impl<D: Device> PtxMode<D> {
/// Relies on everything being set up by `StandbyMode::ptx()`, from which it is called
pub(crate) fn new(device: D) -> Self {
PtxMode { device }
}
}
|
//! Command line options for running compactor
use super::main;
use crate::process_info::setup_metric_registry;
use clap_blocks::{
catalog_dsn::CatalogDsnConfig, compactor::CompactorConfig, object_store::make_object_store,
run_config::RunConfig,
};
use compactor::object_store::metrics::MetricsStore;
use iox_query::exec::{Executor, ExecutorConfig};
use iox_time::{SystemProvider, TimeProvider};
use ioxd_common::{
server_type::{CommonServerState, CommonServerStateError},
Service,
};
use ioxd_compactor::create_compactor_server_type;
use object_store::DynObjectStore;
use object_store_metrics::ObjectStoreMetrics;
use observability_deps::tracing::*;
use parquet_file::storage::{ParquetStorage, StorageId};
use std::num::NonZeroUsize;
use std::sync::Arc;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("Run: {0}")]
Run(#[from] main::Error),
#[error("Invalid config: {0}")]
InvalidConfig(#[from] CommonServerStateError),
#[error("Catalog error: {0}")]
Catalog(#[from] iox_catalog::interface::Error),
#[error("Catalog DSN error: {0}")]
CatalogDsn(#[from] clap_blocks::catalog_dsn::Error),
#[error("Cannot parse object store config: {0}")]
ObjectStoreParsing(#[from] clap_blocks::object_store::ParseError),
}
#[derive(Debug, clap::Parser)]
#[clap(
name = "run",
about = "Runs in compactor mode using the RPC write path",
long_about = "Run the IOx compactor server.\n\nThe configuration options below can be \
set either with the command line flags or with the specified environment \
variable. If there is a file named '.env' in the current working directory, \
it is sourced before loading the configuration.
Configuration is loaded from the following sources (highest precedence first):
- command line arguments
- user set environment variables
- .env file contents
- pre-configured default values"
)]
pub struct Config {
#[clap(flatten)]
pub(crate) run_config: RunConfig,
#[clap(flatten)]
pub(crate) catalog_dsn: CatalogDsnConfig,
#[clap(flatten)]
pub(crate) compactor_config: CompactorConfig,
}
pub async fn command(config: Config) -> Result<(), Error> {
let common_state = CommonServerState::from_config(config.run_config.clone())?;
let time_provider = Arc::new(SystemProvider::new()) as Arc<dyn TimeProvider>;
let metric_registry = setup_metric_registry();
let catalog = config
.catalog_dsn
.get_catalog("compactor", Arc::clone(&metric_registry))
.await?;
let object_store = make_object_store(config.run_config.object_store_config())
.map_err(Error::ObjectStoreParsing)?;
// Decorate the object store with a metric recorder.
let object_store: Arc<DynObjectStore> = Arc::new(ObjectStoreMetrics::new(
object_store,
Arc::clone(&time_provider),
&metric_registry,
));
let parquet_store_real = ParquetStorage::new(object_store, StorageId::from("iox"));
let parquet_store_scratchpad = ParquetStorage::new(
Arc::new(MetricsStore::new(
Arc::new(object_store::memory::InMemory::new()),
&metric_registry,
"scratchpad",
)),
StorageId::from("iox_scratchpad"),
);
let num_threads = config
.compactor_config
.query_exec_thread_count
.unwrap_or_else(|| {
NonZeroUsize::new(num_cpus::get().saturating_sub(1))
.unwrap_or_else(|| NonZeroUsize::new(1).unwrap())
});
info!(%num_threads, "using specified number of threads");
let exec = Arc::new(Executor::new_with_config(ExecutorConfig {
num_threads,
target_query_partitions: num_threads,
object_stores: [&parquet_store_real, &parquet_store_scratchpad]
.into_iter()
.map(|store| (store.id(), Arc::clone(store.object_store())))
.collect(),
metric_registry: Arc::clone(&metric_registry),
mem_pool_size: config.compactor_config.exec_mem_pool_bytes,
}));
let time_provider = Arc::new(SystemProvider::new());
let process_once = config.compactor_config.process_once;
let server_type = create_compactor_server_type(
&common_state,
Arc::clone(&metric_registry),
catalog,
parquet_store_real,
parquet_store_scratchpad,
exec,
time_provider,
config.compactor_config,
)
.await;
info!("starting compactor");
let services = vec![Service::create(server_type, common_state.run_config())];
let res = main::main(common_state, services, metric_registry).await;
match res {
Ok(()) => Ok(()),
// compactor is allowed to shut itself down
Err(main::Error::Wrapper {
source: _source @ ioxd_common::Error::LostServer,
}) if process_once => Ok(()),
Err(e) => Err(e.into()),
}
}
|
use std::iter::FromIterator;
use itertools::zip;
pub trait Metric<T> {
fn score(lhs: &T, rhs: &T) -> f32;
fn score_map(lhs: &T, rhs: &[T]) -> f32 {
let mut res = 0_f32;
for i in 0..rhs.len() {
let delta = Self::score(lhs, &rhs[i]);
res += delta * delta;
}
res.sqrt()
}
fn score_zip(lhs: &[T], rhs: &[T]) -> Vec<f32> {
Vec::from_iter(
zip(lhs.iter(), rhs.iter())
.map(|(a, b)| Self::score(a, b))
)
}
}
|
use crate::Transformer;
use lowlang_syntax::*;
use lowlang_syntax::visit::VisitorMut;
use std::collections::BTreeMap;
pub struct Inliner<'t> {
to_inline: BTreeMap<ItemId, Body<'t>>,
current_body: Option<*mut Body<'t>>,
current_block: Option<*mut Block<'t>>,
changed: bool,
}
impl<'t> Inliner<'t> {
pub fn new() -> Inliner<'t> {
Inliner {
to_inline: BTreeMap::new(),
current_body: None,
current_block: None,
changed: false,
}
}
#[inline]
fn body(&mut self) -> &mut Body<'t> {
unsafe { &mut *self.current_body.unwrap() }
}
#[inline]
fn block(&mut self) -> &mut Block<'t> {
unsafe { &mut *self.current_block.unwrap() }
}
}
impl<'t> Transformer<'t> for Inliner<'t> {
fn transform(&mut self, package: &mut Package<'t>) -> bool {
if self.to_inline.is_empty() {
for (id, body) in &package.bodies {
if body.attributes.inline {
self.to_inline.insert(*id, body.clone());
}
}
}
self.visit_package(package);
self.changed
}
fn reset(&mut self) {
self.current_body = None;
self.current_block = None;
self.changed = false;
}
}
impl<'t> VisitorMut<'t> for Inliner<'t> {
#[inline]
fn visit_body(&mut self, body: &mut Body<'t>) {
self.current_body = Some(body);
self.super_body(body);
}
#[inline]
fn visit_block(&mut self, block: &mut Block<'t>) {
self.current_block = Some(block);
self.super_block(block);
}
fn visit_term(&mut self, term: &mut Terminator<'t>) {
if let Terminator::Call(places, Operand::Constant(Const::FuncAddr(Addr::Id(proc), _)), args, target) = term {
if let Some(mut inlined) = self.to_inline.get(proc).cloned() {
let max_local = self.body().max_local_id();
let max_block = self.body().max_block_id();
let locals = inlined.locals.iter().map(|(id, _)| (*id, *id + max_local)).collect();
let rets = places.iter().zip(inlined.rets()).map(|(place, ret)| (ret.id, place.clone())).collect();
let args = args.iter().zip(inlined.args()).map(|(op, arg)| (arg.id, op.clone())).collect();
let blocks = inlined.blocks.iter().skip(1).map(|(id, _)| (*id, *id + max_block)).collect();
replace_ops(&mut inlined, args);
replace_places(&mut inlined, rets);
crate::vars::replace(&mut inlined, &locals);
replace_blocks(&mut inlined, blocks);
replace_returns(&mut inlined, *target);
let mut blocks = inlined.blocks.into_iter();
let (_, first) = blocks.next().unwrap();
self.block().stmts.extend(first.stmts);
self.block().term = first.term;
self.body().locals.extend(inlined.locals.into_iter().filter(|l| l.1.kind == LocalKind::Tmp || l.1.kind == LocalKind::Var));
self.body().blocks.extend(blocks.map(|(_, b)| (b.id, b)));
self.changed = true;
}
}
}
}
fn replace_ops<'t>(body: &mut Body<'t>, with: BTreeMap<LocalId, Operand<'t>>) {
struct Replacer<'t>(BTreeMap<LocalId, Operand<'t>>);
Replacer(with).visit_body(body);
impl<'t> VisitorMut<'t> for Replacer<'t> {
fn visit_op(&mut self, op: &mut Operand<'t>) {
match op {
Operand::Place(place) => {
match &place.base {
PlaceBase::Local(id) => if let Some(new) = self.0.get(id) {
if let Operand::Place(new) = new {
*place = place.merge(new);
} else {
*op = new.clone();
}
},
_ => {},
}
},
_ => {},
}
self.super_op(op);
}
}
}
fn replace_places(body: &mut Body, with: BTreeMap<LocalId, Place>) {
struct Replacer(BTreeMap<LocalId, Place>);
Replacer(with).visit_body(body);
impl<'t> VisitorMut<'t> for Replacer {
fn visit_place(&mut self, place: &mut Place) {
match &place.base {
PlaceBase::Local(id) => if let Some(new) = self.0.get(id) {
*place = place.merge(new);
},
_ => {},
}
self.super_place(place);
}
}
}
fn replace_blocks(body: &mut Body, with: BTreeMap<BlockId, BlockId>) {
struct Replacer(BTreeMap<BlockId, BlockId>);
Replacer(with).visit_body(body);
impl<'t> VisitorMut<'t> for Replacer {
fn visit_block(&mut self, block: &mut Block<'t>) {
if let Some(new) = self.0.get(&block.id) {
block.id = *new;
}
self.super_block(block);
}
fn visit_term(&mut self, term: &mut Terminator<'t>) {
match term {
Terminator::Jump(to) => if let Some(new) = self.0.get(to) {
*to = *new;
},
Terminator::Call(_, _, _, to) => if let Some(new) = self.0.get(to) {
*to = *new;
},
Terminator::Switch(_, _, tos) => {
for to in tos {
if let Some(new) = self.0.get(to) {
*to = *new;
}
}
},
_ => {},
}
}
}
}
fn replace_returns(body: &mut Body, target: BlockId) {
struct Replacer(BlockId);
Replacer(target).visit_body(body);
impl<'t> VisitorMut<'t> for Replacer {
fn visit_term(&mut self, term: &mut Terminator<'t>) {
if let Terminator::Return = term {
*term = Terminator::Jump(self.0);
}
}
}
}
|
extern crate sdl2;
extern crate rustfft;
extern crate num;
extern crate rand;
use num::complex::Complex;
use std::f64::consts::PI;
use std::f64;
use rand::Rng;
const DIMS: (usize, usize) = (400, 400);
struct Point {
pos: (i32, i32),
}
fn radians_to_rgb(rad: f64) -> (f64, f64, f64) {
//outputs values bounded from 0 to 1
(
((rad - PI/2.0).sin()).powf(2.0),
((rad - (4.0*PI/3.0) - PI/2.0).sin()).powf(2.0),
((rad - (2.0*PI/3.0) - PI/2.0).sin()).powf(2.0)
)
}
fn distance(p1: (f64, f64), p2: (f64, f64)) -> f64 {
((p1.0 - p2.0).powi(2) + (p1.1 - p2.1).powi(2)).powf(0.5)
}
fn add_point(point_list: &mut Vec<Point>, fft_in_buffer: &mut Vec<Complex<f64>>, x: i32, y: i32) {
point_list.push(Point {pos: (x, y)});
fft_in_buffer[(x + (y * DIMS.0 as i32)) as usize] = Complex::new(255.0, 0.0);
}
fn main() {
// set up all the SDL2 nonsense
let ctx = sdl2::init()
.expect("Couldn't initalize SDL2.");
let video_ctx = ctx.video()
.expect("Couldn't initalize SDL2 video context.");
let window = video_ctx.window("FFT Drawpad", DIMS.0 as u32, DIMS.1 as u32)
.position_centered()
.build()
.expect("Couldn't build SDL2 window.");
let mut canvas = window
.into_canvas()
.build()
.expect("Couldn't build SDL2 window canvas.");
let canvas_tex_creator = canvas
.texture_creator();
let mut streaming_tex = canvas_tex_creator
.create_texture_streaming(sdl2::pixels::PixelFormatEnum::RGB24, DIMS.0 as u32, DIMS.1 as u32)
.expect("Couldn't capture canvas for a streaming texture.");
// the main loop
let mut point_list: Vec<Point> = vec![];
let mut need_to_fft = false;
// set up the FFT stuff
let mut fft_in_buffer: Vec<Complex<f64>> = vec![Complex::new(0.0, 0.0); DIMS.0 * DIMS.1];
let mut fft_out_buffer: Vec<Complex<f64>> = vec![Complex::new(0.0, 0.0); DIMS.0 * DIMS.1];
let mut fft_render_buffer: Vec<Complex<f64>> = vec![Complex::new(0.0, 0.0); DIMS.0 * DIMS.1];
let mut conv_matrix: Vec<Complex<f64>> = vec![Complex::new(0.0, 0.0); DIMS.0 * DIMS.1];
for (index, value) in (&mut conv_matrix).into_iter().enumerate() {
let x: f64 = (index % DIMS.0) as f64;
let y: f64 = (index / DIMS.0) as f64;
let rad: f64 = distance((x, y), (DIMS.0 as f64 / 2.0, DIMS.1 as f64 / 2.0));
//https://www.desmos.com/calculator/f2cofzioy0
let inner_ring: f64 = -((4.0 - (rad / 10.0)).exp()) + 5.0;
let bounding_ring: f64 = 1.0 / (1.0 + (-10.0 + (rad / 5.0)).exp());
*value = Complex::new(
// MODIFY THIS LINE vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv
// the argument to the final powf is hwo strong the effect will be
inner_ring * bounding_ring,
//20.0 - ((rad / 16.0) - 10.0).powi(2),
// (if (distance((x, y), (DIMS.0 as f64 / 2.0, DIMS.1 as f64 / 2.0)) < 10.0) { -20.0 } else { 1.0 }),
// MODIFY THE ABOVE LINE ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
0.0
);
}
let mut plan = rustfft::FFTplanner::new(false);
let mut plan_inverse = rustfft::FFTplanner::new(true);
let fft = plan.plan_fft(DIMS.0 * DIMS.1);
let fft_inverse = plan_inverse.plan_fft(DIMS.0 * DIMS.1);
let mut conv_matrix_fft: Vec<Complex<f64>> = vec![Complex::new(0.0, 0.0); DIMS.0 * DIMS.1];
fft.process(&mut conv_matrix, &mut conv_matrix_fft);
'main : loop {
// take input
for event in ctx.event_pump().expect("wtf?").poll_iter() {
use sdl2::event::Event;
match event {
Event::MouseButtonDown{x, y, mouse_btn: sdl2::mouse::MouseButton::Left, ..} => {
add_point(&mut point_list, &mut fft_in_buffer, x, y);
need_to_fft = true;
}
Event::KeyDown{..} => {
// we're going to go through quite a process, but the gist of it is that we'll end up placing a point based on the fft_render_buffer
// We take a sample of 1000 random points and we sum up the magnitude of those points
// Then, we take a random number from 0 to the sum, and choose a point from the list bassed on that number
let mut point_sample: Vec<((i32, i32), f64)> = vec![];
for _ in 0..1000 {
let random_x = rand::thread_rng().gen_range(0, DIMS.0 as i32);
let random_y = rand::thread_rng().gen_range(0, DIMS.1 as i32);
let single_point = ((random_x, random_y), fft_render_buffer[(random_x + (random_y * DIMS.0 as i32)) as usize].re);
point_sample.push(single_point);
}
let sample_sum: f64 = point_sample.iter().fold(0.0, |acc, x| acc + x.1);
let sample_selection: f64 = rand::thread_rng().gen_range(0.0, sample_sum);
let mut running_sum: f64 = 0.0;
let mut final_point: ((i32, i32), f64) = ((0, 0), 0.0);
for running_point in point_sample {
running_sum += running_point.1;
if (running_sum > sample_selection) {
final_point = running_point;
break;
}
}
add_point(&mut point_list, &mut fft_in_buffer, (final_point.0).0, (final_point.0).1);
need_to_fft = true;
}
Event::Quit{..} => break 'main,
_ => (),
}
}
// PERFORM THE FFT ON WINDOW 0'S CONTENTS
// first, transform the data into something that the dft crate can understand
// that result is in fft_buffer -- which is already allocated
if need_to_fft {
need_to_fft = false;
// first save input vector
let fft_in_buffer_backup = fft_in_buffer.clone();
// perform the DFT
fft.process(&mut fft_in_buffer, &mut fft_out_buffer);
// and restore the input vector
fft_in_buffer = fft_in_buffer_backup;
// next, convolute the output buffer
for (index, value) in (&mut fft_out_buffer).into_iter().enumerate() {
*value *= conv_matrix_fft[index];
}
// perform the inverse transform
fft_inverse.process(&mut fft_out_buffer, &mut fft_render_buffer);
// reverse the render buffer to correct for the domain distortion of the DFT
let buffer_length = (&fft_render_buffer).len();
{
let (top, bottom) = fft_render_buffer.split_at_mut(buffer_length / 2);
top.swap_with_slice(bottom);
}
{
fft_render_buffer
.chunks_mut(DIMS.0)
.for_each(|chunk| {
let (left, right) = chunk.split_at_mut(DIMS.0 / 2);
left.swap_with_slice(right);
});
}
// find the max value in the FFT out buffer
let mut max_value: f64 = 0.0;
for value in &fft_render_buffer {
if value.norm().round() > max_value {
max_value = value.norm().round();
}
}
// copy the fft_render_buffer to the window's canvas streaming texture
streaming_tex.with_lock(None, |buffer: &mut [u8], _pitch: usize| {
for (index, value) in (&fft_render_buffer).into_iter().enumerate() {
let amplitude: f64 = value.re.floor(); // 0 to max_value
//let brightness: f64 = if amplitude > 0.0 { 256.0 * amplitude / max_value } else { 0.0 }; // 0 to 255
let brightness: f64 = 256.0 * amplitude / max_value; // 0 to 255
/*
let rgb: (f64, f64, f64) = radians_to_rgb(value.arg()); // all elements are 0 to 1
buffer[index * 3 ] = (brightness * rgb.0).floor() as u8;
buffer[index * 3 + 1] = (brightness * rgb.1).floor() as u8;
buffer[index * 3 + 2] = (brightness * rgb.2).floor() as u8;
*/
buffer[index * 3 ] = (brightness).floor() as u8;
buffer[index * 3 + 1] = (brightness).floor() as u8;
buffer[index * 3 + 2] = (brightness).floor() as u8;
}
}).expect("wtf?");
}
// update canvases from texture
canvas.clear();
canvas.copy(&streaming_tex, None, None).expect("wtf?");
for p in &point_list {
// draw the points
canvas.set_draw_color(sdl2::pixels::Color::RGB(255, 0, 0));
canvas.fill_rect(sdl2::rect::Rect::new(p.pos.0, p.pos.1, 5, 5));
}
canvas.present();
}
}
|
use std::ops;
use super::Vector3;
use super::Matrix4;
pub struct Quaternion {
pub x: f32,
pub y: f32,
pub z: f32,
pub w: f32,
}
impl Quaternion {
pub fn with_angle_axis(angle: f32, axis: &Vector3) -> Quaternion {
let half_angle = angle / 2.;
let s = half_angle.sin();
Quaternion {
x: axis.x * s,
y: axis.y * s,
z: axis.z * s,
w: half_angle.cos()
}
}
pub fn to_matrix(&self) -> Matrix4 {
let (x, y, z, w) = (self.x, self.y, self.z, self.w);
let (x2, y2, z2) = (x * 2., y * 2., z * 2.);
let (xx, xy, xz) = (x * x2, x * y2, x * z2);
let (yy, yz, zz) = (y * y2, y * z2, z * z2);
let (wx, wy, wz) = (w * x2, w * y2, w * z2);
let mut m: [f32; 16] = [0.; 16];
m[ 0 ] = 1. - ( yy + zz );
m[ 4 ] = xy - wz;
m[ 8 ] = xz + wy;
m[ 1 ] = xy + wz;
m[ 5 ] = 1. - ( xx + zz );
m[ 9 ] = yz - wx;
m[ 2 ] = xz - wy;
m[ 6 ] = yz + wx;
m[ 10 ] = 1. - ( xx + yy );
m[ 3 ] = 0.;
m[ 7 ] = 0.;
m[ 11 ] = 0.;
m[ 12 ] = 0.;
m[ 13 ] = 0.;
m[ 14 ] = 0.;
m[ 15 ] = 1.;
Matrix4 { m }
}
pub fn transform(&self, v: &Vector3) -> Vector3 {
let (x, y, z) = (v.x, v.y, v.z);
let (qx, qy, qz, qw) = (self.x, self.y, self.z, self.w);
// Calculate quaternion * vector.
let ix = qw * x + qy * z - qz * y;
let iy = qw * y + qz * x - qx * z;
let iz = qw * z + qx * y - qy * x;
let iw = -qx * x - qy * y - qz * z;
// Calculate result * inverse quaternion.
let rx = ix * qw + iw * -qx + iy * -qz - iz * -qy;
let ry = iy * qw + iw * -qy + iz * -qx - ix * -qz;
let rz = iz * qw + iw * -qz + ix * -qy - iy * -qx;
Vector3::new(rx, ry, rz)
}
}
impl ops::Mul<Self> for Quaternion {
type Output = Self;
fn mul(self, rhs: Quaternion) -> Quaternion {
let (qax, qay, qaz, qaw) = (self.x, self.y, self.z, self.w);
let (qbx, qby, qbz, qbw) = (rhs.x, rhs.y, rhs.z, rhs.w);
let x = qax * qbw + qaw * qbx + qay * qbz - qaz * qby;
let y = qay * qbw + qaw * qby + qaz * qbx - qax * qbz;
let z = qaz * qbw + qaw * qbz + qax * qby - qay * qbx;
let w = qaw * qbw - qax * qbx - qay * qby - qaz * qbz;
Quaternion { x, y, z, w }
}
}
|
// auto generated, do not modify.
// created: Mon Feb 22 23:57:02 2016
// src-file: /QtWidgets/qgraphicsscene.h
// dst-file: /src/widgets/qgraphicsscene.rs
//
// header block begin =>
#![feature(libc)]
#![feature(core)]
#![feature(collections)]
extern crate libc;
use self::libc::*;
// <= header block end
// main block begin =>
// <= main block end
// use block begin =>
use super::super::core::qobject::*; // 771
use std::ops::Deref;
use super::super::gui::qbrush::*; // 771
use super::super::core::qrect::*; // 771
use super::super::gui::qpainterpath::*; // 771
use super::super::gui::qtransform::*; // 771
use super::qgraphicsitem::*; // 773
use super::super::core::qcoreevent::*; // 771
use super::super::core::qpoint::*; // 771
use super::super::gui::qpolygon::*; // 771
use super::super::gui::qpen::*; // 771
use super::super::core::qline::*; // 771
use super::super::gui::qpalette::*; // 771
use super::super::gui::qpainter::*; // 771
use super::super::core::qobjectdefs::*; // 771
use super::super::core::qstring::*; // 771
use super::super::gui::qfont::*; // 771
use super::qgraphicswidget::*; // 773
// use super::qlist::*; // 775
use super::super::gui::qpixmap::*; // 771
use super::qstyle::*; // 773
use super::qwidget::*; // 773
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QGraphicsScene_Class_Size() -> c_int;
// proto: void QGraphicsScene::setForegroundBrush(const QBrush & brush);
fn C_ZN14QGraphicsScene18setForegroundBrushERK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QGraphicsScene::setSceneRect(const QRectF & rect);
fn C_ZN14QGraphicsScene12setSceneRectERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: bool QGraphicsScene::isActive();
fn C_ZNK14QGraphicsScene8isActiveEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: bool QGraphicsScene::hasFocus();
fn C_ZNK14QGraphicsScene8hasFocusEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: QRectF QGraphicsScene::itemsBoundingRect();
fn C_ZNK14QGraphicsScene17itemsBoundingRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QGraphicsScene::sendEvent(QGraphicsItem * item, QEvent * event);
fn C_ZN14QGraphicsScene9sendEventEP13QGraphicsItemP6QEvent(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> c_char;
// proto: qreal QGraphicsScene::minimumRenderSize();
fn C_ZNK14QGraphicsScene17minimumRenderSizeEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: QPainterPath QGraphicsScene::selectionArea();
fn C_ZNK14QGraphicsScene13selectionAreaEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsScene::update(const QRectF & rect);
fn C_ZN14QGraphicsScene6updateERK6QRectF(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QGraphicsPolygonItem * QGraphicsScene::addPolygon(const QPolygonF & polygon, const QPen & pen, const QBrush & brush);
fn C_ZN14QGraphicsScene10addPolygonERK9QPolygonFRK4QPenRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
// proto: QGraphicsLineItem * QGraphicsScene::addLine(const QLineF & line, const QPen & pen);
fn C_ZN14QGraphicsScene7addLineERK6QLineFRK4QPen(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: QPalette QGraphicsScene::palette();
fn C_ZNK14QGraphicsScene7paletteEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: bool QGraphicsScene::isSortCacheEnabled();
fn C_ZNK14QGraphicsScene18isSortCacheEnabledEv(qthis: u64 /* *mut c_void*/) -> c_char;
// proto: void QGraphicsScene::QGraphicsScene(const QRectF & sceneRect, QObject * parent);
fn C_ZN14QGraphicsSceneC2ERK6QRectFP7QObject(arg0: *mut c_void, arg1: *mut c_void) -> u64;
// proto: void QGraphicsScene::QGraphicsScene(QObject * parent);
fn C_ZN14QGraphicsSceneC2EP7QObject(arg0: *mut c_void) -> u64;
// proto: void QGraphicsScene::clearFocus();
fn C_ZN14QGraphicsScene10clearFocusEv(qthis: u64 /* *mut c_void*/);
// proto: const QMetaObject * QGraphicsScene::metaObject();
fn C_ZNK14QGraphicsScene10metaObjectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QGraphicsSimpleTextItem * QGraphicsScene::addSimpleText(const QString & text, const QFont & font);
fn C_ZN14QGraphicsScene13addSimpleTextERK7QStringRK5QFont(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: QGraphicsLineItem * QGraphicsScene::addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen & pen);
fn C_ZN14QGraphicsScene7addLineEddddRK4QPen(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: *mut c_void) -> *mut c_void;
// proto: void QGraphicsScene::setBspTreeDepth(int depth);
fn C_ZN14QGraphicsScene15setBspTreeDepthEi(qthis: u64 /* *mut c_void*/, arg0: c_int);
// proto: QRectF QGraphicsScene::sceneRect();
fn C_ZNK14QGraphicsScene9sceneRectEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QGraphicsWidget * QGraphicsScene::activeWindow();
fn C_ZNK14QGraphicsScene12activeWindowEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QBrush QGraphicsScene::backgroundBrush();
fn C_ZNK14QGraphicsScene15backgroundBrushEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QGraphicsItem * QGraphicsScene::itemAt(qreal x, qreal y, const QTransform & deviceTransform);
fn C_ZNK14QGraphicsScene6itemAtEddRK10QTransform(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: *mut c_void) -> *mut c_void;
// proto: void QGraphicsScene::advance();
fn C_ZN14QGraphicsScene7advanceEv(qthis: u64 /* *mut c_void*/);
// proto: void QGraphicsScene::setStickyFocus(bool enabled);
fn C_ZN14QGraphicsScene14setStickyFocusEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QList<QGraphicsItem *> QGraphicsScene::selectedItems();
fn C_ZNK14QGraphicsScene13selectedItemsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsScene::clear();
fn C_ZN14QGraphicsScene5clearEv(qthis: u64 /* *mut c_void*/);
// proto: void QGraphicsScene::setActivePanel(QGraphicsItem * item);
fn C_ZN14QGraphicsScene14setActivePanelEP13QGraphicsItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QGraphicsPixmapItem * QGraphicsScene::addPixmap(const QPixmap & pixmap);
fn C_ZN14QGraphicsScene9addPixmapERK7QPixmap(qthis: u64 /* *mut c_void*/, arg0: *mut c_void) -> *mut c_void;
// proto: QBrush QGraphicsScene::foregroundBrush();
fn C_ZNK14QGraphicsScene15foregroundBrushEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QList<QGraphicsView *> QGraphicsScene::views();
fn C_ZNK14QGraphicsScene5viewsEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsScene::~QGraphicsScene();
fn C_ZN14QGraphicsSceneD2Ev(qthis: u64 /* *mut c_void*/);
// proto: QGraphicsRectItem * QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen & pen, const QBrush & brush);
fn C_ZN14QGraphicsScene7addRectEddddRK4QPenRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: *mut c_void, arg5: *mut c_void) -> *mut c_void;
// proto: int QGraphicsScene::bspTreeDepth();
fn C_ZNK14QGraphicsScene12bspTreeDepthEv(qthis: u64 /* *mut c_void*/) -> c_int;
// proto: void QGraphicsScene::setSceneRect(qreal x, qreal y, qreal w, qreal h);
fn C_ZN14QGraphicsScene12setSceneRectEdddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double);
// proto: void QGraphicsScene::setStyle(QStyle * style);
fn C_ZN14QGraphicsScene8setStyleEP6QStyle(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QGraphicsScene::setPalette(const QPalette & palette);
fn C_ZN14QGraphicsScene10setPaletteERK8QPalette(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QGraphicsScene::setMinimumRenderSize(qreal minSize);
fn C_ZN14QGraphicsScene20setMinimumRenderSizeEd(qthis: u64 /* *mut c_void*/, arg0: c_double);
// proto: void QGraphicsScene::QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject * parent);
fn C_ZN14QGraphicsSceneC2EddddP7QObject(arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: *mut c_void) -> u64;
// proto: QGraphicsItem * QGraphicsScene::mouseGrabberItem();
fn C_ZNK14QGraphicsScene16mouseGrabberItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QGraphicsRectItem * QGraphicsScene::addRect(const QRectF & rect, const QPen & pen, const QBrush & brush);
fn C_ZN14QGraphicsScene7addRectERK6QRectFRK4QPenRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
// proto: QGraphicsEllipseItem * QGraphicsScene::addEllipse(const QRectF & rect, const QPen & pen, const QBrush & brush);
fn C_ZN14QGraphicsScene10addEllipseERK6QRectFRK4QPenRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
// proto: qreal QGraphicsScene::height();
fn C_ZNK14QGraphicsScene6heightEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QGraphicsScene::setSelectionArea(const QPainterPath & path, const QTransform & deviceTransform);
fn C_ZN14QGraphicsScene16setSelectionAreaERK12QPainterPathRK10QTransform(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void);
// proto: QFont QGraphicsScene::font();
fn C_ZNK14QGraphicsScene4fontEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsScene::clearSelection();
fn C_ZN14QGraphicsScene14clearSelectionEv(qthis: u64 /* *mut c_void*/);
// proto: void QGraphicsScene::removeItem(QGraphicsItem * item);
fn C_ZN14QGraphicsScene10removeItemEP13QGraphicsItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QGraphicsEllipseItem * QGraphicsScene::addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen & pen, const QBrush & brush);
fn C_ZN14QGraphicsScene10addEllipseEddddRK4QPenRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double, arg4: *mut c_void, arg5: *mut c_void) -> *mut c_void;
// proto: void QGraphicsScene::setActiveWindow(QGraphicsWidget * widget);
fn C_ZN14QGraphicsScene15setActiveWindowEP15QGraphicsWidget(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QGraphicsItem * QGraphicsScene::focusItem();
fn C_ZNK14QGraphicsScene9focusItemEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QGraphicsTextItem * QGraphicsScene::addText(const QString & text, const QFont & font);
fn C_ZN14QGraphicsScene7addTextERK7QStringRK5QFont(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QGraphicsScene::setSortCacheEnabled(bool enabled);
fn C_ZN14QGraphicsScene19setSortCacheEnabledEb(qthis: u64 /* *mut c_void*/, arg0: c_char);
// proto: QGraphicsItem * QGraphicsScene::itemAt(const QPointF & pos, const QTransform & deviceTransform);
fn C_ZNK14QGraphicsScene6itemAtERK7QPointFRK10QTransform(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void) -> *mut c_void;
// proto: void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup * group);
fn C_ZN14QGraphicsScene16destroyItemGroupEP18QGraphicsItemGroup(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: qreal QGraphicsScene::width();
fn C_ZNK14QGraphicsScene5widthEv(qthis: u64 /* *mut c_void*/) -> c_double;
// proto: void QGraphicsScene::update(qreal x, qreal y, qreal w, qreal h);
fn C_ZN14QGraphicsScene6updateEdddd(qthis: u64 /* *mut c_void*/, arg0: c_double, arg1: c_double, arg2: c_double, arg3: c_double);
// proto: void QGraphicsScene::addItem(QGraphicsItem * item);
fn C_ZN14QGraphicsScene7addItemEP13QGraphicsItem(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QGraphicsScene::setBackgroundBrush(const QBrush & brush);
fn C_ZN14QGraphicsScene18setBackgroundBrushERK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QGraphicsItem * QGraphicsScene::activePanel();
fn C_ZNK14QGraphicsScene11activePanelEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: QStyle * QGraphicsScene::style();
fn C_ZNK14QGraphicsScene5styleEv(qthis: u64 /* *mut c_void*/) -> *mut c_void;
// proto: void QGraphicsScene::setFont(const QFont & font);
fn C_ZN14QGraphicsScene7setFontERK5QFont(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: QGraphicsPathItem * QGraphicsScene::addPath(const QPainterPath & path, const QPen & pen, const QBrush & brush);
fn C_ZN14QGraphicsScene7addPathERK12QPainterPathRK4QPenRK6QBrush(qthis: u64 /* *mut c_void*/, arg0: *mut c_void, arg1: *mut c_void, arg2: *mut c_void) -> *mut c_void;
// proto: bool QGraphicsScene::stickyFocus();
fn C_ZNK14QGraphicsScene11stickyFocusEv(qthis: u64 /* *mut c_void*/) -> c_char;
fn QGraphicsScene_SlotProxy_connect__ZN14QGraphicsScene16selectionChangedEv(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
fn QGraphicsScene_SlotProxy_connect__ZN14QGraphicsScene16sceneRectChangedERK6QRectF(qthis: *mut c_void, ffifptr: *mut c_void, rsfptr: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QGraphicsScene)=1
#[derive(Default)]
pub struct QGraphicsScene {
qbase: QObject,
pub qclsinst: u64 /* *mut c_void*/,
pub _changed: QGraphicsScene_changed_signal,
pub _sceneRectChanged: QGraphicsScene_sceneRectChanged_signal,
pub _selectionChanged: QGraphicsScene_selectionChanged_signal,
pub _focusItemChanged: QGraphicsScene_focusItemChanged_signal,
}
impl /*struct*/ QGraphicsScene {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QGraphicsScene {
return QGraphicsScene{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QGraphicsScene {
type Target = QObject;
fn deref(&self) -> &QObject {
return & self.qbase;
}
}
impl AsRef<QObject> for QGraphicsScene {
fn as_ref(& self) -> & QObject {
return & self.qbase;
}
}
// proto: void QGraphicsScene::setForegroundBrush(const QBrush & brush);
impl /*struct*/ QGraphicsScene {
pub fn setForegroundBrush<RetType, T: QGraphicsScene_setForegroundBrush<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setForegroundBrush(self);
// return 1;
}
}
pub trait QGraphicsScene_setForegroundBrush<RetType> {
fn setForegroundBrush(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setForegroundBrush(const QBrush & brush);
impl<'a> /*trait*/ QGraphicsScene_setForegroundBrush<()> for (&'a QBrush) {
fn setForegroundBrush(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene18setForegroundBrushERK6QBrush()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene18setForegroundBrushERK6QBrush(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsScene::setSceneRect(const QRectF & rect);
impl /*struct*/ QGraphicsScene {
pub fn setSceneRect<RetType, T: QGraphicsScene_setSceneRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSceneRect(self);
// return 1;
}
}
pub trait QGraphicsScene_setSceneRect<RetType> {
fn setSceneRect(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setSceneRect(const QRectF & rect);
impl<'a> /*trait*/ QGraphicsScene_setSceneRect<()> for (&'a QRectF) {
fn setSceneRect(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene12setSceneRectERK6QRectF()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene12setSceneRectERK6QRectF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: bool QGraphicsScene::isActive();
impl /*struct*/ QGraphicsScene {
pub fn isActive<RetType, T: QGraphicsScene_isActive<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isActive(self);
// return 1;
}
}
pub trait QGraphicsScene_isActive<RetType> {
fn isActive(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: bool QGraphicsScene::isActive();
impl<'a> /*trait*/ QGraphicsScene_isActive<i8> for () {
fn isActive(self , rsthis: & QGraphicsScene) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene8isActiveEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene8isActiveEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: bool QGraphicsScene::hasFocus();
impl /*struct*/ QGraphicsScene {
pub fn hasFocus<RetType, T: QGraphicsScene_hasFocus<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.hasFocus(self);
// return 1;
}
}
pub trait QGraphicsScene_hasFocus<RetType> {
fn hasFocus(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: bool QGraphicsScene::hasFocus();
impl<'a> /*trait*/ QGraphicsScene_hasFocus<i8> for () {
fn hasFocus(self , rsthis: & QGraphicsScene) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene8hasFocusEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene8hasFocusEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: QRectF QGraphicsScene::itemsBoundingRect();
impl /*struct*/ QGraphicsScene {
pub fn itemsBoundingRect<RetType, T: QGraphicsScene_itemsBoundingRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.itemsBoundingRect(self);
// return 1;
}
}
pub trait QGraphicsScene_itemsBoundingRect<RetType> {
fn itemsBoundingRect(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QRectF QGraphicsScene::itemsBoundingRect();
impl<'a> /*trait*/ QGraphicsScene_itemsBoundingRect<QRectF> for () {
fn itemsBoundingRect(self , rsthis: & QGraphicsScene) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene17itemsBoundingRectEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene17itemsBoundingRectEv(rsthis.qclsinst)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QGraphicsScene::sendEvent(QGraphicsItem * item, QEvent * event);
impl /*struct*/ QGraphicsScene {
pub fn sendEvent<RetType, T: QGraphicsScene_sendEvent<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sendEvent(self);
// return 1;
}
}
pub trait QGraphicsScene_sendEvent<RetType> {
fn sendEvent(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: bool QGraphicsScene::sendEvent(QGraphicsItem * item, QEvent * event);
impl<'a> /*trait*/ QGraphicsScene_sendEvent<i8> for (&'a QGraphicsItem, &'a QEvent) {
fn sendEvent(self , rsthis: & QGraphicsScene) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene9sendEventEP13QGraphicsItemP6QEvent()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene9sendEventEP13QGraphicsItemP6QEvent(rsthis.qclsinst, arg0, arg1)};
return ret as i8; // 1
// return 1;
}
}
// proto: qreal QGraphicsScene::minimumRenderSize();
impl /*struct*/ QGraphicsScene {
pub fn minimumRenderSize<RetType, T: QGraphicsScene_minimumRenderSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.minimumRenderSize(self);
// return 1;
}
}
pub trait QGraphicsScene_minimumRenderSize<RetType> {
fn minimumRenderSize(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: qreal QGraphicsScene::minimumRenderSize();
impl<'a> /*trait*/ QGraphicsScene_minimumRenderSize<f64> for () {
fn minimumRenderSize(self , rsthis: & QGraphicsScene) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene17minimumRenderSizeEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene17minimumRenderSizeEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: QPainterPath QGraphicsScene::selectionArea();
impl /*struct*/ QGraphicsScene {
pub fn selectionArea<RetType, T: QGraphicsScene_selectionArea<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.selectionArea(self);
// return 1;
}
}
pub trait QGraphicsScene_selectionArea<RetType> {
fn selectionArea(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QPainterPath QGraphicsScene::selectionArea();
impl<'a> /*trait*/ QGraphicsScene_selectionArea<QPainterPath> for () {
fn selectionArea(self , rsthis: & QGraphicsScene) -> QPainterPath {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene13selectionAreaEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene13selectionAreaEv(rsthis.qclsinst)};
let mut ret1 = QPainterPath::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScene::update(const QRectF & rect);
impl /*struct*/ QGraphicsScene {
pub fn update<RetType, T: QGraphicsScene_update<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.update(self);
// return 1;
}
}
pub trait QGraphicsScene_update<RetType> {
fn update(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::update(const QRectF & rect);
impl<'a> /*trait*/ QGraphicsScene_update<()> for (Option<&'a QRectF>) {
fn update(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene6updateERK6QRectF()};
let arg0 = (if self.is_none() {QRectF::new(()).qclsinst} else {self.unwrap().qclsinst}) as *mut c_void;
unsafe {C_ZN14QGraphicsScene6updateERK6QRectF(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QGraphicsPolygonItem * QGraphicsScene::addPolygon(const QPolygonF & polygon, const QPen & pen, const QBrush & brush);
impl /*struct*/ QGraphicsScene {
pub fn addPolygon<RetType, T: QGraphicsScene_addPolygon<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addPolygon(self);
// return 1;
}
}
pub trait QGraphicsScene_addPolygon<RetType> {
fn addPolygon(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsPolygonItem * QGraphicsScene::addPolygon(const QPolygonF & polygon, const QPen & pen, const QBrush & brush);
impl<'a> /*trait*/ QGraphicsScene_addPolygon<QGraphicsPolygonItem> for (&'a QPolygonF, Option<&'a QPen>, Option<&'a QBrush>) {
fn addPolygon(self , rsthis: & QGraphicsScene) -> QGraphicsPolygonItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene10addPolygonERK9QPolygonFRK4QPenRK6QBrush()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QPen::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let arg2 = (if self.2.is_none() {QBrush::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene10addPolygonERK9QPolygonFRK4QPenRK6QBrush(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QGraphicsPolygonItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QGraphicsLineItem * QGraphicsScene::addLine(const QLineF & line, const QPen & pen);
impl /*struct*/ QGraphicsScene {
pub fn addLine<RetType, T: QGraphicsScene_addLine<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addLine(self);
// return 1;
}
}
pub trait QGraphicsScene_addLine<RetType> {
fn addLine(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsLineItem * QGraphicsScene::addLine(const QLineF & line, const QPen & pen);
impl<'a> /*trait*/ QGraphicsScene_addLine<QGraphicsLineItem> for (&'a QLineF, Option<&'a QPen>) {
fn addLine(self , rsthis: & QGraphicsScene) -> QGraphicsLineItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene7addLineERK6QLineFRK4QPen()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QPen::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene7addLineERK6QLineFRK4QPen(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QGraphicsLineItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QPalette QGraphicsScene::palette();
impl /*struct*/ QGraphicsScene {
pub fn palette<RetType, T: QGraphicsScene_palette<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.palette(self);
// return 1;
}
}
pub trait QGraphicsScene_palette<RetType> {
fn palette(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QPalette QGraphicsScene::palette();
impl<'a> /*trait*/ QGraphicsScene_palette<QPalette> for () {
fn palette(self , rsthis: & QGraphicsScene) -> QPalette {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene7paletteEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene7paletteEv(rsthis.qclsinst)};
let mut ret1 = QPalette::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QGraphicsScene::isSortCacheEnabled();
impl /*struct*/ QGraphicsScene {
pub fn isSortCacheEnabled<RetType, T: QGraphicsScene_isSortCacheEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.isSortCacheEnabled(self);
// return 1;
}
}
pub trait QGraphicsScene_isSortCacheEnabled<RetType> {
fn isSortCacheEnabled(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: bool QGraphicsScene::isSortCacheEnabled();
impl<'a> /*trait*/ QGraphicsScene_isSortCacheEnabled<i8> for () {
fn isSortCacheEnabled(self , rsthis: & QGraphicsScene) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene18isSortCacheEnabledEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene18isSortCacheEnabledEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
// proto: void QGraphicsScene::QGraphicsScene(const QRectF & sceneRect, QObject * parent);
impl /*struct*/ QGraphicsScene {
pub fn new<T: QGraphicsScene_new>(value: T) -> QGraphicsScene {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QGraphicsScene_new {
fn new(self) -> QGraphicsScene;
}
// proto: void QGraphicsScene::QGraphicsScene(const QRectF & sceneRect, QObject * parent);
impl<'a> /*trait*/ QGraphicsScene_new for (&'a QRectF, Option<&'a QObject>) {
fn new(self) -> QGraphicsScene {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsSceneC2ERK6QRectFP7QObject()};
let ctysz: c_int = unsafe{QGraphicsScene_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {0} else {self.1.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN14QGraphicsSceneC2ERK6QRectFP7QObject(arg0, arg1)};
let rsthis = QGraphicsScene{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QGraphicsScene::QGraphicsScene(QObject * parent);
impl<'a> /*trait*/ QGraphicsScene_new for (Option<&'a QObject>) {
fn new(self) -> QGraphicsScene {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsSceneC2EP7QObject()};
let ctysz: c_int = unsafe{QGraphicsScene_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = (if self.is_none() {0} else {self.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN14QGraphicsSceneC2EP7QObject(arg0)};
let rsthis = QGraphicsScene{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QGraphicsScene::clearFocus();
impl /*struct*/ QGraphicsScene {
pub fn clearFocus<RetType, T: QGraphicsScene_clearFocus<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clearFocus(self);
// return 1;
}
}
pub trait QGraphicsScene_clearFocus<RetType> {
fn clearFocus(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::clearFocus();
impl<'a> /*trait*/ QGraphicsScene_clearFocus<()> for () {
fn clearFocus(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene10clearFocusEv()};
unsafe {C_ZN14QGraphicsScene10clearFocusEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: const QMetaObject * QGraphicsScene::metaObject();
impl /*struct*/ QGraphicsScene {
pub fn metaObject<RetType, T: QGraphicsScene_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QGraphicsScene_metaObject<RetType> {
fn metaObject(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: const QMetaObject * QGraphicsScene::metaObject();
impl<'a> /*trait*/ QGraphicsScene_metaObject<QMetaObject> for () {
fn metaObject(self , rsthis: & QGraphicsScene) -> QMetaObject {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene10metaObjectEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene10metaObjectEv(rsthis.qclsinst)};
let mut ret1 = QMetaObject::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QGraphicsSimpleTextItem * QGraphicsScene::addSimpleText(const QString & text, const QFont & font);
impl /*struct*/ QGraphicsScene {
pub fn addSimpleText<RetType, T: QGraphicsScene_addSimpleText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addSimpleText(self);
// return 1;
}
}
pub trait QGraphicsScene_addSimpleText<RetType> {
fn addSimpleText(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsSimpleTextItem * QGraphicsScene::addSimpleText(const QString & text, const QFont & font);
impl<'a> /*trait*/ QGraphicsScene_addSimpleText<QGraphicsSimpleTextItem> for (&'a QString, Option<&'a QFont>) {
fn addSimpleText(self , rsthis: & QGraphicsScene) -> QGraphicsSimpleTextItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene13addSimpleTextERK7QStringRK5QFont()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QFont::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene13addSimpleTextERK7QStringRK5QFont(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QGraphicsSimpleTextItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QGraphicsLineItem * QGraphicsScene::addLine(qreal x1, qreal y1, qreal x2, qreal y2, const QPen & pen);
impl<'a> /*trait*/ QGraphicsScene_addLine<QGraphicsLineItem> for (f64, f64, f64, f64, Option<&'a QPen>) {
fn addLine(self , rsthis: & QGraphicsScene) -> QGraphicsLineItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene7addLineEddddRK4QPen()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
let arg4 = (if self.4.is_none() {QPen::new(()).qclsinst} else {self.4.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene7addLineEddddRK4QPen(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4)};
let mut ret1 = QGraphicsLineItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScene::setBspTreeDepth(int depth);
impl /*struct*/ QGraphicsScene {
pub fn setBspTreeDepth<RetType, T: QGraphicsScene_setBspTreeDepth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBspTreeDepth(self);
// return 1;
}
}
pub trait QGraphicsScene_setBspTreeDepth<RetType> {
fn setBspTreeDepth(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setBspTreeDepth(int depth);
impl<'a> /*trait*/ QGraphicsScene_setBspTreeDepth<()> for (i32) {
fn setBspTreeDepth(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene15setBspTreeDepthEi()};
let arg0 = self as c_int;
unsafe {C_ZN14QGraphicsScene15setBspTreeDepthEi(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QRectF QGraphicsScene::sceneRect();
impl /*struct*/ QGraphicsScene {
pub fn sceneRect<RetType, T: QGraphicsScene_sceneRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.sceneRect(self);
// return 1;
}
}
pub trait QGraphicsScene_sceneRect<RetType> {
fn sceneRect(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QRectF QGraphicsScene::sceneRect();
impl<'a> /*trait*/ QGraphicsScene_sceneRect<QRectF> for () {
fn sceneRect(self , rsthis: & QGraphicsScene) -> QRectF {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene9sceneRectEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene9sceneRectEv(rsthis.qclsinst)};
let mut ret1 = QRectF::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QGraphicsWidget * QGraphicsScene::activeWindow();
impl /*struct*/ QGraphicsScene {
pub fn activeWindow<RetType, T: QGraphicsScene_activeWindow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.activeWindow(self);
// return 1;
}
}
pub trait QGraphicsScene_activeWindow<RetType> {
fn activeWindow(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsWidget * QGraphicsScene::activeWindow();
impl<'a> /*trait*/ QGraphicsScene_activeWindow<QGraphicsWidget> for () {
fn activeWindow(self , rsthis: & QGraphicsScene) -> QGraphicsWidget {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene12activeWindowEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene12activeWindowEv(rsthis.qclsinst)};
let mut ret1 = QGraphicsWidget::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QBrush QGraphicsScene::backgroundBrush();
impl /*struct*/ QGraphicsScene {
pub fn backgroundBrush<RetType, T: QGraphicsScene_backgroundBrush<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.backgroundBrush(self);
// return 1;
}
}
pub trait QGraphicsScene_backgroundBrush<RetType> {
fn backgroundBrush(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QBrush QGraphicsScene::backgroundBrush();
impl<'a> /*trait*/ QGraphicsScene_backgroundBrush<QBrush> for () {
fn backgroundBrush(self , rsthis: & QGraphicsScene) -> QBrush {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene15backgroundBrushEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene15backgroundBrushEv(rsthis.qclsinst)};
let mut ret1 = QBrush::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QGraphicsItem * QGraphicsScene::itemAt(qreal x, qreal y, const QTransform & deviceTransform);
impl /*struct*/ QGraphicsScene {
pub fn itemAt<RetType, T: QGraphicsScene_itemAt<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.itemAt(self);
// return 1;
}
}
pub trait QGraphicsScene_itemAt<RetType> {
fn itemAt(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsItem * QGraphicsScene::itemAt(qreal x, qreal y, const QTransform & deviceTransform);
impl<'a> /*trait*/ QGraphicsScene_itemAt<QGraphicsItem> for (f64, f64, &'a QTransform) {
fn itemAt(self , rsthis: & QGraphicsScene) -> QGraphicsItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene6itemAtEddRK10QTransform()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK14QGraphicsScene6itemAtEddRK10QTransform(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QGraphicsItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScene::advance();
impl /*struct*/ QGraphicsScene {
pub fn advance<RetType, T: QGraphicsScene_advance<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.advance(self);
// return 1;
}
}
pub trait QGraphicsScene_advance<RetType> {
fn advance(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::advance();
impl<'a> /*trait*/ QGraphicsScene_advance<()> for () {
fn advance(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene7advanceEv()};
unsafe {C_ZN14QGraphicsScene7advanceEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QGraphicsScene::setStickyFocus(bool enabled);
impl /*struct*/ QGraphicsScene {
pub fn setStickyFocus<RetType, T: QGraphicsScene_setStickyFocus<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setStickyFocus(self);
// return 1;
}
}
pub trait QGraphicsScene_setStickyFocus<RetType> {
fn setStickyFocus(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setStickyFocus(bool enabled);
impl<'a> /*trait*/ QGraphicsScene_setStickyFocus<()> for (i8) {
fn setStickyFocus(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene14setStickyFocusEb()};
let arg0 = self as c_char;
unsafe {C_ZN14QGraphicsScene14setStickyFocusEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QList<QGraphicsItem *> QGraphicsScene::selectedItems();
impl /*struct*/ QGraphicsScene {
pub fn selectedItems<RetType, T: QGraphicsScene_selectedItems<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.selectedItems(self);
// return 1;
}
}
pub trait QGraphicsScene_selectedItems<RetType> {
fn selectedItems(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QList<QGraphicsItem *> QGraphicsScene::selectedItems();
impl<'a> /*trait*/ QGraphicsScene_selectedItems<u64> for () {
fn selectedItems(self , rsthis: & QGraphicsScene) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene13selectedItemsEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene13selectedItemsEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: void QGraphicsScene::clear();
impl /*struct*/ QGraphicsScene {
pub fn clear<RetType, T: QGraphicsScene_clear<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clear(self);
// return 1;
}
}
pub trait QGraphicsScene_clear<RetType> {
fn clear(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::clear();
impl<'a> /*trait*/ QGraphicsScene_clear<()> for () {
fn clear(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene5clearEv()};
unsafe {C_ZN14QGraphicsScene5clearEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QGraphicsScene::setActivePanel(QGraphicsItem * item);
impl /*struct*/ QGraphicsScene {
pub fn setActivePanel<RetType, T: QGraphicsScene_setActivePanel<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setActivePanel(self);
// return 1;
}
}
pub trait QGraphicsScene_setActivePanel<RetType> {
fn setActivePanel(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setActivePanel(QGraphicsItem * item);
impl<'a> /*trait*/ QGraphicsScene_setActivePanel<()> for (&'a QGraphicsItem) {
fn setActivePanel(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene14setActivePanelEP13QGraphicsItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene14setActivePanelEP13QGraphicsItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QGraphicsPixmapItem * QGraphicsScene::addPixmap(const QPixmap & pixmap);
impl /*struct*/ QGraphicsScene {
pub fn addPixmap<RetType, T: QGraphicsScene_addPixmap<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addPixmap(self);
// return 1;
}
}
pub trait QGraphicsScene_addPixmap<RetType> {
fn addPixmap(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsPixmapItem * QGraphicsScene::addPixmap(const QPixmap & pixmap);
impl<'a> /*trait*/ QGraphicsScene_addPixmap<QGraphicsPixmapItem> for (&'a QPixmap) {
fn addPixmap(self , rsthis: & QGraphicsScene) -> QGraphicsPixmapItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene9addPixmapERK7QPixmap()};
let arg0 = self.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene9addPixmapERK7QPixmap(rsthis.qclsinst, arg0)};
let mut ret1 = QGraphicsPixmapItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QBrush QGraphicsScene::foregroundBrush();
impl /*struct*/ QGraphicsScene {
pub fn foregroundBrush<RetType, T: QGraphicsScene_foregroundBrush<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.foregroundBrush(self);
// return 1;
}
}
pub trait QGraphicsScene_foregroundBrush<RetType> {
fn foregroundBrush(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QBrush QGraphicsScene::foregroundBrush();
impl<'a> /*trait*/ QGraphicsScene_foregroundBrush<QBrush> for () {
fn foregroundBrush(self , rsthis: & QGraphicsScene) -> QBrush {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene15foregroundBrushEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene15foregroundBrushEv(rsthis.qclsinst)};
let mut ret1 = QBrush::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QList<QGraphicsView *> QGraphicsScene::views();
impl /*struct*/ QGraphicsScene {
pub fn views<RetType, T: QGraphicsScene_views<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.views(self);
// return 1;
}
}
pub trait QGraphicsScene_views<RetType> {
fn views(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QList<QGraphicsView *> QGraphicsScene::views();
impl<'a> /*trait*/ QGraphicsScene_views<u64> for () {
fn views(self , rsthis: & QGraphicsScene) -> u64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene5viewsEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene5viewsEv(rsthis.qclsinst)};
return ret as u64; // 5
// return 1;
}
}
// proto: void QGraphicsScene::~QGraphicsScene();
impl /*struct*/ QGraphicsScene {
pub fn free<RetType, T: QGraphicsScene_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QGraphicsScene_free<RetType> {
fn free(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::~QGraphicsScene();
impl<'a> /*trait*/ QGraphicsScene_free<()> for () {
fn free(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsSceneD2Ev()};
unsafe {C_ZN14QGraphicsSceneD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: QGraphicsRectItem * QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen & pen, const QBrush & brush);
impl /*struct*/ QGraphicsScene {
pub fn addRect<RetType, T: QGraphicsScene_addRect<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addRect(self);
// return 1;
}
}
pub trait QGraphicsScene_addRect<RetType> {
fn addRect(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsRectItem * QGraphicsScene::addRect(qreal x, qreal y, qreal w, qreal h, const QPen & pen, const QBrush & brush);
impl<'a> /*trait*/ QGraphicsScene_addRect<QGraphicsRectItem> for (f64, f64, f64, f64, Option<&'a QPen>, Option<&'a QBrush>) {
fn addRect(self , rsthis: & QGraphicsScene) -> QGraphicsRectItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene7addRectEddddRK4QPenRK6QBrush()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
let arg4 = (if self.4.is_none() {QPen::new(()).qclsinst} else {self.4.unwrap().qclsinst}) as *mut c_void;
let arg5 = (if self.5.is_none() {QBrush::new(()).qclsinst} else {self.5.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene7addRectEddddRK4QPenRK6QBrush(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)};
let mut ret1 = QGraphicsRectItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: int QGraphicsScene::bspTreeDepth();
impl /*struct*/ QGraphicsScene {
pub fn bspTreeDepth<RetType, T: QGraphicsScene_bspTreeDepth<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.bspTreeDepth(self);
// return 1;
}
}
pub trait QGraphicsScene_bspTreeDepth<RetType> {
fn bspTreeDepth(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: int QGraphicsScene::bspTreeDepth();
impl<'a> /*trait*/ QGraphicsScene_bspTreeDepth<i32> for () {
fn bspTreeDepth(self , rsthis: & QGraphicsScene) -> i32 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene12bspTreeDepthEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene12bspTreeDepthEv(rsthis.qclsinst)};
return ret as i32; // 1
// return 1;
}
}
// proto: void QGraphicsScene::setSceneRect(qreal x, qreal y, qreal w, qreal h);
impl<'a> /*trait*/ QGraphicsScene_setSceneRect<()> for (f64, f64, f64, f64) {
fn setSceneRect(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene12setSceneRectEdddd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
unsafe {C_ZN14QGraphicsScene12setSceneRectEdddd(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QGraphicsScene::setStyle(QStyle * style);
impl /*struct*/ QGraphicsScene {
pub fn setStyle<RetType, T: QGraphicsScene_setStyle<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setStyle(self);
// return 1;
}
}
pub trait QGraphicsScene_setStyle<RetType> {
fn setStyle(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setStyle(QStyle * style);
impl<'a> /*trait*/ QGraphicsScene_setStyle<()> for (&'a QStyle) {
fn setStyle(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene8setStyleEP6QStyle()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene8setStyleEP6QStyle(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsScene::setPalette(const QPalette & palette);
impl /*struct*/ QGraphicsScene {
pub fn setPalette<RetType, T: QGraphicsScene_setPalette<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setPalette(self);
// return 1;
}
}
pub trait QGraphicsScene_setPalette<RetType> {
fn setPalette(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setPalette(const QPalette & palette);
impl<'a> /*trait*/ QGraphicsScene_setPalette<()> for (&'a QPalette) {
fn setPalette(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene10setPaletteERK8QPalette()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene10setPaletteERK8QPalette(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsScene::setMinimumRenderSize(qreal minSize);
impl /*struct*/ QGraphicsScene {
pub fn setMinimumRenderSize<RetType, T: QGraphicsScene_setMinimumRenderSize<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setMinimumRenderSize(self);
// return 1;
}
}
pub trait QGraphicsScene_setMinimumRenderSize<RetType> {
fn setMinimumRenderSize(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setMinimumRenderSize(qreal minSize);
impl<'a> /*trait*/ QGraphicsScene_setMinimumRenderSize<()> for (f64) {
fn setMinimumRenderSize(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene20setMinimumRenderSizeEd()};
let arg0 = self as c_double;
unsafe {C_ZN14QGraphicsScene20setMinimumRenderSizeEd(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsScene::QGraphicsScene(qreal x, qreal y, qreal width, qreal height, QObject * parent);
impl<'a> /*trait*/ QGraphicsScene_new for (f64, f64, f64, f64, Option<&'a QObject>) {
fn new(self) -> QGraphicsScene {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsSceneC2EddddP7QObject()};
let ctysz: c_int = unsafe{QGraphicsScene_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
let arg4 = (if self.4.is_none() {0} else {self.4.unwrap().qclsinst}) as *mut c_void;
let qthis: u64 = unsafe {C_ZN14QGraphicsSceneC2EddddP7QObject(arg0, arg1, arg2, arg3, arg4)};
let rsthis = QGraphicsScene{qbase: QObject::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: QGraphicsItem * QGraphicsScene::mouseGrabberItem();
impl /*struct*/ QGraphicsScene {
pub fn mouseGrabberItem<RetType, T: QGraphicsScene_mouseGrabberItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.mouseGrabberItem(self);
// return 1;
}
}
pub trait QGraphicsScene_mouseGrabberItem<RetType> {
fn mouseGrabberItem(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsItem * QGraphicsScene::mouseGrabberItem();
impl<'a> /*trait*/ QGraphicsScene_mouseGrabberItem<QGraphicsItem> for () {
fn mouseGrabberItem(self , rsthis: & QGraphicsScene) -> QGraphicsItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene16mouseGrabberItemEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene16mouseGrabberItemEv(rsthis.qclsinst)};
let mut ret1 = QGraphicsItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QGraphicsRectItem * QGraphicsScene::addRect(const QRectF & rect, const QPen & pen, const QBrush & brush);
impl<'a> /*trait*/ QGraphicsScene_addRect<QGraphicsRectItem> for (&'a QRectF, Option<&'a QPen>, Option<&'a QBrush>) {
fn addRect(self , rsthis: & QGraphicsScene) -> QGraphicsRectItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene7addRectERK6QRectFRK4QPenRK6QBrush()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QPen::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let arg2 = (if self.2.is_none() {QBrush::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene7addRectERK6QRectFRK4QPenRK6QBrush(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QGraphicsRectItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QGraphicsEllipseItem * QGraphicsScene::addEllipse(const QRectF & rect, const QPen & pen, const QBrush & brush);
impl /*struct*/ QGraphicsScene {
pub fn addEllipse<RetType, T: QGraphicsScene_addEllipse<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addEllipse(self);
// return 1;
}
}
pub trait QGraphicsScene_addEllipse<RetType> {
fn addEllipse(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsEllipseItem * QGraphicsScene::addEllipse(const QRectF & rect, const QPen & pen, const QBrush & brush);
impl<'a> /*trait*/ QGraphicsScene_addEllipse<QGraphicsEllipseItem> for (&'a QRectF, Option<&'a QPen>, Option<&'a QBrush>) {
fn addEllipse(self , rsthis: & QGraphicsScene) -> QGraphicsEllipseItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene10addEllipseERK6QRectFRK4QPenRK6QBrush()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QPen::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let arg2 = (if self.2.is_none() {QBrush::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene10addEllipseERK6QRectFRK4QPenRK6QBrush(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QGraphicsEllipseItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: qreal QGraphicsScene::height();
impl /*struct*/ QGraphicsScene {
pub fn height<RetType, T: QGraphicsScene_height<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.height(self);
// return 1;
}
}
pub trait QGraphicsScene_height<RetType> {
fn height(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: qreal QGraphicsScene::height();
impl<'a> /*trait*/ QGraphicsScene_height<f64> for () {
fn height(self , rsthis: & QGraphicsScene) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene6heightEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene6heightEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QGraphicsScene::setSelectionArea(const QPainterPath & path, const QTransform & deviceTransform);
impl /*struct*/ QGraphicsScene {
pub fn setSelectionArea<RetType, T: QGraphicsScene_setSelectionArea<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSelectionArea(self);
// return 1;
}
}
pub trait QGraphicsScene_setSelectionArea<RetType> {
fn setSelectionArea(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setSelectionArea(const QPainterPath & path, const QTransform & deviceTransform);
impl<'a> /*trait*/ QGraphicsScene_setSelectionArea<()> for (&'a QPainterPath, &'a QTransform) {
fn setSelectionArea(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene16setSelectionAreaERK12QPainterPathRK10QTransform()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene16setSelectionAreaERK12QPainterPathRK10QTransform(rsthis.qclsinst, arg0, arg1)};
// return 1;
}
}
// proto: QFont QGraphicsScene::font();
impl /*struct*/ QGraphicsScene {
pub fn font<RetType, T: QGraphicsScene_font<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.font(self);
// return 1;
}
}
pub trait QGraphicsScene_font<RetType> {
fn font(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QFont QGraphicsScene::font();
impl<'a> /*trait*/ QGraphicsScene_font<QFont> for () {
fn font(self , rsthis: & QGraphicsScene) -> QFont {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene4fontEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene4fontEv(rsthis.qclsinst)};
let mut ret1 = QFont::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScene::clearSelection();
impl /*struct*/ QGraphicsScene {
pub fn clearSelection<RetType, T: QGraphicsScene_clearSelection<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.clearSelection(self);
// return 1;
}
}
pub trait QGraphicsScene_clearSelection<RetType> {
fn clearSelection(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::clearSelection();
impl<'a> /*trait*/ QGraphicsScene_clearSelection<()> for () {
fn clearSelection(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene14clearSelectionEv()};
unsafe {C_ZN14QGraphicsScene14clearSelectionEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QGraphicsScene::removeItem(QGraphicsItem * item);
impl /*struct*/ QGraphicsScene {
pub fn removeItem<RetType, T: QGraphicsScene_removeItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.removeItem(self);
// return 1;
}
}
pub trait QGraphicsScene_removeItem<RetType> {
fn removeItem(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::removeItem(QGraphicsItem * item);
impl<'a> /*trait*/ QGraphicsScene_removeItem<()> for (&'a QGraphicsItem) {
fn removeItem(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene10removeItemEP13QGraphicsItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene10removeItemEP13QGraphicsItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QGraphicsEllipseItem * QGraphicsScene::addEllipse(qreal x, qreal y, qreal w, qreal h, const QPen & pen, const QBrush & brush);
impl<'a> /*trait*/ QGraphicsScene_addEllipse<QGraphicsEllipseItem> for (f64, f64, f64, f64, Option<&'a QPen>, Option<&'a QBrush>) {
fn addEllipse(self , rsthis: & QGraphicsScene) -> QGraphicsEllipseItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene10addEllipseEddddRK4QPenRK6QBrush()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
let arg4 = (if self.4.is_none() {QPen::new(()).qclsinst} else {self.4.unwrap().qclsinst}) as *mut c_void;
let arg5 = (if self.5.is_none() {QBrush::new(()).qclsinst} else {self.5.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene10addEllipseEddddRK4QPenRK6QBrush(rsthis.qclsinst, arg0, arg1, arg2, arg3, arg4, arg5)};
let mut ret1 = QGraphicsEllipseItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScene::setActiveWindow(QGraphicsWidget * widget);
impl /*struct*/ QGraphicsScene {
pub fn setActiveWindow<RetType, T: QGraphicsScene_setActiveWindow<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setActiveWindow(self);
// return 1;
}
}
pub trait QGraphicsScene_setActiveWindow<RetType> {
fn setActiveWindow(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setActiveWindow(QGraphicsWidget * widget);
impl<'a> /*trait*/ QGraphicsScene_setActiveWindow<()> for (&'a QGraphicsWidget) {
fn setActiveWindow(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene15setActiveWindowEP15QGraphicsWidget()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene15setActiveWindowEP15QGraphicsWidget(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QGraphicsItem * QGraphicsScene::focusItem();
impl /*struct*/ QGraphicsScene {
pub fn focusItem<RetType, T: QGraphicsScene_focusItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.focusItem(self);
// return 1;
}
}
pub trait QGraphicsScene_focusItem<RetType> {
fn focusItem(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsItem * QGraphicsScene::focusItem();
impl<'a> /*trait*/ QGraphicsScene_focusItem<QGraphicsItem> for () {
fn focusItem(self , rsthis: & QGraphicsScene) -> QGraphicsItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene9focusItemEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene9focusItemEv(rsthis.qclsinst)};
let mut ret1 = QGraphicsItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QGraphicsTextItem * QGraphicsScene::addText(const QString & text, const QFont & font);
impl /*struct*/ QGraphicsScene {
pub fn addText<RetType, T: QGraphicsScene_addText<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addText(self);
// return 1;
}
}
pub trait QGraphicsScene_addText<RetType> {
fn addText(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsTextItem * QGraphicsScene::addText(const QString & text, const QFont & font);
impl<'a> /*trait*/ QGraphicsScene_addText<QGraphicsTextItem> for (&'a QString, Option<&'a QFont>) {
fn addText(self , rsthis: & QGraphicsScene) -> QGraphicsTextItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene7addTextERK7QStringRK5QFont()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QFont::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene7addTextERK7QStringRK5QFont(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QGraphicsTextItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScene::setSortCacheEnabled(bool enabled);
impl /*struct*/ QGraphicsScene {
pub fn setSortCacheEnabled<RetType, T: QGraphicsScene_setSortCacheEnabled<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setSortCacheEnabled(self);
// return 1;
}
}
pub trait QGraphicsScene_setSortCacheEnabled<RetType> {
fn setSortCacheEnabled(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setSortCacheEnabled(bool enabled);
impl<'a> /*trait*/ QGraphicsScene_setSortCacheEnabled<()> for (i8) {
fn setSortCacheEnabled(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene19setSortCacheEnabledEb()};
let arg0 = self as c_char;
unsafe {C_ZN14QGraphicsScene19setSortCacheEnabledEb(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QGraphicsItem * QGraphicsScene::itemAt(const QPointF & pos, const QTransform & deviceTransform);
impl<'a> /*trait*/ QGraphicsScene_itemAt<QGraphicsItem> for (&'a QPointF, &'a QTransform) {
fn itemAt(self , rsthis: & QGraphicsScene) -> QGraphicsItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene6itemAtERK7QPointFRK10QTransform()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = self.1.qclsinst as *mut c_void;
let mut ret = unsafe {C_ZNK14QGraphicsScene6itemAtERK7QPointFRK10QTransform(rsthis.qclsinst, arg0, arg1)};
let mut ret1 = QGraphicsItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup * group);
impl /*struct*/ QGraphicsScene {
pub fn destroyItemGroup<RetType, T: QGraphicsScene_destroyItemGroup<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.destroyItemGroup(self);
// return 1;
}
}
pub trait QGraphicsScene_destroyItemGroup<RetType> {
fn destroyItemGroup(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::destroyItemGroup(QGraphicsItemGroup * group);
impl<'a> /*trait*/ QGraphicsScene_destroyItemGroup<()> for (&'a QGraphicsItemGroup) {
fn destroyItemGroup(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene16destroyItemGroupEP18QGraphicsItemGroup()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene16destroyItemGroupEP18QGraphicsItemGroup(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: qreal QGraphicsScene::width();
impl /*struct*/ QGraphicsScene {
pub fn width<RetType, T: QGraphicsScene_width<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.width(self);
// return 1;
}
}
pub trait QGraphicsScene_width<RetType> {
fn width(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: qreal QGraphicsScene::width();
impl<'a> /*trait*/ QGraphicsScene_width<f64> for () {
fn width(self , rsthis: & QGraphicsScene) -> f64 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene5widthEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene5widthEv(rsthis.qclsinst)};
return ret as f64; // 1
// return 1;
}
}
// proto: void QGraphicsScene::update(qreal x, qreal y, qreal w, qreal h);
impl<'a> /*trait*/ QGraphicsScene_update<()> for (f64, f64, f64, f64) {
fn update(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene6updateEdddd()};
let arg0 = self.0 as c_double;
let arg1 = self.1 as c_double;
let arg2 = self.2 as c_double;
let arg3 = self.3 as c_double;
unsafe {C_ZN14QGraphicsScene6updateEdddd(rsthis.qclsinst, arg0, arg1, arg2, arg3)};
// return 1;
}
}
// proto: void QGraphicsScene::addItem(QGraphicsItem * item);
impl /*struct*/ QGraphicsScene {
pub fn addItem<RetType, T: QGraphicsScene_addItem<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addItem(self);
// return 1;
}
}
pub trait QGraphicsScene_addItem<RetType> {
fn addItem(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::addItem(QGraphicsItem * item);
impl<'a> /*trait*/ QGraphicsScene_addItem<()> for (&'a QGraphicsItem) {
fn addItem(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene7addItemEP13QGraphicsItem()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene7addItemEP13QGraphicsItem(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: void QGraphicsScene::setBackgroundBrush(const QBrush & brush);
impl /*struct*/ QGraphicsScene {
pub fn setBackgroundBrush<RetType, T: QGraphicsScene_setBackgroundBrush<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setBackgroundBrush(self);
// return 1;
}
}
pub trait QGraphicsScene_setBackgroundBrush<RetType> {
fn setBackgroundBrush(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setBackgroundBrush(const QBrush & brush);
impl<'a> /*trait*/ QGraphicsScene_setBackgroundBrush<()> for (&'a QBrush) {
fn setBackgroundBrush(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene18setBackgroundBrushERK6QBrush()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene18setBackgroundBrushERK6QBrush(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QGraphicsItem * QGraphicsScene::activePanel();
impl /*struct*/ QGraphicsScene {
pub fn activePanel<RetType, T: QGraphicsScene_activePanel<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.activePanel(self);
// return 1;
}
}
pub trait QGraphicsScene_activePanel<RetType> {
fn activePanel(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsItem * QGraphicsScene::activePanel();
impl<'a> /*trait*/ QGraphicsScene_activePanel<QGraphicsItem> for () {
fn activePanel(self , rsthis: & QGraphicsScene) -> QGraphicsItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene11activePanelEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene11activePanelEv(rsthis.qclsinst)};
let mut ret1 = QGraphicsItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: QStyle * QGraphicsScene::style();
impl /*struct*/ QGraphicsScene {
pub fn style<RetType, T: QGraphicsScene_style<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.style(self);
// return 1;
}
}
pub trait QGraphicsScene_style<RetType> {
fn style(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QStyle * QGraphicsScene::style();
impl<'a> /*trait*/ QGraphicsScene_style<QStyle> for () {
fn style(self , rsthis: & QGraphicsScene) -> QStyle {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene5styleEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene5styleEv(rsthis.qclsinst)};
let mut ret1 = QStyle::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: void QGraphicsScene::setFont(const QFont & font);
impl /*struct*/ QGraphicsScene {
pub fn setFont<RetType, T: QGraphicsScene_setFont<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.setFont(self);
// return 1;
}
}
pub trait QGraphicsScene_setFont<RetType> {
fn setFont(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: void QGraphicsScene::setFont(const QFont & font);
impl<'a> /*trait*/ QGraphicsScene_setFont<()> for (&'a QFont) {
fn setFont(self , rsthis: & QGraphicsScene) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene7setFontERK5QFont()};
let arg0 = self.qclsinst as *mut c_void;
unsafe {C_ZN14QGraphicsScene7setFontERK5QFont(rsthis.qclsinst, arg0)};
// return 1;
}
}
// proto: QGraphicsPathItem * QGraphicsScene::addPath(const QPainterPath & path, const QPen & pen, const QBrush & brush);
impl /*struct*/ QGraphicsScene {
pub fn addPath<RetType, T: QGraphicsScene_addPath<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.addPath(self);
// return 1;
}
}
pub trait QGraphicsScene_addPath<RetType> {
fn addPath(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: QGraphicsPathItem * QGraphicsScene::addPath(const QPainterPath & path, const QPen & pen, const QBrush & brush);
impl<'a> /*trait*/ QGraphicsScene_addPath<QGraphicsPathItem> for (&'a QPainterPath, Option<&'a QPen>, Option<&'a QBrush>) {
fn addPath(self , rsthis: & QGraphicsScene) -> QGraphicsPathItem {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN14QGraphicsScene7addPathERK12QPainterPathRK4QPenRK6QBrush()};
let arg0 = self.0.qclsinst as *mut c_void;
let arg1 = (if self.1.is_none() {QPen::new(()).qclsinst} else {self.1.unwrap().qclsinst}) as *mut c_void;
let arg2 = (if self.2.is_none() {QBrush::new(()).qclsinst} else {self.2.unwrap().qclsinst}) as *mut c_void;
let mut ret = unsafe {C_ZN14QGraphicsScene7addPathERK12QPainterPathRK4QPenRK6QBrush(rsthis.qclsinst, arg0, arg1, arg2)};
let mut ret1 = QGraphicsPathItem::inheritFrom(ret as u64);
return ret1;
// return 1;
}
}
// proto: bool QGraphicsScene::stickyFocus();
impl /*struct*/ QGraphicsScene {
pub fn stickyFocus<RetType, T: QGraphicsScene_stickyFocus<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.stickyFocus(self);
// return 1;
}
}
pub trait QGraphicsScene_stickyFocus<RetType> {
fn stickyFocus(self , rsthis: & QGraphicsScene) -> RetType;
}
// proto: bool QGraphicsScene::stickyFocus();
impl<'a> /*trait*/ QGraphicsScene_stickyFocus<i8> for () {
fn stickyFocus(self , rsthis: & QGraphicsScene) -> i8 {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK14QGraphicsScene11stickyFocusEv()};
let mut ret = unsafe {C_ZNK14QGraphicsScene11stickyFocusEv(rsthis.qclsinst)};
return ret as i8; // 1
// return 1;
}
}
#[derive(Default)] // for QGraphicsScene_changed
pub struct QGraphicsScene_changed_signal{poi:u64}
impl /* struct */ QGraphicsScene {
pub fn changed(&self) -> QGraphicsScene_changed_signal {
return QGraphicsScene_changed_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsScene_changed_signal {
pub fn connect<T: QGraphicsScene_changed_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsScene_changed_signal_connect {
fn connect(self, sigthis: QGraphicsScene_changed_signal);
}
#[derive(Default)] // for QGraphicsScene_sceneRectChanged
pub struct QGraphicsScene_sceneRectChanged_signal{poi:u64}
impl /* struct */ QGraphicsScene {
pub fn sceneRectChanged(&self) -> QGraphicsScene_sceneRectChanged_signal {
return QGraphicsScene_sceneRectChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsScene_sceneRectChanged_signal {
pub fn connect<T: QGraphicsScene_sceneRectChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsScene_sceneRectChanged_signal_connect {
fn connect(self, sigthis: QGraphicsScene_sceneRectChanged_signal);
}
#[derive(Default)] // for QGraphicsScene_selectionChanged
pub struct QGraphicsScene_selectionChanged_signal{poi:u64}
impl /* struct */ QGraphicsScene {
pub fn selectionChanged(&self) -> QGraphicsScene_selectionChanged_signal {
return QGraphicsScene_selectionChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsScene_selectionChanged_signal {
pub fn connect<T: QGraphicsScene_selectionChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsScene_selectionChanged_signal_connect {
fn connect(self, sigthis: QGraphicsScene_selectionChanged_signal);
}
#[derive(Default)] // for QGraphicsScene_focusItemChanged
pub struct QGraphicsScene_focusItemChanged_signal{poi:u64}
impl /* struct */ QGraphicsScene {
pub fn focusItemChanged(&self) -> QGraphicsScene_focusItemChanged_signal {
return QGraphicsScene_focusItemChanged_signal{poi:self.qclsinst};
}
}
impl /* struct */ QGraphicsScene_focusItemChanged_signal {
pub fn connect<T: QGraphicsScene_focusItemChanged_signal_connect>(self, overload_args: T) {
overload_args.connect(self);
}
}
pub trait QGraphicsScene_focusItemChanged_signal_connect {
fn connect(self, sigthis: QGraphicsScene_focusItemChanged_signal);
}
// selectionChanged()
extern fn QGraphicsScene_selectionChanged_signal_connect_cb_0(rsfptr:fn(), ) {
println!("{}:{}", file!(), line!());
rsfptr();
}
extern fn QGraphicsScene_selectionChanged_signal_connect_cb_box_0(rsfptr_raw:*mut Box<Fn()>, ) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
// rsfptr();
unsafe{(*rsfptr_raw)()};
}
impl /* trait */ QGraphicsScene_selectionChanged_signal_connect for fn() {
fn connect(self, sigthis: QGraphicsScene_selectionChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScene_selectionChanged_signal_connect_cb_0 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsScene_SlotProxy_connect__ZN14QGraphicsScene16selectionChangedEv(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsScene_selectionChanged_signal_connect for Box<Fn()> {
fn connect(self, sigthis: QGraphicsScene_selectionChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScene_selectionChanged_signal_connect_cb_box_0 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsScene_SlotProxy_connect__ZN14QGraphicsScene16selectionChangedEv(arg0, arg1, arg2)};
}
}
// sceneRectChanged(const class QRectF &)
extern fn QGraphicsScene_sceneRectChanged_signal_connect_cb_1(rsfptr:fn(QRectF), arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsarg0 = QRectF::inheritFrom(arg0 as u64);
rsfptr(rsarg0);
}
extern fn QGraphicsScene_sceneRectChanged_signal_connect_cb_box_1(rsfptr_raw:*mut Box<Fn(QRectF)>, arg0: *mut c_void) {
println!("{}:{}", file!(), line!());
let rsfptr = unsafe{Box::from_raw(rsfptr_raw)};
let rsarg0 = QRectF::inheritFrom(arg0 as u64);
// rsfptr(rsarg0);
unsafe{(*rsfptr_raw)(rsarg0)};
}
impl /* trait */ QGraphicsScene_sceneRectChanged_signal_connect for fn(QRectF) {
fn connect(self, sigthis: QGraphicsScene_sceneRectChanged_signal) {
// do smth...
// self as u64; // error for Fn, Ok for fn
self as *mut c_void as u64;
self as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScene_sceneRectChanged_signal_connect_cb_1 as *mut c_void;
let arg2 = self as *mut c_void;
unsafe {QGraphicsScene_SlotProxy_connect__ZN14QGraphicsScene16sceneRectChangedERK6QRectF(arg0, arg1, arg2)};
}
}
impl /* trait */ QGraphicsScene_sceneRectChanged_signal_connect for Box<Fn(QRectF)> {
fn connect(self, sigthis: QGraphicsScene_sceneRectChanged_signal) {
// do smth...
// Box::into_raw(self) as u64;
// Box::into_raw(self) as *mut c_void;
let arg0 = sigthis.poi as *mut c_void;
let arg1 = QGraphicsScene_sceneRectChanged_signal_connect_cb_box_1 as *mut c_void;
let arg2 = Box::into_raw(Box::new(self)) as *mut c_void;
unsafe {QGraphicsScene_SlotProxy_connect__ZN14QGraphicsScene16sceneRectChangedERK6QRectF(arg0, arg1, arg2)};
}
}
// <= body block end
|
extern crate crypto; // 外部库引入
use crypto::digest::Digest;
use crypto::sha3::Sha3;
fn main() {
let mut h = Sha3::sha3_256();
h::input_str("hello world");
let result = h.result_str();
println!("hash = {}", result);
println!("Hello, world!");
}
|
use std::{collections::HashSet, sync::Arc};
use datafusion::{
common::{DataFusionError, Result as DataFusionResult},
execution::FunctionRegistry,
logical_expr::{AggregateUDF, ScalarUDF, WindowUDF},
};
use once_cell::sync::Lazy;
use crate::{gapfill, regex, window};
static REGISTRY: Lazy<IOxFunctionRegistry> = Lazy::new(IOxFunctionRegistry::new);
/// Lookup for all DataFusion User Defined Functions used by IOx
#[derive(Debug)]
pub(crate) struct IOxFunctionRegistry {}
impl IOxFunctionRegistry {
fn new() -> Self {
Self {}
}
}
impl FunctionRegistry for IOxFunctionRegistry {
fn udfs(&self) -> HashSet<String> {
[
gapfill::DATE_BIN_GAPFILL_UDF_NAME,
gapfill::LOCF_UDF_NAME,
gapfill::INTERPOLATE_UDF_NAME,
regex::REGEX_MATCH_UDF_NAME,
regex::REGEX_NOT_MATCH_UDF_NAME,
window::WINDOW_BOUNDS_UDF_NAME,
]
.into_iter()
.map(|s| s.to_string())
.collect()
}
fn udf(&self, name: &str) -> DataFusionResult<Arc<ScalarUDF>> {
match name {
gapfill::DATE_BIN_GAPFILL_UDF_NAME => Ok(gapfill::DATE_BIN_GAPFILL.clone()),
gapfill::LOCF_UDF_NAME => Ok(gapfill::LOCF.clone()),
gapfill::INTERPOLATE_UDF_NAME => Ok(gapfill::INTERPOLATE.clone()),
regex::REGEX_MATCH_UDF_NAME => Ok(regex::REGEX_MATCH_UDF.clone()),
regex::REGEX_NOT_MATCH_UDF_NAME => Ok(regex::REGEX_NOT_MATCH_UDF.clone()),
window::WINDOW_BOUNDS_UDF_NAME => Ok(window::WINDOW_BOUNDS_UDF.clone()),
_ => Err(DataFusionError::Plan(format!(
"IOx FunctionRegistry does not contain function '{name}'"
))),
}
}
fn udaf(&self, name: &str) -> DataFusionResult<Arc<AggregateUDF>> {
Err(DataFusionError::Plan(format!(
"IOx FunctionRegistry does not contain user defined aggregate function '{name}'"
)))
}
fn udwf(&self, name: &str) -> DataFusionResult<Arc<WindowUDF>> {
Err(DataFusionError::Plan(format!(
"IOx FunctionRegistry does not contain user defined window function '{name}'"
)))
}
}
/// Return a reference to the global function registry
pub(crate) fn instance() -> &'static IOxFunctionRegistry {
®ISTRY
}
|
// Copyright 2015 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
// Test that we are able to introduce a negative constraint that
// `MyType: !MyTrait` along with other "fundamental" wrappers.
// aux-build:coherence_copy_like_lib.rs
extern crate coherence_copy_like_lib as lib;
struct MyType { x: i32 }
trait MyTrait { }
impl<T: lib::MyCopy> MyTrait for T { }
impl MyTrait for MyType { }
impl<'a> MyTrait for &'a MyType { }
impl MyTrait for Box<MyType> { }
impl<'a> MyTrait for &'a Box<MyType> { }
fn main() { }
|
use intern;
use grammar::{parse_tree, repr};
use std::collections::{HashMap, HashSet};
pub struct FirstSet {
pub set: HashSet<parse_tree::TerminalString>,
pub epsilon: bool
}
pub fn firsts(grammar: &repr::Grammar) -> HashMap<parse_tree::NonterminalString,
FirstSet> {
let mut ret = HashMap::new();
for &nt in grammar.nonterminals.keys() {
ret.insert(nt, FirstSet {
set: HashSet::new(),
epsilon: false
});
}
// fix point search
let mut fp = false;
while !fp {
fp = true;
for (nt, data) in grammar.nonterminals.iter() {
'a: for prod in data.productions.iter() {
for sym in prod.symbols.iter() {
match sym {
// if we encounter an opaque symbol (i.e. either a
// terminal of a non-terminal that does not derive
// epsilon, we just stop processing this rule. This
// is done with "continue 'a"
&repr::Symbol::Terminal(t) => {
fp &= !ret.get_mut(nt).unwrap().set.insert(t);
continue 'a
}
&repr::Symbol::Nonterminal(sym) => {
// trick to be able to access mutably ret[idx]
// while ret[sym] is immutabily borrowed. this
// is safe since the case sym == idx doesn't
// interest us anyway...
//let ((sub1, sub2), idx1, idx2) =
// if sym > idx {
// let (fst, snd) = ret.split_at_mut(sym);
// ((snd, fst), 0, idx)
// } else if sym < idx {
// (ret.split_at_mut(idx), sym, 0)
// } else { continue };
let clone = ret[&sym].set.clone();
for s in clone.iter() {
fp &= !ret.get_mut(nt).unwrap().set.insert(s.clone());
}
if !ret[&sym].epsilon { continue 'a }
}
}
}
// if we arrive here without jumping to the next
// iteration of 'a, it means all the symbols in
// this production devive epsilon, or there are
// no symbols (i.e. this is a e-rule) so:
fp &= ret[nt].epsilon;
ret.get_mut(nt).unwrap().epsilon = true;
}
}
}
ret
}
pub fn compute(grammar: &repr::Grammar, nts: &[String]) {
let firsts = firsts(grammar);
for nt in nts {
println!("=== FIRST({}) ===", nt);
for sym in firsts[&parse_tree::NonterminalString(intern::intern(&nt))].set.iter() {
println!("{}", sym)
}
}
}
|
use std::collections::VecDeque;
pub const INPUT: &str = include_str!("../input.txt");
pub struct HeightMap {
width: usize,
height: usize,
heights: Vec<u8>,
initial_position: usize,
target_position: usize,
}
impl HeightMap {
fn from_input(input: &str) -> Self {
let lines = input.lines().collect::<Vec<_>>();
let width = lines[0].len();
let height = lines.len();
let bytes = lines.into_iter().flat_map(str::bytes).collect::<Vec<_>>();
let initial_position = bytes.iter().position(|&b| b == b'S').unwrap();
let target_position = bytes.iter().position(|&b| b == b'E').unwrap();
let heights = bytes
.into_iter()
.map(|b| match b {
b'S' => 0,
b'E' => 25,
b if b.is_ascii_lowercase() => b - b'a',
_ => panic!("invalid height {b}"),
})
.collect::<Vec<_>>();
HeightMap {
width,
height,
heights,
initial_position,
target_position,
}
}
}
pub fn parse_input(input: &str) -> HeightMap {
HeightMap::from_input(input)
}
pub fn part_one(height_map: &HeightMap) -> usize {
find_shortest_path_len(height_map, [height_map.initial_position]).unwrap()
}
pub fn part_two(height_map: &HeightMap) -> usize {
let starting_positions =
height_map
.heights
.iter()
.enumerate()
.filter_map(|(i, &h)| if h == 0 { Some(i) } else { None });
find_shortest_path_len(height_map, starting_positions).unwrap()
}
fn find_shortest_path_len<I>(height_map: &HeightMap, starting_positions: I) -> Option<usize>
where
I: IntoIterator<Item = usize>,
{
let mut queue = starting_positions
.into_iter()
.map(|p| (p, 0))
.collect::<VecDeque<_>>();
let mut seen = vec![false; height_map.width * height_map.height];
for p in &queue {
seen[p.0] = true;
}
while let Some((position, steps)) = queue.pop_front() {
if position == height_map.target_position {
return Some(steps);
}
let x = position % height_map.width;
let y = position / height_map.width;
let adjacent_positions = [
x.checked_sub(1).map(|x| x + y * height_map.width),
x.checked_add(1)
.filter(|&x| x < height_map.width)
.map(|x| x + y * height_map.width),
y.checked_sub(1).map(|y| x + y * height_map.width),
y.checked_add(1)
.filter(|&y| y < height_map.height)
.map(|y| x + y * height_map.width),
];
for p in adjacent_positions {
if let Some(p) =
p.filter(|&p| !seen[p] && height_map.heights[p] <= height_map.heights[position] + 1)
{
seen[p] = true;
queue.push_back((p, steps + 1));
}
}
}
None
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_part_one() {
let height_map = parse_input(INPUT);
assert_eq!(part_one(&height_map), 472);
}
#[test]
fn test_part_two() {
let height_map = parse_input(INPUT);
assert_eq!(part_two(&height_map), 465);
}
}
|
// pathfinder/path-utils/src/curve.rs
//
// Copyright © 2017 The Pathfinder Project Developers.
//
// 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.
//! Geometry utilities for quadratic Bézier curves.
use euclid::approxeq::ApproxEq;
use euclid::Point2D;
use std::f32;
use PathCommand;
use intersection::Intersect;
use line::Line;
/// A quadratic Bézier curve.
#[derive(Clone, Copy, PartialEq, Debug)]
pub struct Curve {
/// The start and end points of the curve, respectively.
pub endpoints: [Point2D<f32>; 2],
/// The control point of the curve.
pub control_point: Point2D<f32>,
}
impl Curve {
/// Creates a new quadratic Bézier curve from the given endpoints and control point.
#[inline]
pub fn new(endpoint_0: &Point2D<f32>, control_point: &Point2D<f32>, endpoint_1: &Point2D<f32>)
-> Curve {
Curve {
endpoints: [*endpoint_0, *endpoint_1],
control_point: *control_point,
}
}
/// Returns the curve point at time `t` (0.0 to 1.0).
#[inline]
pub fn sample(&self, t: f32) -> Point2D<f32> {
let (p0, p1, p2) = (&self.endpoints[0], &self.control_point, &self.endpoints[1]);
Point2D::lerp(&p0.lerp(*p1, t), p1.lerp(*p2, t), t)
}
/// De Casteljau subdivides this curve into two at time `t` (0.0 to 1.0).
///
/// Returns the two resulting curves.
#[inline]
pub fn subdivide(&self, t: f32) -> (Curve, Curve) {
let (p0, p1, p2) = (&self.endpoints[0], &self.control_point, &self.endpoints[1]);
let (ap1, bp1) = (p0.lerp(*p1, t), p1.lerp(*p2, t));
let ap2bp0 = ap1.lerp(bp1, t);
(Curve::new(p0, &ap1, &ap2bp0), Curve::new(&ap2bp0, &bp1, p2))
}
/// Divides this curve into two at the point with *x* coordinate equal to `x`.
///
/// Results are undefined if there is not exactly one point on the curve with *x* coordinate
/// equal to `x`.
pub fn subdivide_at_x(&self, x: f32) -> (Curve, Curve) {
let (prev_part, next_part) = self.subdivide(self.solve_t_for_x(x));
if self.endpoints[0].x <= self.endpoints[1].x {
(prev_part, next_part)
} else {
(next_part, prev_part)
}
}
/// A convenience method that constructs a `CurveTo` path command from this curve's control
/// point and second endpoint.
#[inline]
pub fn to_path_command(&self) -> PathCommand {
PathCommand::CurveTo(self.control_point, self.endpoints[1])
}
/// Returns the times at which the derivative of the curve becomes 0 with respect to *x* and
/// *y* in that order.
pub fn inflection_points(&self) -> (Option<f32>, Option<f32>) {
let inflection_point_x = Curve::inflection_point_x(self.endpoints[0].x,
self.control_point.x,
self.endpoints[1].x);
let inflection_point_y = Curve::inflection_point_x(self.endpoints[0].y,
self.control_point.y,
self.endpoints[1].y);
(inflection_point_x, inflection_point_y)
}
/// Returns the time of the single point on this curve with *x* coordinate equal to `x`.
///
/// Internally, this method uses the [Citardauq Formula] to avoid precision problems.
///
/// If there is not exactly one point with *x* coordinate equal to `x`, the results are
/// undefined.
///
/// [Citardauq Formula]: https://math.stackexchange.com/a/311397
pub fn solve_t_for_x(&self, x: f32) -> f32 {
let p0x = self.endpoints[0].x as f64;
let p1x = self.control_point.x as f64;
let p2x = self.endpoints[1].x as f64;
let x = x as f64;
let a = p0x - 2.0 * p1x + p2x;
let b = -2.0 * p0x + 2.0 * p1x;
let c = p0x - x;
let t = 2.0 * c / (-b - (b * b - 4.0 * a * c).sqrt());
t.max(0.0).min(1.0) as f32
}
/// A convenience method that returns the *y* coordinate of the single point on this curve with
/// *x* coordinate equal to `x`.
///
/// Results are undefined if there is not exactly one point with *x* coordinate equal to `x`.
#[inline]
pub fn solve_y_for_x(&self, x: f32) -> f32 {
self.sample(self.solve_t_for_x(x)).y
}
/// Returns a line segment from the start endpoint of this curve to the end of this curve.
#[inline]
pub fn baseline(&self) -> Line {
Line::new(&self.endpoints[0], &self.endpoints[1])
}
#[inline]
fn inflection_point_x(endpoint_x_0: f32, control_point_x: f32, endpoint_x_1: f32)
-> Option<f32> {
let num = endpoint_x_0 - control_point_x;
let denom = endpoint_x_0 - 2.0 * control_point_x + endpoint_x_1;
let t = num / denom;
if t > f32::approx_epsilon() && t < 1.0 - f32::approx_epsilon() {
Some(t)
} else {
None
}
}
/// Returns the point of intersection of this curve with the given curve.
#[inline]
pub fn intersect<T>(&self, other: &T) -> Option<Point2D<f32>> where T: Intersect {
<Curve as Intersect>::intersect(self, other)
}
}
|
use super::InternalEvent;
use metrics::counter;
#[derive(Debug)]
pub struct FileEventReceived<'a> {
pub file: &'a str,
pub byte_size: usize,
}
impl InternalEvent for FileEventReceived<'_> {
fn emit_logs(&self) {
trace!(
message = "received one event.",
%self.file,
rate_limit_secs = 10
);
}
fn emit_metrics(&self) {
counter!(
"events_processed", 1,
"component_kind" => "source",
"component_type" => "file",
);
counter!(
"bytes_processed", self.byte_size as u64,
"component_kind" => "source",
"component_type" => "file",
);
}
}
|
pub type TyRef = usize;
pub type TmRef = usize;
pub type DBI = usize;
#[derive(Eq, Clone, Copy, PartialEq, Debug)]
pub enum Ty {
Var(DBI),
ForAll(TyRef),
Arr(TyRef, TyRef),
}
#[derive(Eq, Clone, Copy, PartialEq, Debug)]
pub enum Tm {
Var(DBI),
Abs(TyRef, TmRef),
App(TmRef, TmRef),
Gen(TmRef),
Inst(TmRef, TyRef),
}
#[derive(Eq, Clone, PartialEq)]
pub enum TyExpr {
Var(DBI),
ForAll(Box<TyExpr>),
Arr(Box<TyExpr>, Box<TyExpr>),
}
#[derive(Eq, Clone, PartialEq)]
pub enum TmExpr {
Var(DBI),
Abs(TyExpr, Box<TmExpr>),
App(Box<TmExpr>, Box<TmExpr>),
Gen(Box<TmExpr>),
Inst(Box<TmExpr>, TyExpr),
}
impl std::fmt::Debug for TyExpr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
TyExpr::Var(i) => write!(f, "{}", i),
TyExpr::ForAll(ty) => write!(f, "(∀. {:?})", ty),
TyExpr::Arr(domain, codomain) => write!(f, "{:?} → {:?}", domain, codomain),
}
}
}
impl std::fmt::Debug for TmExpr {
fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> {
match self {
TmExpr::Var(i) => write!(f, "{}", i),
TmExpr::Abs(ty, body) => write!(f, "λ {:?}. {:?}", ty, body),
TmExpr::App(opr, opt) => write!(f, "({:?} {:?})", opr, opt),
TmExpr::Gen(body) => write!(f, "Λ. {:?}", body),
TmExpr::Inst(tm, ty) => write!(f, "{:?}[{:?}]", tm, ty),
}
}
}
|
fn main() {
println!("Repeated={}", m1::test1(4));
test_res(42);
test_res(230);
}
mod m1 {
use std::iter;
pub fn test1(len: usize) -> String {
iter::repeat("x").take(len).collect()
}
}
fn test_res(x: usize) {
match fallible1(x) {
Ok(s) => println!("worked 1={}", s),
Err(e) => println!("error 2={}", e)
}
match fallible2(x) {
Ok(s) => println!("worked 2={}", s),
Err(e) => println!("error 2={}", e)
}
}
fn fallible1(x: usize) -> Result<String, u64> {
let mut answer = another_fallible(x)?;
answer.push_str("ss");
Ok(answer)
}
fn fallible2(x: usize) -> Result<String, u64> {
match another_fallible(x) {
Ok(mut s) => {
s.push_str("qq");
Ok(s)
},
Err(e) => Err(e)
}
}
fn another_fallible(x: usize) -> Result<String, u64> {
if x > 100 {
return Err(42);
}
Ok("hello".to_string())
}
///////////////////////////////////////////////////
fn borrow1() {
let a = 42;
// a = 3; a not mut
let b = 10;
let mut c = 15;
let x;
{
// let e = &mut b; // b not mut
let e = &mut c;
*e = 5;
let y = 56;
x = &y;
println!("x={}", x);
}
// println!("x again={}", x);
}
///////////////////////////////////////////////////
enum Jtres<S, E> {
Ok(S),
Err(E)
}
fn test_resjt(x: usize) {
/*
match fallible1jt(x) {
Ok(s) => println!("worked jt1={}", s),
Err(e) => println!("error jt2={}", e)
}
*/
match fallible2jt(x) {
Ok(s) => println!("worked 2={}", s),
Err(e) => println!("error 2={}", e)
}
}
/*
fn fallible1jt(x: usize) -> Jtres<String, u64> {
let answer = another_falliblejt(x)?; // Try trait
answer.push_str("ss");
Jtres::Ok(answer)
}
*/
fn fallible2jt(x: usize) -> Jtres<String, u64> {
match another_falliblejt(x) {
Jtres::Ok(mut s) => {
s.push_str("qq");
Jtres::Ok(s)
},
Jtres::Err(e) => Jtres::Err(e)
}
}
fn another_falliblejt(x: usize) -> Jtres<String, u64> {
if x > 100 {
return Jtres::Err(42);
}
Jtres::Ok("hello".to_string())
}
fn option() {
let mut foo: Option<u32>;
foo = None;
foo = Some(3);
} |
//! Boolean satisfiability solver.
use std::io;
use partial_ref::{IntoPartialRef, IntoPartialRefMut, PartialRef};
use anyhow::Error;
use thiserror::Error;
use varisat_checker::ProofProcessor;
use varisat_dimacs::DimacsParser;
use varisat_formula::{CnfFormula, ExtendFormula, Lit, Var};
use crate::{
assumptions::set_assumptions,
config::SolverConfigUpdate,
context::{config_changed, parts::*, Context},
load::load_clause,
proof,
schedule::schedule_step,
state::SatState,
variables,
};
pub use crate::proof::ProofFormat;
/// Possible errors while solving a formula.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum SolverError {
#[error("The solver was interrupted")]
Interrupted,
#[error("Error in proof processor: {}", cause)]
ProofProcessorError {
#[source]
cause: Error,
},
#[error("Error writing proof file: {}", cause)]
ProofIoError {
#[source]
cause: io::Error,
},
}
impl SolverError {
/// Whether a Solver instance can be used after producing such an error.
pub fn is_recoverable(&self) -> bool {
matches!(self, SolverError::Interrupted)
}
}
/// A boolean satisfiability solver.
#[derive(Default)]
pub struct Solver<'a> {
ctx: Box<Context<'a>>,
}
impl<'a> Solver<'a> {
/// Create a new solver.
pub fn new() -> Solver<'a> {
Solver::default()
}
/// Change the solver configuration.
pub fn config(&mut self, config_update: &SolverConfigUpdate) -> Result<(), Error> {
config_update.apply(&mut self.ctx.solver_config)?;
let mut ctx = self.ctx.into_partial_ref_mut();
config_changed(ctx.borrow(), config_update);
Ok(())
}
/// Add a formula to the solver.
pub fn add_formula(&mut self, formula: &CnfFormula) {
let mut ctx = self.ctx.into_partial_ref_mut();
for clause in formula.iter() {
load_clause(ctx.borrow(), clause);
}
}
/// Reads and adds a formula in DIMACS CNF format.
///
/// Using this avoids creating a temporary [`CnfFormula`].
pub fn add_dimacs_cnf(&mut self, input: impl io::Read) -> Result<(), Error> {
let parser = DimacsParser::parse_incremental(input, |parser| {
self.add_formula(&parser.take_formula());
Ok(())
})?;
log::info!(
"Parsed formula with {} variables and {} clauses",
parser.var_count(),
parser.clause_count()
);
Ok(())
}
/// Sets the "witness" sampling mode for a variable.
pub fn witness_var(&mut self, var: Var) {
// TODO add link to sampling mode section of the manual when written
let mut ctx = self.ctx.into_partial_ref_mut();
let global = variables::global_from_user(ctx.borrow(), var, false);
variables::set_sampling_mode(ctx.borrow(), global, variables::data::SamplingMode::Witness);
}
/// Sets the "sample" sampling mode for a variable.
pub fn sample_var(&mut self, var: Var) {
// TODO add link to sampling mode section of the manual when written
// TODO add warning about constrainig variables that previously were witness variables
let mut ctx = self.ctx.into_partial_ref_mut();
let global = variables::global_from_user(ctx.borrow(), var, false);
variables::set_sampling_mode(ctx.borrow(), global, variables::data::SamplingMode::Sample);
}
/// Hide a variable.
///
/// Turns a free variable into an existentially quantified variable. If the passed `Var` is used
/// again after this call, it refers to a new variable not the previously hidden variable.
pub fn hide_var(&mut self, var: Var) {
// TODO add link to sampling mode section of the manual when written
let mut ctx = self.ctx.into_partial_ref_mut();
let global = variables::global_from_user(ctx.borrow(), var, false);
variables::set_sampling_mode(ctx.borrow(), global, variables::data::SamplingMode::Hide);
}
/// Observe solver internal variables.
///
/// This turns solver internal variables into witness variables. There is no guarantee that the
/// newly visible variables correspond to previously hidden variables.
///
/// Returns a list of newly visible variables.
pub fn observe_internal_vars(&mut self) -> Vec<Var> {
// TODO add link to sampling mode section of the manual when written
let mut ctx = self.ctx.into_partial_ref_mut();
variables::observe_internal_vars(ctx.borrow())
}
/// Check the satisfiability of the current formula.
pub fn solve(&mut self) -> Result<bool, SolverError> {
self.ctx.solver_state.solver_invoked = true;
let mut ctx = self.ctx.into_partial_ref_mut();
assert!(
!ctx.part_mut(SolverStateP).state_is_invalid,
"solve() called after encountering an unrecoverable error"
);
while schedule_step(ctx.borrow()) {}
proof::solve_finished(ctx.borrow());
self.check_for_solver_error()?;
match self.ctx.solver_state.sat_state {
SatState::Unknown => Err(SolverError::Interrupted),
SatState::Sat => Ok(true),
SatState::Unsat | SatState::UnsatUnderAssumptions => Ok(false),
}
}
/// Check for asynchronously generated errors.
///
/// To avoid threading errors out of deep call stacks, we have a solver_error field in the
/// SolverState. This function takes and returns that error if present.
fn check_for_solver_error(&mut self) -> Result<(), SolverError> {
let mut ctx = self.ctx.into_partial_ref_mut();
let error = ctx.part_mut(SolverStateP).solver_error.take();
if let Some(error) = error {
if !error.is_recoverable() {
ctx.part_mut(SolverStateP).state_is_invalid = true;
}
Err(error)
} else {
Ok(())
}
}
/// Assume given literals for future calls to solve.
///
/// This replaces the current set of assumed literals.
pub fn assume(&mut self, assumptions: &[Lit]) {
let mut ctx = self.ctx.into_partial_ref_mut();
set_assumptions(ctx.borrow(), assumptions);
}
/// Set of literals that satisfy the formula.
pub fn model(&self) -> Option<Vec<Lit>> {
let ctx = self.ctx.into_partial_ref();
if ctx.part(SolverStateP).sat_state == SatState::Sat {
Some(
ctx.part(VariablesP)
.user_var_iter()
.flat_map(|user_var| {
let global_var = ctx
.part(VariablesP)
.global_from_user()
.get(user_var)
.expect("no existing global var for user var");
ctx.part(ModelP).assignment()[global_var.index()]
.map(|value| user_var.lit(value))
})
.collect(),
)
} else {
None
}
}
/// Subset of the assumptions that made the formula unsatisfiable.
///
/// This is not guaranteed to be minimal and may just return all assumptions every time.
pub fn failed_core(&self) -> Option<&[Lit]> {
match self.ctx.solver_state.sat_state {
SatState::UnsatUnderAssumptions => Some(self.ctx.assumptions.user_failed_core()),
SatState::Unsat => Some(&[]),
SatState::Unknown | SatState::Sat => None,
}
}
/// Generate a proof of unsatisfiability during solving.
///
/// This needs to be called before any clauses are added.
pub fn write_proof(&mut self, target: impl io::Write + 'a, format: ProofFormat) {
assert!(
self.ctx.solver_state.formula_is_empty,
"called after clauses were added"
);
self.ctx.proof.write_proof(target, format);
}
/// Stop generating a proof of unsatisfiability.
///
/// This also flushes internal buffers and closes the target file.
pub fn close_proof(&mut self) -> Result<(), SolverError> {
let mut ctx = self.ctx.into_partial_ref_mut();
proof::close_proof(ctx.borrow());
self.check_for_solver_error()
}
/// Generate and check a proof on the fly.
///
/// This needs to be called before any clauses are added.
pub fn enable_self_checking(&mut self) {
assert!(
self.ctx.solver_state.formula_is_empty,
"called after clauses were added"
);
self.ctx.proof.begin_checking();
}
/// Generate a proof and process it using a [`ProofProcessor`].
///
/// This implicitly enables self checking.
///
/// This needs to be called before any clauses are added.
pub fn add_proof_processor(&mut self, processor: &'a mut dyn ProofProcessor) {
assert!(
self.ctx.solver_state.formula_is_empty,
"called after clauses were added"
);
self.ctx.proof.add_processor(processor);
}
}
impl<'a> Drop for Solver<'a> {
fn drop(&mut self) {
let _ = self.close_proof();
}
}
impl<'a> ExtendFormula for Solver<'a> {
/// Add a clause to the solver.
fn add_clause(&mut self, clause: &[Lit]) {
let mut ctx = self.ctx.into_partial_ref_mut();
load_clause(ctx.borrow(), clause);
}
/// Add a new variable to the solver.
fn new_var(&mut self) -> Var {
self.ctx.solver_state.formula_is_empty = false;
let mut ctx = self.ctx.into_partial_ref_mut();
variables::new_user_var(ctx.borrow())
}
}
#[cfg(test)]
mod tests {
use super::*;
use proptest::prelude::*;
use varisat_checker::{CheckedProofStep, CheckerData};
use varisat_formula::{
cnf_formula, lits,
test::{sat_formula, sgen_unsat_formula},
};
use varisat_dimacs::write_dimacs;
fn enable_test_schedule(solver: &mut Solver) {
let mut config = SolverConfigUpdate::new();
config.reduce_locals_interval = Some(150);
config.reduce_mids_interval = Some(100);
solver.config(&config).unwrap();
}
#[test]
#[should_panic(expected = "solve() called after encountering an unrecoverable error")]
fn error_handling_proof_writing() {
let mut output_buffer = [0u8; 4];
let mut solver = Solver::new();
let proof_output = std::io::Cursor::new(&mut output_buffer[..]);
solver.write_proof(proof_output, ProofFormat::Varisat);
solver.add_formula(&cnf_formula![
-1, -2, -3; -1, -2, -4; -1, -2, -5; -1, -3, -4; -1, -3, -5; -1, -4, -5; -2, -3, -4;
-2, -3, -5; -2, -4, -5; -3, -4, -5; 1, 2, 5; 1, 2, 3; 1, 2, 4; 1, 5, 3; 1, 5, 4;
1, 3, 4; 2, 5, 3; 2, 5, 4; 2, 3, 4; 5, 3, 4;
]);
let result = solver.solve();
assert!(match result {
Err(SolverError::ProofIoError { .. }) => true,
_ => false,
});
let _ = solver.solve();
}
struct FailingProcessor;
impl ProofProcessor for FailingProcessor {
fn process_step(
&mut self,
_step: &CheckedProofStep,
_data: CheckerData,
) -> Result<(), Error> {
anyhow::bail!("failing processor");
}
}
#[test]
#[should_panic(expected = "solve() called after encountering an unrecoverable error")]
fn error_handling_proof_processing() {
let mut processor = FailingProcessor;
let mut solver = Solver::new();
solver.add_proof_processor(&mut processor);
solver.add_formula(&cnf_formula![
-1, -2, -3; -1, -2, -4; -1, -2, -5; -1, -3, -4; -1, -3, -5; -1, -4, -5; -2, -3, -4;
-2, -3, -5; -2, -4, -5; -3, -4, -5; 1, 2, 5; 1, 2, 3; 1, 2, 4; 1, 5, 3; 1, 5, 4;
1, 3, 4; 2, 5, 3; 2, 5, 4; 2, 3, 4; 5, 3, 4;
]);
let result = solver.solve();
assert!(match result {
Err(SolverError::ProofProcessorError { cause }) => {
format!("{}", cause) == "failing processor"
}
_ => false,
});
let _ = solver.solve();
}
#[test]
#[should_panic(expected = "called after clauses were added")]
fn write_proof_too_late() {
let mut solver = Solver::new();
solver.add_clause(&lits![1, 2, 3]);
solver.write_proof(std::io::sink(), ProofFormat::Varisat);
}
#[test]
#[should_panic(expected = "called after clauses were added")]
fn add_proof_processor_too_late() {
let mut processor = FailingProcessor;
let mut solver = Solver::new();
solver.add_clause(&lits![1, 2, 3]);
solver.add_proof_processor(&mut processor);
}
#[test]
#[should_panic(expected = "called after clauses were added")]
fn enable_self_checking_too_late() {
let mut solver = Solver::new();
solver.add_clause(&lits![1, 2, 3]);
solver.enable_self_checking();
}
#[test]
fn self_check_duplicated_unit_clauses() {
let mut solver = Solver::new();
solver.enable_self_checking();
solver.add_formula(&cnf_formula![
4;
4;
]);
assert_eq!(solver.solve().ok(), Some(true));
}
proptest! {
#[test]
fn sgen_unsat(
formula in sgen_unsat_formula(1..7usize),
test_schedule in proptest::bool::ANY,
) {
let mut solver = Solver::new();
solver.add_formula(&formula);
if test_schedule {
enable_test_schedule(&mut solver);
}
prop_assert_eq!(solver.solve().ok(), Some(false));
}
#[test]
fn sgen_unsat_checked(
formula in sgen_unsat_formula(1..7usize),
test_schedule in proptest::bool::ANY,
) {
let mut solver = Solver::new();
solver.enable_self_checking();
solver.add_formula(&formula);
if test_schedule {
enable_test_schedule(&mut solver);
}
prop_assert_eq!(solver.solve().ok(), Some(false));
}
#[test]
fn sat(
formula in sat_formula(4..20usize, 10..100usize, 0.05..0.2, 0.9..1.0),
test_schedule in proptest::bool::ANY,
) {
let mut solver = Solver::new();
solver.add_formula(&formula);
if test_schedule {
enable_test_schedule(&mut solver);
}
prop_assert_eq!(solver.solve().ok(), Some(true));
let model = solver.model().unwrap();
for clause in formula.iter() {
prop_assert!(clause.iter().any(|lit| model.contains(lit)));
}
}
#[test]
fn sat_via_dimacs(formula in sat_formula(4..20usize, 10..100usize, 0.05..0.2, 0.9..1.0)) {
let mut solver = Solver::new();
let mut dimacs = vec![];
write_dimacs(&mut dimacs, &formula).unwrap();
solver.add_dimacs_cnf(&mut &dimacs[..]).unwrap();
prop_assert_eq!(solver.solve().ok(), Some(true));
let model = solver.model().unwrap();
for clause in formula.iter() {
prop_assert!(clause.iter().any(|lit| model.contains(lit)));
}
}
#[test]
fn sgen_unsat_incremental_clauses(formula in sgen_unsat_formula(1..7usize)) {
let mut solver = Solver::new();
let mut last_state = Some(true);
for clause in formula.iter() {
solver.add_clause(clause);
let state = solver.solve().ok();
if state != last_state {
prop_assert_eq!(state, Some(false));
prop_assert_eq!(last_state, Some(true));
last_state = state;
}
}
prop_assert_eq!(last_state, Some(false));
}
}
}
|
pub mod codegen;
pub mod context;
pub mod stored_value;
pub mod constexpr;
|
#[doc = "Reader of register MOSCCTL"]
pub type R = crate::R<u32, super::MOSCCTL>;
#[doc = "Writer for register MOSCCTL"]
pub type W = crate::W<u32, super::MOSCCTL>;
#[doc = "Register MOSCCTL `reset()`'s with value 0"]
impl crate::ResetValue for super::MOSCCTL {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `CVAL`"]
pub type CVAL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CVAL`"]
pub struct CVAL_W<'a> {
w: &'a mut W,
}
impl<'a> CVAL_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 `MOSCIM`"]
pub type MOSCIM_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `MOSCIM`"]
pub struct MOSCIM_W<'a> {
w: &'a mut W,
}
impl<'a> MOSCIM_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 `NOXTAL`"]
pub type NOXTAL_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `NOXTAL`"]
pub struct NOXTAL_W<'a> {
w: &'a mut W,
}
impl<'a> NOXTAL_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 `PWRDN`"]
pub type PWRDN_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PWRDN`"]
pub struct PWRDN_W<'a> {
w: &'a mut W,
}
impl<'a> PWRDN_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 `OSCRNG`"]
pub type OSCRNG_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OSCRNG`"]
pub struct OSCRNG_W<'a> {
w: &'a mut W,
}
impl<'a> OSCRNG_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
}
}
impl R {
#[doc = "Bit 0 - Clock Validation for MOSC"]
#[inline(always)]
pub fn cval(&self) -> CVAL_R {
CVAL_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - MOSC Failure Action"]
#[inline(always)]
pub fn moscim(&self) -> MOSCIM_R {
MOSCIM_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - No Crystal Connected"]
#[inline(always)]
pub fn noxtal(&self) -> NOXTAL_R {
NOXTAL_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - Power Down"]
#[inline(always)]
pub fn pwrdn(&self) -> PWRDN_R {
PWRDN_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - Oscillator Range"]
#[inline(always)]
pub fn oscrng(&self) -> OSCRNG_R {
OSCRNG_R::new(((self.bits >> 4) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - Clock Validation for MOSC"]
#[inline(always)]
pub fn cval(&mut self) -> CVAL_W {
CVAL_W { w: self }
}
#[doc = "Bit 1 - MOSC Failure Action"]
#[inline(always)]
pub fn moscim(&mut self) -> MOSCIM_W {
MOSCIM_W { w: self }
}
#[doc = "Bit 2 - No Crystal Connected"]
#[inline(always)]
pub fn noxtal(&mut self) -> NOXTAL_W {
NOXTAL_W { w: self }
}
#[doc = "Bit 3 - Power Down"]
#[inline(always)]
pub fn pwrdn(&mut self) -> PWRDN_W {
PWRDN_W { w: self }
}
#[doc = "Bit 4 - Oscillator Range"]
#[inline(always)]
pub fn oscrng(&mut self) -> OSCRNG_W {
OSCRNG_W { w: self }
}
}
|
use std::cmp::Ordering;
use std::convert::From;
use std::fmt;
use std::net::{AddrParseError, Ipv4Addr, Ipv6Addr};
use std::str::FromStr;
use std::u128;
#[derive(Debug, Clone, Copy)]
struct Ipv4Range {
ip: u32,
cidr: u8,
}
#[derive(Debug, Clone, Copy)]
struct Ipv6Range {
ip: u128,
cidr: u8,
}
impl PartialEq for Ipv4Range {
fn eq(&self, other: &Self) -> bool {
self.ip == other.ip
}
}
impl PartialEq for Ipv6Range {
fn eq(&self, other: &Self) -> bool {
self.ip == other.ip
}
}
impl Eq for Ipv4Range {}
impl Eq for Ipv6Range {}
impl PartialOrd for Ipv4Range {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.ip.partial_cmp(&other.ip)
}
}
impl PartialOrd for Ipv6Range {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
self.ip.partial_cmp(&other.ip)
}
}
impl Ord for Ipv4Range {
fn cmp(&self, other: &Self) -> Ordering {
self.ip.cmp(&other.ip)
}
}
impl Ord for Ipv6Range {
fn cmp(&self, other: &Self) -> Ordering {
self.ip.cmp(&other.ip)
}
}
#[derive(Debug, Clone)]
enum RangeParseError {
MoreThanOneSlash,
IpInvalid(AddrParseError),
CidrInvalid,
}
trait IpRange: Sized {
fn normalize(&mut self) -> &mut Self;
fn _set_cidr(&mut self, c: u8) -> &mut Self;
fn _reduce_cidr_by_one(&mut self) -> &mut Self;
fn is_subset_of(&self, other: &Self) -> bool;
fn is_superset_of(&self, other: &Self) -> bool;
fn merge_with(&self, other: &Self) -> Option<Self>;
}
impl IpRange for Ipv4Range {
fn normalize(&mut self) -> &mut Self {
match self.cidr {
0 => self.ip = 0,
1..=31 => self.ip &= <u32>::max_value() << (32 - self.cidr),
32 => {}
_ => panic!("invalid CIDR size {}", self.cidr),
};
self
}
fn _set_cidr(&mut self, c: u8) -> &mut Self {
self.cidr = c;
self
}
fn _reduce_cidr_by_one(&mut self) -> &mut Self {
match self.cidr {
0 => self,
n => {
self.cidr = n - 1;
self.normalize()
}
}
}
fn is_subset_of(&self, other: &Self) -> bool {
self.cidr >= other.cidr && self.clone()._set_cidr(other.cidr).normalize().ip == other.ip
}
fn is_superset_of(&self, other: &Self) -> bool {
self.cidr <= other.cidr && other.clone()._set_cidr(self.cidr).normalize().ip == self.ip
}
fn merge_with(&self, other: &Self) -> Option<Self> {
if self.is_subset_of(other) {
Some(*other)
} else if other.is_subset_of(self) {
Some(*self)
} else if self.cidr != other.cidr {
None
} else if self.clone()._reduce_cidr_by_one().ip == other.clone()._reduce_cidr_by_one().ip {
// two adjacent networks, e.g.
// 192.168.1.0/24 and 192.168.0.0/24
// can be merged to
// 192.168.0.0/23
Some(*(self.clone()._reduce_cidr_by_one()))
} else {
None
}
}
}
impl IpRange for Ipv6Range {
fn normalize(&mut self) -> &mut Self {
match self.cidr {
0 => self.ip = 0,
1..=127 => self.ip &= <u128>::max_value() << (128 - self.cidr),
128 => {}
_ => panic!("invalid CIDR size {}", self.cidr),
};
self
}
fn _set_cidr(&mut self, c: u8) -> &mut Self {
self.cidr = c;
self
}
fn _reduce_cidr_by_one(&mut self) -> &mut Self {
match self.cidr {
0 => self,
n => {
self.cidr = n - 1;
self.normalize()
}
}
}
fn is_subset_of(&self, other: &Self) -> bool {
self.cidr >= other.cidr && self.clone()._set_cidr(other.cidr).normalize().ip == other.ip
}
fn is_superset_of(&self, other: &Self) -> bool {
self.cidr <= other.cidr && other.clone()._set_cidr(self.cidr).normalize().ip == self.ip
}
fn merge_with(&self, other: &Self) -> Option<Self> {
if self.is_subset_of(other) {
Some(*other)
} else if other.is_subset_of(self) {
Some(*self)
} else if self.cidr != other.cidr {
None
} else if self.clone()._reduce_cidr_by_one().ip == other.clone()._reduce_cidr_by_one().ip {
// two adjacent networks, e.g.
// 192.168.1.0/24 and 192.168.0.0/24
// can be merged to
// 192.168.0.0/23
Some(*(self.clone()._reduce_cidr_by_one()))
} else {
None
}
}
}
impl fmt::Display for Ipv4Range {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}/{}", Ipv4Addr::from(self.ip), self.cidr)
}
}
impl fmt::Display for Ipv6Range {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}/{}", Ipv6Addr::from(self.ip), self.cidr)
}
}
impl FromStr for Ipv4Range {
type Err = RangeParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let slashes: Vec<&str> = s.trim().split("/").collect();
match (slashes.len(), slashes[0].parse::<Ipv4Addr>()) {
(1..=2, Err(e)) => Err(RangeParseError::IpInvalid(e)),
(1, Ok(i)) => Ok(Ipv4Range {
ip: i.into(),
cidr: 32,
}),
(2, Ok(i)) => match slashes[1].parse() {
Ok(n) => match n {
0..=32 => {
let mut res = Ipv4Range {
ip: i.into(),
cidr: n,
};
res.normalize();
Ok(res)
}
_ => Err(RangeParseError::CidrInvalid),
},
Err(_) => Err(RangeParseError::CidrInvalid),
},
_ => Err(RangeParseError::MoreThanOneSlash),
}
}
}
impl FromStr for Ipv6Range {
type Err = RangeParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let slashes: Vec<&str> = s.trim().split("/").collect();
match (slashes.len(), slashes[0].parse::<Ipv6Addr>()) {
(1, Err(e)) => Err(RangeParseError::IpInvalid(e)),
(2, Err(e)) => Err(RangeParseError::IpInvalid(e)),
(1, Ok(i)) => Ok(Ipv6Range {
ip: i.into(),
cidr: 32,
}),
(2, Ok(i)) => match slashes[1].parse() {
Ok(n) => match n {
0..=128 => {
let mut res = Ipv6Range {
ip: i.into(),
cidr: n,
};
res.normalize();
Ok(res)
}
_ => Err(RangeParseError::CidrInvalid),
},
Err(_) => Err(RangeParseError::CidrInvalid),
},
_ => Err(RangeParseError::MoreThanOneSlash),
}
}
}
#[derive(Debug, Clone)]
struct IpRangeList {
v4: Vec<Ipv4Range>,
v6: Vec<Ipv6Range>,
}
impl fmt::Display for IpRangeList {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ipv4: [")?;
for i in &self.v4 {
write!(f, "{}, ", i)?;
}
writeln!(f, "]")?;
write!(f, "ipv6: [")?;
for i in &self.v6 {
write!(f, "{}, ", i)?;
}
write!(f, "]")?;
Ok(())
}
}
impl IpRangeList {
fn new() -> Self {
Self {
v4: Vec::new(),
v6: Vec::new(),
}
}
fn empty(&mut self) -> &mut Self {
self.v4 = Vec::new();
self.v6 = Vec::new();
self
}
fn add_list(&mut self, other: IpRangeList) -> &mut Self {
for i in other.v4 {
self.add_v4(i);
}
for i in other.v6 {
self.add_v6(i);
}
self
}
fn substract_list(&mut self, other: IpRangeList) -> &mut Self {
for i in other.v4 {
self.substract_v4(i);
}
for i in other.v6 {
self.substract_v6(i);
}
self
}
fn neighbor_merge_v4(&mut self, idx: usize) -> &mut Self {
if idx > 0 {
if let Some(r) = self.v4[idx - 1].merge_with(&self.v4[idx]) {
// delete one, replace one
self.v4.remove(idx - 1);
self.v4[idx - 1] = r;
// we have to try again, if we can merge the newly created one, too
self.neighbor_merge_v4(idx - 1);
} else {
};
} else {
};
if idx + 1 < self.v4.len() {
if let Some(r) = self.v4[idx].merge_with(&self.v4[idx + 1]) {
// delete one, replace one
self.v4.remove(idx);
self.v4[idx] = r;
// we have to try again, if we can merge the newly created one, too
self.neighbor_merge_v4(idx);
} else {
};
} else {
};
self
}
fn add_v4(&mut self, i: Ipv4Range) -> &mut Self {
match self.v4.binary_search_by(|probe| probe.cmp(&i)) {
Ok(idx) => match i.merge_with(&self.v4[idx]) {
Some(r) => {
self.v4[idx] = r;
self.neighbor_merge_v4(idx)
}
None => unreachable!(),
},
Err(idx) => {
self.v4.insert(idx, i);
self.neighbor_merge_v4(idx)
}
}
}
fn neighbor_merge_v6(&mut self, idx: usize) -> &mut Self {
if idx > 0 {
if let Some(r) = self.v6[idx - 1].merge_with(&self.v6[idx]) {
// delete one, replace one
self.v6.remove(idx - 1);
self.v6[idx - 1] = r;
// we have to try again, if we can merge the newly created one, too
self.neighbor_merge_v6(idx - 1);
} else {
};
} else {
};
if idx + 1 < self.v6.len() {
if let Some(r) = self.v6[idx].merge_with(&self.v6[idx + 1]) {
// delete one, replace one
self.v6.remove(idx);
self.v6[idx] = r;
// we have to try again, if we can merge the newly created one, too
self.neighbor_merge_v6(idx);
} else {
};
} else {
};
self
}
fn add_v6(&mut self, i: Ipv6Range) -> &mut Self {
match self.v6.binary_search_by(|probe| probe.cmp(&i)) {
Ok(idx) => match i.merge_with(&self.v6[idx]) {
Some(r) => {
self.v6[idx] = r;
self.neighbor_merge_v6(idx)
}
None => unreachable!(),
},
Err(idx) => {
self.v6.insert(idx, i);
self.neighbor_merge_v6(idx)
}
}
}
fn substract_v4(&mut self, i: Ipv4Range) -> &mut Self {
for it in &mut self.v4 {
unimplemented!()
}
self
}
fn substract_v6(&mut self, i: Ipv6Range) -> &mut Self {
for it in &mut self.v6 {
unimplemented!()
}
self
}
}
fn main() {}
#[cfg(test)]
mod tests {
extern crate rand;
use self::rand::seq::SliceRandom;
use self::rand::*;
use super::*;
#[test]
fn parse_addresses() {
let i: Ipv4Range = " 1.2.3.4 ".parse().unwrap();
let i: Ipv4Range = " 1.2.3.4/0 ".parse().unwrap();
let i: Ipv4Range = "1.2.3.4/32".parse().unwrap();
let i: Ipv6Range = "::1".parse().unwrap();
let i: Ipv6Range = "::1/0".parse().unwrap();
let i: Ipv6Range = "::1/128".parse().unwrap();
}
#[test]
fn sub_and_superset1a() {
let i: Ipv4Range = "255.255.255.255/32".parse().unwrap();
for c in 0..32 {
let j = format!("255.255.255.255/{}", c);
let j: Ipv4Range = j.parse().unwrap();
assert!(i.is_superset_of(&i));
assert!(i.is_subset_of(&i));
assert!(j.is_superset_of(&j));
assert!(j.is_subset_of(&j));
assert!(!i.is_superset_of(&j));
assert!(i.is_subset_of(&j));
assert!(j.is_superset_of(&i));
assert!(!j.is_subset_of(&i));
}
}
#[test]
fn sub_and_superset1b() {
let i: Ipv4Range = "0.0.0.0/32".parse().unwrap();
for c in 0..32 {
let j = format!("0.0.0.0/{}", c);
let j: Ipv4Range = j.parse().unwrap();
assert!(i.is_superset_of(&i));
assert!(i.is_subset_of(&i));
assert!(j.is_superset_of(&j));
assert!(j.is_subset_of(&j));
assert!(!i.is_superset_of(&j));
assert!(i.is_subset_of(&j));
assert!(j.is_superset_of(&i));
assert!(!j.is_subset_of(&i));
}
}
#[test]
fn sub_and_superset2a() {
let i: Ipv6Range = "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/128"
.parse()
.unwrap();
for c in 0..127 {
let j = format!("ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff/{}", c);
let j: Ipv6Range = j.parse().unwrap();
assert!(i.is_superset_of(&i));
assert!(i.is_subset_of(&i));
assert!(j.is_superset_of(&j));
assert!(j.is_subset_of(&j));
assert!(!i.is_superset_of(&j));
assert!(i.is_subset_of(&j));
assert!(j.is_superset_of(&i));
assert!(!j.is_subset_of(&i));
}
}
#[test]
fn sub_and_superset2b() {
let i: Ipv6Range = "::/128".parse().unwrap();
for c in 0..127 {
let j = format!("::/{}", c);
let j: Ipv6Range = j.parse().unwrap();
assert!(i.is_superset_of(&i));
assert!(i.is_subset_of(&i));
assert!(j.is_superset_of(&j));
assert!(j.is_subset_of(&j));
assert!(!i.is_superset_of(&j));
assert!(i.is_subset_of(&j));
assert!(j.is_superset_of(&i));
assert!(!j.is_subset_of(&i));
}
}
#[test]
fn merge_with() {
let a: Ipv4Range = "192.168.0.0/24".parse().unwrap();
let b: Ipv4Range = "192.168.1.0/24".parse().unwrap();
let c: Ipv4Range = "192.168.2.0/24".parse().unwrap();
let d: Ipv4Range = "192.168.0.0/23".parse().unwrap();
for i in [a, b, c, d].iter() {
assert!(i.merge_with(i).unwrap() == *i);
}
assert!(a.merge_with(&b).unwrap() == d);
assert!(a.merge_with(&c).is_none());
assert!(a.merge_with(&d).unwrap() == d);
assert!(b.merge_with(&a).unwrap() == d);
assert!(b.merge_with(&c).is_none());
assert!(b.merge_with(&d).unwrap() == d);
assert!(c.merge_with(&a).is_none());
assert!(c.merge_with(&b).is_none());
assert!(c.merge_with(&d).is_none());
assert!(d.merge_with(&a).unwrap() == d);
assert!(d.merge_with(&b).unwrap() == d);
assert!(d.merge_with(&c).is_none());
}
#[test]
fn add_v4() {
let mut l = IpRangeList::new();
let mut tmp: Vec<Ipv4Range> = Vec::new();
for a in 0..256 {
let j = format!("192.168.{}.1/24", a);
let j: Ipv4Range = j.parse().unwrap();
tmp.push(j);
}
tmp.shuffle(&mut rand::thread_rng());
for i in 0..256 {
l.add_v4(tmp[i]);
println!("***************************************");
println!("{}", tmp[i]);
println!("{}", l);
}
assert!(l.v4.len() == 1);
assert!(
l.v4[0]
== Ipv4Range {
ip: 192 * 256 * 256 * 256 + 168 * 256 * 256,
cidr: 16
}
);
}
fn _generate_random_list() -> IpRangeList {
match rand::thread_rng().gen_range(1..=2) {
1..=2 => (),
_ => unreachable!(),
}
IpRangeList::new()
}
}
|
use crate::assembler::program_parsers::program;
use crate::vm::VM;
use std;
use std::fs::File;
use std::io;
use std::io::prelude::*;
use std::io::Write;
use std::path::Path;
use crate::assembler::Assembler;
pub struct REPL {
command_buffer: Vec<String>,
vm: VM,
asm: Assembler,
}
impl REPL {
pub fn new() -> REPL {
REPL {
vm: VM::new(),
command_buffer: vec![],
asm: Assembler::new(),
}
}
pub fn run(&mut self) {
println!("Welcome!");
loop {
let mut buffer = String::new();
let stdin = io::stdin();
print!(">>> ");
io::stdout().flush().expect("Unable to flush stdout");
stdin
.read_line(&mut buffer)
.expect("Unable to read line from user");
let buffer = buffer.trim();
self.command_buffer.push(buffer.to_string());
match buffer {
"quit" => {
println!("Thank you");
std::process::exit(0);
}
"history" => {
for command in &self.command_buffer {
println!("{}", command);
}
}
"program" => {
for instruction in &self.vm.program {
println!("{}", instruction);
}
}
"registers" => {
println!("print out registers list");
println!("{:#?}", self.vm.registers);
}
".symbols" => {
println!("Listing symbols table:");
println!("{:#?}", self.asm.symbols);
println!("End of Symbols Listing");
}
".load_file" => {
println!("Please enter the path which you want to load:");
io::stdout().flush().expect("Unable to flush stdout");
let mut path = String::new();
stdin
.read_line(&mut path)
.expect("Unable to read line from user");
let _path = path.trim();
let filename = Path::new(&_path);
let mut file = match File::open(&filename) {
Ok(file) => file,
Err(e) => {
println!("Cannot open the file {:?}: ", e);
continue;
}
};
let mut contents = String::new();
file.read_to_string(&mut contents)
.expect("There was an error reading from file");
match self.asm.assemble(&contents) {
Ok(mut assembled_program) => {
self.vm.program.append(&mut assembled_program);
println!("{:#?}", self.vm.program);
self.vm.run();
}
Err(errors) => {
for e in errors {
println!("Unable to parse input: {}", e);
}
continue;
}
}
}
_ => {
let program = match program(buffer.into()) {
Ok((_remainder, program)) => program,
Err(e) => {
println!("Unable to parse input: {:?}", e);
continue;
}
};
self.vm
.program
.append(&mut program.to_bytes(&self.asm.symbols));
self.vm.run_once();
}
}
}
}
}
|
use jsonrpc_http_server::{jsonrpc_core::{Compatibility, IoHandler, Params, Value}, ServerBuilder, jsonrpc_core};
use futures::channel::{mpsc};
use futures::executor::block_on;
use futures::{StreamExt, TryFutureExt};
use futures::future::FutureExt;
// Massbit dependencies
use tokio02_spawn::core::abort_on_panic;
use tokio02_spawn::core::tokio02_spawn;
use crate::helper::{loop_blocks};
use crate::types::{IndexManager, DeployParams};
impl IndexManager {
pub fn serve(
http_addr: String,
) -> jsonrpc_http_server::Server {
// Use mpsc channel to spawn tokio 0.2 because json-rpc-http-server crate is not updated to tokio 0.2
let mut handler = IoHandler::with_compatibility(Compatibility::Both);
let (task_sender, task_receiver) =
mpsc::channel::<Box<dyn std::future::Future<Output = ()> + Send + Unpin>>(100);
tokio::spawn(task_receiver.for_each(|f| {
async {
tokio::task::spawn_blocking(move || block_on(abort_on_panic(f)));
}
}));
let sender = task_sender.clone();
handler.add_method("index_deploy", move|params: Params| {
Box::pin(tokio02_spawn(
sender.clone(),
async move {
let params = params.parse().unwrap();
deploy_handler(params).await
}.boxed(),
)).compat()
});
// Start the server
let server = ServerBuilder::new(handler)
.start_http(&http_addr.parse().unwrap())
.expect("Unable to start RPC server");
server
}
}
async fn deploy_handler(
params: DeployParams,
) -> Result<Value, jsonrpc_core::Error> {
#[allow(unused_must_use)]
tokio::spawn(async move{
loop_blocks(params).await;// Start streaming and indexing blocks
});
Ok(serde_json::to_value("Deploy index success").expect("Unable to deploy new index"))
} |
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
mod parser;
mod generator;
use std::fs::File;
use std::path::Path;
use std::io::Read;
use std::error::Error;
// TODO: Use error_chain!
pub fn translate(input_filename: &str, output_filename: &Path) -> Result<(), Box<Error>> {
let mut f = File::open(input_filename)?;
let mut s = String::new();
f.read_to_string(&mut s)?;
let s: parser::Schema = s.parse()?;
generator::generate(output_filename, s)?;
Ok(())
}
|
//! Quite complex implementation for possibly timed out operation. Needed to be this complex so
//! that any Unpin traits and such the inner future might have are properly reimplemented (by
//! leveraging futures combinators).
use futures::future::{Either, Map};
use std::future::Future;
use std::time::Duration;
use tokio::time::{error::Elapsed, timeout, Timeout};
pub type MaybeTimeout<F> =
Either<Timeout<F>, Map<F, fn(<F as Future>::Output) -> Result<<F as Future>::Output, Elapsed>>>;
fn ok_never_elapsed<V>(v: V) -> Result<V, Elapsed> {
Ok(v)
}
/// Extends futures with `maybe_timeout` which allows timeouting based on the repeated `timeout:
/// Option<StringSerialized<humantime::Duration>>` field in the API method options.
pub trait MaybeTimeoutExt {
/// Possibly wraps this future in a timeout, depending of whether the duration is given or not.
///
/// Returns a wrapper which will always return whatever the this future returned, wrapped in a
/// Result with the possibility of elapsing the `maybe_duration`.
fn maybe_timeout<D: Into<Duration>>(self, maybe_duration: Option<D>) -> MaybeTimeout<Self>
where
Self: Future + Sized,
{
use futures::future::FutureExt;
let maybe_duration: Option<Duration> = maybe_duration.map(|to_d| to_d.into());
if let Some(dur) = maybe_duration {
Either::Left(timeout(dur, self))
} else {
Either::Right(self.map(ok_never_elapsed))
}
}
}
impl<T: Future> MaybeTimeoutExt for T {}
|
//! Log and trace initialization and setup
use std::cmp::max;
pub use trogging::config::*;
pub use trogging::{self, TroggingGuard};
use trogging::{
cli::LoggingConfigBuilderExt,
tracing_subscriber::{prelude::*, Registry},
};
/// Start simple logger. Panics on error.
pub fn init_simple_logs(log_verbose_count: u8) -> Result<TroggingGuard, trogging::Error> {
trogging::Builder::new()
.with_log_verbose_count(log_verbose_count)
.install_global()
}
/// Start log or trace emitter. Panics on error.
pub fn init_logs_and_tracing(
log_verbose_count: u8,
config: &crate::commands::run::Config,
) -> Result<TroggingGuard, trogging::Error> {
let mut logging_config = config.logging_config().clone();
// Handle the case if -v/-vv is specified both before and after the server
// command
logging_config.log_verbose_count = max(logging_config.log_verbose_count, log_verbose_count);
let log_layer = trogging::Builder::new()
.with_logging_config(&logging_config)
.build()?;
let layers = log_layer;
// Optionally enable the tokio console exporter layer, if enabled.
//
// This spawns a background tokio task to serve the instrumentation data,
// and hooks the instrumentation into the tracing pipeline.
#[cfg(feature = "tokio_console")]
let layers = {
use console_subscriber::ConsoleLayer;
let console_layer = ConsoleLayer::builder().with_default_env().spawn();
layers.and_then(console_layer)
};
let subscriber = Registry::default().with(layers);
trogging::install_global(subscriber)
}
|
use input_i_scanner::{scan_with, InputIScanner};
fn main() {
let stdin = std::io::stdin();
let mut _i_i = InputIScanner::from(stdin.lock());
let t = scan_with!(_i_i, usize);
for _ in 0..t {
let n = scan_with!(_i_i, usize);
let a = scan_with!(_i_i, u64; n);
solve(n, a);
}
}
fn solve(n: usize, a: Vec<u64>) {
let mut l = 1;
for i in 0..n {
l = lcm(l, (i + 2) as u64);
if l > 1_000_000_000 {
break;
}
if a[i] % l == 0 {
println!("NO");
return;
}
}
println!("YES");
}
fn gcd(a: u64, b: u64) -> u64 {
if b == 0 {
a
} else {
gcd(b, a % b)
}
}
fn lcm(a: u64, b: u64) -> u64 {
a / gcd(a, b) * b
}
|
use std::collections::VecDeque;
use super::ArcDynFact;
#[derive(Clone)]
pub struct FactsRow<In> {
pub(super) cells: VecDeque<ArcDynFact<In>>,
pub(super) value: usize,
}
#[derive(Clone)]
pub struct FactsTable<In> {
pub(super) rows: VecDeque<FactsRow<In>>,
}
impl<In> FactsRow<In> {
pub fn new<I: IntoIterator<Item = ArcDynFact<In>>>(facts: I, value: usize) -> Self {
let cells = facts.into_iter().collect();
Self { cells, value }
}
}
impl<In> FactsTable<In> {
pub fn from_rows<I: IntoIterator<Item = FactsRow<In>>>(rows: I) -> Self {
let rows = rows.into_iter().collect();
Self { rows }
}
}
|
#[doc = r"Register block"]
#[repr(C)]
pub struct RegisterBlock {
#[doc = "0x00 - Master Timer Control Register"]
pub mcr: MCR,
#[doc = "0x04 - Master Timer Interrupt Status Register"]
pub misr: MISR,
#[doc = "0x08 - Master Timer Interrupt Clear Register"]
pub micr: MICR,
#[doc = "0x0c - MDIER4"]
pub mdier: MDIER,
#[doc = "0x10 - Master Timer Counter Register"]
pub mcntr: MCNTR,
#[doc = "0x14 - Master Timer Period Register"]
pub mper: MPER,
#[doc = "0x18 - Master Timer Repetition Register"]
pub mrep: MREP,
#[doc = "0x1c - Master Timer Compare 1 Register"]
pub mcmp1r: MCMP1R,
_reserved8: [u8; 4usize],
#[doc = "0x24 - Master Timer Compare 2 Register"]
pub mcmp2r: MCMP2R,
#[doc = "0x28 - Master Timer Compare 3 Register"]
pub mcmp3r: MCMP3R,
#[doc = "0x2c - Master Timer Compare 4 Register"]
pub mcmp4r: MCMP4R,
}
#[doc = "Master Timer Control Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mcr](mcr) module"]
pub type MCR = crate::Reg<u32, _MCR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MCR;
#[doc = "`read()` method returns [mcr::R](mcr::R) reader structure"]
impl crate::Readable for MCR {}
#[doc = "`write(|w| ..)` method takes [mcr::W](mcr::W) writer structure"]
impl crate::Writable for MCR {}
#[doc = "Master Timer Control Register"]
pub mod mcr;
#[doc = "Master Timer Interrupt Status Register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [misr](misr) module"]
pub type MISR = crate::Reg<u32, _MISR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MISR;
#[doc = "`read()` method returns [misr::R](misr::R) reader structure"]
impl crate::Readable for MISR {}
#[doc = "Master Timer Interrupt Status Register"]
pub mod misr;
#[doc = "Master Timer Interrupt Clear Register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [micr](micr) module"]
pub type MICR = crate::Reg<u32, _MICR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MICR;
#[doc = "`write(|w| ..)` method takes [micr::W](micr::W) writer structure"]
impl crate::Writable for MICR {}
#[doc = "Master Timer Interrupt Clear Register"]
pub mod micr;
#[doc = "MDIER4\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mdier](mdier) module"]
pub type MDIER = crate::Reg<u32, _MDIER>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MDIER;
#[doc = "`read()` method returns [mdier::R](mdier::R) reader structure"]
impl crate::Readable for MDIER {}
#[doc = "`write(|w| ..)` method takes [mdier::W](mdier::W) writer structure"]
impl crate::Writable for MDIER {}
#[doc = "MDIER4"]
pub mod mdier;
#[doc = "Master Timer Counter Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mcntr](mcntr) module"]
pub type MCNTR = crate::Reg<u32, _MCNTR>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MCNTR;
#[doc = "`read()` method returns [mcntr::R](mcntr::R) reader structure"]
impl crate::Readable for MCNTR {}
#[doc = "`write(|w| ..)` method takes [mcntr::W](mcntr::W) writer structure"]
impl crate::Writable for MCNTR {}
#[doc = "Master Timer Counter Register"]
pub mod mcntr;
#[doc = "Master Timer Period Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mper](mper) module"]
pub type MPER = crate::Reg<u32, _MPER>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MPER;
#[doc = "`read()` method returns [mper::R](mper::R) reader structure"]
impl crate::Readable for MPER {}
#[doc = "`write(|w| ..)` method takes [mper::W](mper::W) writer structure"]
impl crate::Writable for MPER {}
#[doc = "Master Timer Period Register"]
pub mod mper;
#[doc = "Master Timer Repetition Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mrep](mrep) module"]
pub type MREP = crate::Reg<u32, _MREP>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MREP;
#[doc = "`read()` method returns [mrep::R](mrep::R) reader structure"]
impl crate::Readable for MREP {}
#[doc = "`write(|w| ..)` method takes [mrep::W](mrep::W) writer structure"]
impl crate::Writable for MREP {}
#[doc = "Master Timer Repetition Register"]
pub mod mrep;
#[doc = "Master Timer Compare 1 Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mcmp1r](mcmp1r) module"]
pub type MCMP1R = crate::Reg<u32, _MCMP1R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MCMP1R;
#[doc = "`read()` method returns [mcmp1r::R](mcmp1r::R) reader structure"]
impl crate::Readable for MCMP1R {}
#[doc = "`write(|w| ..)` method takes [mcmp1r::W](mcmp1r::W) writer structure"]
impl crate::Writable for MCMP1R {}
#[doc = "Master Timer Compare 1 Register"]
pub mod mcmp1r;
#[doc = "Master Timer Compare 2 Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mcmp2r](mcmp2r) module"]
pub type MCMP2R = crate::Reg<u32, _MCMP2R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MCMP2R;
#[doc = "`read()` method returns [mcmp2r::R](mcmp2r::R) reader structure"]
impl crate::Readable for MCMP2R {}
#[doc = "`write(|w| ..)` method takes [mcmp2r::W](mcmp2r::W) writer structure"]
impl crate::Writable for MCMP2R {}
#[doc = "Master Timer Compare 2 Register"]
pub mod mcmp2r;
#[doc = "Master Timer Compare 3 Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mcmp3r](mcmp3r) module"]
pub type MCMP3R = crate::Reg<u32, _MCMP3R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MCMP3R;
#[doc = "`read()` method returns [mcmp3r::R](mcmp3r::R) reader structure"]
impl crate::Readable for MCMP3R {}
#[doc = "`write(|w| ..)` method takes [mcmp3r::W](mcmp3r::W) writer structure"]
impl crate::Writable for MCMP3R {}
#[doc = "Master Timer Compare 3 Register"]
pub mod mcmp3r;
#[doc = "Master Timer Compare 4 Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mcmp4r](mcmp4r) module"]
pub type MCMP4R = crate::Reg<u32, _MCMP4R>;
#[allow(missing_docs)]
#[doc(hidden)]
pub struct _MCMP4R;
#[doc = "`read()` method returns [mcmp4r::R](mcmp4r::R) reader structure"]
impl crate::Readable for MCMP4R {}
#[doc = "`write(|w| ..)` method takes [mcmp4r::W](mcmp4r::W) writer structure"]
impl crate::Writable for MCMP4R {}
#[doc = "Master Timer Compare 4 Register"]
pub mod mcmp4r;
|
use std::io;
fn main() {
let mut buffer = String::new();
io::stdin().read_line(&mut buffer).unwrap();
let input_num_vec: Vec<i64> = buffer
.trim()
.split_whitespace()
.map(|c| c.parse().unwrap())
.collect();
let first_num = input_num_vec[0];
let second_num = input_num_vec[1];
let third_num = input_num_vec[2];
println!("{} {} {}", third_num, first_num, second_num);
}
|
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;
fn main() {
input! {
n: usize,
m: usize,
k: usize,
ab: [(Usize1, Usize1); m],
cd: [(Usize1, Usize1); k],
}
let mut graph = vec![vec![]; n];
for &(ai, bi) in &ab {
graph[ai].push(bi);
graph[bi].push(ai);
}
let mut components = vec![INF; n];
for w in 0..n {
if components[w] != INF {
continue;
}
let mut queue = VecDeque::new();
queue.push_back(w);
while let Some(u) = queue.pop_front() {
if components[u] != INF {
continue;
}
components[u] = w;
for &v in &graph[u] {
queue.push_back(v);
}
}
}
let mut components_set = HashMap::new();
for u in 0..n {
components_set
.entry(components[u])
.or_insert(HashSet::new())
.insert(u);
}
// eprintln!("{:?}", components_set);
for &(ci, di) in &cd {
if components[ci] == components[di] {
graph[ci].push(di);
graph[di].push(ci);
}
}
for u in 0..n {
print!(
"{} ",
components_set[&components[u]].len() - graph[u].len() - 1
);
}
println!("");
}
|
#![feature(macro_rules)]
use runge_kutta::{step_rk2, step_rk4};
mod runge_kutta;
#[deriving(Show)]
struct State {
p: f64,
v: f64
}
impl Add<State, State> for State {
fn add(&self, rhs: &State) -> State {
State { p: self.p + rhs.p, v: self.v + rhs.v }
}
}
impl Mul<f64, State> for State {
fn mul(&self, rhs: &f64) -> State {
State { p: self.p * (*rhs), v: self.v * (*rhs) }
}
}
impl runge_kutta::State for State {
fn f(&self, _: f64) -> State {
State { p: self.v, v: -0.1 * self.p }
}
}
fn simple_rk_test {
// This is currently just a test of the RK integrators:
let mut t = 0f64;
let mut y2 = State { p: 1.0f64, v: 0.0f64 };
let mut y4 = y2;
let dt = 0.5f64;
for _ in range(0i, 1000) {
println!("{:0.1f}\t{:+0.6f}\t{:+0.6f}", t, y2.p, y4.p);
y2 = step_rk2(t, dt, &y2);
y4 = step_rk4(t, dt, &y4);
t += dt;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.