text stringlengths 8 4.13M |
|---|
// 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::fmt::Debug;
use std::fmt::Formatter;
use std::sync::Arc;
use common_exception::ErrorCode;
use common_exception::Result;
use crate::pipe::Pipe;
use crate::pipe::PipeItem;
use crate::processors::port::InputPort;
use crate::processors::port::OutputPort;
use crate::processors::processor::ProcessorPtr;
use crate::processors::DuplicateProcessor;
use crate::processors::ResizeProcessor;
use crate::processors::ShuffleProcessor;
use crate::SinkPipeBuilder;
use crate::SourcePipeBuilder;
use crate::TransformPipeBuilder;
/// The struct of new pipeline
/// +----------+
/// +--->|Processors|
/// | +----------+
/// +----------+ |
/// +-->|SimplePipe|---+
/// | +----------+ | +-----------+
/// +-----------+ | | +-->|inputs_port|
/// +------>|max threads| | | +-----+ | +-----------+
/// | +-----------+ | +--->>|ports|--+
/// +----------+ | +-----+ | | +-----+ | +------------+
/// | pipeline |------+ |pipe1|----+ | +-->|outputs_port|
/// +----------+ | +-------+ +-----+ | +----------+ | +------------+
/// +------>| pipes |------>| ... | +-->|ResizePipe|---+
/// +-------+ +-----+ +----------+ |
/// |pipeN| | +---------+
/// +-----+ +--->|Processor|
/// +---------+
pub struct Pipeline {
max_threads: usize,
pub pipes: Vec<Pipe>,
on_init: Option<InitCallback>,
on_finished: Option<FinishedCallback>,
}
impl Debug for Pipeline {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(f, "{:?}", &self.pipes)
}
}
pub type InitCallback = Box<dyn FnOnce() -> Result<()> + Send + Sync + 'static>;
pub type FinishedCallback =
Box<dyn FnOnce(&Option<ErrorCode>) -> Result<()> + Send + Sync + 'static>;
impl Pipeline {
pub fn create() -> Pipeline {
Pipeline {
max_threads: 0,
pipes: Vec::new(),
on_init: None,
on_finished: None,
}
}
pub fn is_empty(&self) -> bool {
self.pipes.is_empty()
}
// We need to push data to executor
pub fn is_pushing_pipeline(&self) -> Result<bool> {
match self.pipes.first() {
Some(pipe) => Ok(pipe.input_length != 0),
None => Err(ErrorCode::Internal(
"Logical error, call is_pushing on empty pipeline.",
)),
}
}
// We need to pull data from executor
pub fn is_pulling_pipeline(&self) -> Result<bool> {
match self.pipes.last() {
Some(pipe) => Ok(pipe.output_length != 0),
None => Err(ErrorCode::Internal(
"Logical error, call is_pulling on empty pipeline.",
)),
}
}
// We just need to execute it.
pub fn is_complete_pipeline(&self) -> Result<bool> {
Ok(
!self.pipes.is_empty()
&& !self.is_pushing_pipeline()?
&& !self.is_pulling_pipeline()?,
)
}
pub fn add_pipe(&mut self, pipe: Pipe) {
self.pipes.push(pipe);
}
pub fn input_len(&self) -> usize {
match self.pipes.first() {
None => 0,
Some(pipe) => pipe.input_length,
}
}
pub fn output_len(&self) -> usize {
match self.pipes.last() {
None => 0,
Some(pipe) => pipe.output_length,
}
}
pub fn set_max_threads(&mut self, max_threads: usize) {
let mut max_pipe_size = 0;
for pipe in &self.pipes {
max_pipe_size = std::cmp::max(max_pipe_size, pipe.items.len());
}
self.max_threads = std::cmp::min(max_pipe_size, max_threads);
}
pub fn get_max_threads(&self) -> usize {
self.max_threads
}
pub fn add_transform<F>(&mut self, f: F) -> Result<()>
where F: Fn(Arc<InputPort>, Arc<OutputPort>) -> Result<ProcessorPtr> {
let mut transform_builder = TransformPipeBuilder::create();
for _index in 0..self.output_len() {
let input_port = InputPort::create();
let output_port = OutputPort::create();
let processor = f(input_port.clone(), output_port.clone())?;
transform_builder.add_transform(input_port, output_port, processor);
}
self.add_pipe(transform_builder.finalize());
Ok(())
}
// Add source processor to pipeline.
// numbers: how many output pipe numbers.
pub fn add_source<F>(&mut self, f: F, numbers: usize) -> Result<()>
where F: Fn(Arc<OutputPort>) -> Result<ProcessorPtr> {
if numbers == 0 {
return Err(ErrorCode::Internal(
"Source output port numbers cannot be zero.",
));
}
let mut source_builder = SourcePipeBuilder::create();
for _index in 0..numbers {
let output = OutputPort::create();
source_builder.add_source(output.clone(), f(output)?);
}
self.add_pipe(source_builder.finalize());
Ok(())
}
// Add sink processor to pipeline.
pub fn add_sink<F>(&mut self, f: F) -> Result<()>
where F: Fn(Arc<InputPort>) -> Result<ProcessorPtr> {
let mut sink_builder = SinkPipeBuilder::create();
for _ in 0..self.output_len() {
let input = InputPort::create();
sink_builder.add_sink(input.clone(), f(input)?);
}
self.add_pipe(sink_builder.finalize());
Ok(())
}
/// Add a ResizePipe to pipes
pub fn resize(&mut self, new_size: usize) -> Result<()> {
match self.pipes.last() {
None => Err(ErrorCode::Internal("Cannot resize empty pipe.")),
Some(pipe) if pipe.output_length == 0 => {
Err(ErrorCode::Internal("Cannot resize empty pipe."))
}
Some(pipe) if pipe.output_length == new_size => Ok(()),
Some(pipe) => {
let processor = ResizeProcessor::create(pipe.output_length, new_size);
let inputs_port = processor.get_inputs().to_vec();
let outputs_port = processor.get_outputs().to_vec();
self.pipes
.push(Pipe::create(inputs_port.len(), outputs_port.len(), vec![
PipeItem::create(
ProcessorPtr::create(Box::new(processor)),
inputs_port,
outputs_port,
),
]));
Ok(())
}
}
}
/// Duplite a pipe input to two outputs.
///
/// If `force_finish_together` enabled, once one output is finished, the other output will be finished too.
pub fn duplicate(&mut self, force_finish_together: bool) -> Result<()> {
match self.pipes.last() {
Some(pipe) if pipe.output_length > 0 => {
let mut items = Vec::with_capacity(pipe.output_length);
for _ in 0..pipe.output_length {
let input = InputPort::create();
let output1 = OutputPort::create();
let output2 = OutputPort::create();
let processor = DuplicateProcessor::create(
input.clone(),
output1.clone(),
output2.clone(),
force_finish_together,
);
items.push(PipeItem::create(
ProcessorPtr::create(Box::new(processor)),
vec![input],
vec![output1, output2],
));
}
self.pipes.push(Pipe::create(
pipe.output_length,
pipe.output_length * 2,
items,
));
Ok(())
}
_ => Err(ErrorCode::Internal("Cannot duplicate empty pipe.")),
}
}
/// Used to re-order the input data according to the rule.
///
/// `rule` is a vector of [usize], each element is the index of the output port.
///
/// For example, if the rule is `[1, 2, 0]`, the data flow will be:
///
/// - input 0 -> output 1
/// - input 1 -> output 2
/// - input 2 -> output 0
pub fn reorder_inputs(&mut self, rule: Vec<usize>) {
match self.pipes.last() {
Some(pipe) if pipe.output_length > 1 => {
debug_assert!(rule.len() == pipe.output_length);
let mut inputs = Vec::with_capacity(pipe.output_length);
let mut outputs = Vec::with_capacity(pipe.output_length);
for _ in 0..pipe.output_length {
inputs.push(InputPort::create());
outputs.push(OutputPort::create());
}
let processor = ShuffleProcessor::create(inputs.clone(), outputs.clone(), rule);
self.pipes
.push(Pipe::create(inputs.len(), outputs.len(), vec![
PipeItem::create(
ProcessorPtr::create(Box::new(processor)),
inputs,
outputs,
),
]));
}
_ => {}
}
}
pub fn set_on_init<F: FnOnce() -> Result<()> + Send + Sync + 'static>(&mut self, f: F) {
if let Some(old_on_init) = self.on_init.take() {
self.on_init = Some(Box::new(move || {
old_on_init()?;
f()
}));
return;
}
self.on_init = Some(Box::new(f));
}
pub fn set_on_finished<F: FnOnce(&Option<ErrorCode>) -> Result<()> + Send + Sync + 'static>(
&mut self,
f: F,
) {
if let Some(on_finished) = self.on_finished.take() {
self.on_finished = Some(Box::new(move |may_error| {
on_finished(may_error)?;
f(may_error)
}));
return;
}
self.on_finished = Some(Box::new(f));
}
pub fn take_on_init(&mut self) -> InitCallback {
match self.on_init.take() {
None => Box::new(|| Ok(())),
Some(on_init) => on_init,
}
}
pub fn take_on_finished(&mut self) -> FinishedCallback {
match self.on_finished.take() {
None => Box::new(|_may_error| Ok(())),
Some(on_finished) => on_finished,
}
}
}
impl Drop for Pipeline {
fn drop(&mut self) {
// An error may have occurred before the executor was created.
if let Some(on_finished) = self.on_finished.take() {
(on_finished)(&None).ok();
}
}
}
|
use std::ffi::OsStr;
#[cfg(not(any(target_os = "macos", windows)))]
use std::fs;
use std::io;
#[cfg(windows)]
use std::os::windows::process::CommandExt;
use std::process::{Command, Stdio};
#[rustfmt::skip]
#[cfg(not(windows))]
use {
std::error::Error,
std::os::unix::process::CommandExt,
std::os::unix::io::RawFd,
std::path::PathBuf,
};
#[cfg(not(windows))]
use libc::pid_t;
#[cfg(windows)]
use windows_sys::Win32::System::Threading::{CREATE_NEW_PROCESS_GROUP, CREATE_NO_WINDOW};
#[cfg(target_os = "macos")]
use crate::macos;
/// Start a new process in the background.
#[cfg(windows)]
pub fn spawn_daemon<I, S>(program: &str, args: I) -> io::Result<()>
where
I: IntoIterator<Item = S> + Copy,
S: AsRef<OsStr>,
{
// Setting all the I/O handles to null and setting the
// CREATE_NEW_PROCESS_GROUP and CREATE_NO_WINDOW has the effect
// that console applications will run without opening a new
// console window.
Command::new(program)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.creation_flags(CREATE_NEW_PROCESS_GROUP | CREATE_NO_WINDOW)
.spawn()
.map(|_| ())
}
/// Start a new process in the background.
#[cfg(not(windows))]
pub fn spawn_daemon<I, S>(
program: &str,
args: I,
master_fd: RawFd,
shell_pid: u32,
) -> io::Result<()>
where
I: IntoIterator<Item = S> + Copy,
S: AsRef<OsStr>,
{
let mut command = Command::new(program);
command.args(args).stdin(Stdio::null()).stdout(Stdio::null()).stderr(Stdio::null());
if let Ok(cwd) = foreground_process_path(master_fd, shell_pid) {
command.current_dir(cwd);
}
unsafe {
command
.pre_exec(|| {
match libc::fork() {
-1 => return Err(io::Error::last_os_error()),
0 => (),
_ => libc::_exit(0),
}
if libc::setsid() == -1 {
return Err(io::Error::last_os_error());
}
Ok(())
})
.spawn()?
.wait()
.map(|_| ())
}
}
/// Get working directory of controlling process.
#[cfg(not(windows))]
pub fn foreground_process_path(
master_fd: RawFd,
shell_pid: u32,
) -> Result<PathBuf, Box<dyn Error>> {
let mut pid = unsafe { libc::tcgetpgrp(master_fd) };
if pid < 0 {
pid = shell_pid as pid_t;
}
#[cfg(not(any(target_os = "macos", target_os = "freebsd")))]
let link_path = format!("/proc/{}/cwd", pid);
#[cfg(target_os = "freebsd")]
let link_path = format!("/compat/linux/proc/{}/cwd", pid);
#[cfg(not(target_os = "macos"))]
let cwd = fs::read_link(link_path)?;
#[cfg(target_os = "macos")]
let cwd = macos::proc::cwd(pid)?;
Ok(cwd)
}
|
use std::io::{self, Write};
use std::os::unix::net::UnixStream;
use std::path::Path;
#[repr(u8)]
pub enum Command {
Disable = 0,
Enable = 1,
#[allow(dead_code)]
TriggerNow = 2,
}
pub struct XIdleHookClient {
stream: UnixStream,
}
impl XIdleHookClient {
/// Initializes a new XIdleHookClient for a socket at the given path.
pub fn new<P: AsRef<Path>>(path: P) -> Result<Self, io::Error> {
let stream = UnixStream::connect(path)?;
Ok(XIdleHookClient { stream })
}
/// Sends the specified command to the XIdleHook socket
pub fn send(&mut self, cmd: Command) -> Result<(), io::Error> {
self.stream.write(&[cmd as u8]).map(|_| ())
}
}
|
use shared_bus::{I2cProxy, NullMutex};
use ssd1306::{displaysize::DisplaySize128x32, prelude::*, Builder, I2CDIBuilder};
use stm32f4xx_hal::{
gpio::{
gpioa::{self, PA10, PA6, PA7, PA9},
gpiob::{PB8, PB9},
Alternate, AlternateOD, OpenDrain, Output, PushPull, AF4, AF7,
},
i2c::I2c,
prelude::*,
rcc::Clocks,
serial::{
self,
config::{Parity, StopBits, WordLength},
Event as SerialEvent, Serial,
},
stm32::{I2C1, TIM1, USART1},
timer::Timer,
};
use crate::radiohead_ask;
type I2CInterfaceProxy<'t> =
I2cProxy<'t, NullMutex<I2c<I2C1, (PB8<AlternateOD<AF4>>, PB9<AlternateOD<AF4>>)>>>;
type MLX90614<'t> = mlx9061x::Mlx9061x<I2CInterfaceProxy<'t>, mlx9061x::ic::Mlx90614>;
type DHT11 = dht11::Dht11<PA6<Output<OpenDrain>>>;
type UARTPins = (PA9<Alternate<AF7>>, PA10<Alternate<AF7>>);
pub type RadioHeadASK = radiohead_ask::RadioHeadASK<PA7<Output<PushPull>>, Timer<TIM1>>;
pub fn setup_display<I>(i2c: I) -> GraphicsMode<I2CInterface<I>, DisplaySize128x32>
where
I: embedded_hal::blocking::i2c::Write,
{
let interface = I2CDIBuilder::new().init(i2c);
let mut disp: GraphicsMode<_, _> = Builder::new()
.size(DisplaySize128x32)
.connect(interface)
.into();
disp.init().unwrap();
disp.flush().unwrap();
disp
}
pub fn setup(
gpioa: gpioa::Parts,
i2c: I2CInterfaceProxy,
clocks: Clocks,
tim1: TIM1,
usart1: USART1
) -> (MLX90614, DHT11, RadioHeadASK, Serial<USART1, UARTPins>) {
let humidity_sensor: DHT11 = dht11::Dht11::new(gpioa.pa6.into_open_drain_output());
let temperature_sensor =
mlx9061x::Mlx9061x::new_mlx90614(i2c, mlx9061x::SlaveAddr::Alternative(0x5a), 5).unwrap();
let uart_cfg = serial::config::Config {
baudrate: 9600.bps(),
parity: Parity::ParityNone,
wordlength: WordLength::DataBits8,
stopbits: StopBits::STOP1,
};
let timer = Timer::tim1(tim1, 200.khz(), clocks);
let mut uart = serial::Serial::usart1(
usart1,
(
gpioa.pa9.into_alternate_af7(),
gpioa.pa10.into_alternate_af7(),
),
uart_cfg,
clocks,
)
.unwrap();
uart.listen(SerialEvent::Rxne);
let radio = radiohead_ask::RadioHeadASK::new(gpioa.pa7.into_push_pull_output(), timer);
(temperature_sensor, humidity_sensor, radio, uart)
}
|
use crate::ast::{Loop, LoopKind};
use crate::lexer::*;
use crate::parsers::expression::assignment::multiple::left_hand_side;
use crate::parsers::expression::assignment::multiple::multiple_left_hand_side;
use crate::parsers::expression::expression;
use crate::parsers::program::compound_statement;
use crate::parsers::program::separator;
/// `while` *expression* *do_clause* `end`
pub(crate) fn while_expression(i: Input) -> NodeResult {
map(
tuple((tag("while"), ws0, expression, do_clause, tag("end"))),
|t| {
Node::Loop(Loop {
kind: LoopKind::While,
cond: Box::new(t.2),
body: Box::new(t.3),
bindings: None,
})
},
)(i)
}
/// *separator* *compound_statement* | [ no ⏎ ] `do` *compound_statement*
pub(crate) fn do_clause(i: Input) -> NodeResult {
alt((
map(tuple((separator, compound_statement)), |t| t.1),
map(tuple((no_lt, tag("do"), compound_statement)), |t| t.2),
))(i)
}
/// `until` *expression* *do_clause* `end`
pub(crate) fn until_expression(i: Input) -> NodeResult {
map(
tuple((tag("until"), ws0, expression, do_clause, tag("end"))),
|t| {
Node::Loop(Loop {
kind: LoopKind::Until,
cond: Box::new(t.2),
body: Box::new(t.3),
bindings: None,
})
},
)(i)
}
/// `for` *for_variable* [ no ⏎ ] `in` *expression* *do_clause* `end`
pub(crate) fn for_expression(i: Input) -> NodeResult {
map(
tuple((
tag("for"),
ws0,
for_variable,
no_lt,
tag("in"),
ws0,
expression,
ws0,
do_clause,
tag("end"),
)),
|_| Node::Placeholder,
)(i)
}
/// *left_hand_side* | *multiple_left_hand_side*
pub(crate) fn for_variable(i: Input) -> NodeResult {
alt((left_hand_side, multiple_left_hand_side))(i)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_while_expression() {
use_parser!(while_expression);
// Parse errors
assert_err!("while 1\ndo 2 end");
assert_err!("while 1do2; 3end");
// Success cases
assert_ok!(
"while 1\n2end",
Node::loop_(
LoopKind::While,
Node::int(1),
Node::Block(vec![Node::int(2)]),
vec![]
)
);
assert_ok!(
"while 1do 2; 3end",
Node::loop_(
LoopKind::While,
Node::int(1),
Node::Block(vec![Node::int(2), Node::int(3)]),
vec![]
)
);
assert_ok!(
"while 1 \n2\n3\nend",
Node::loop_(
LoopKind::While,
Node::int(1),
Node::Block(vec![Node::int(2), Node::int(3)]),
vec![]
)
);
}
#[test]
fn test_until_expression() {
use_parser!(until_expression);
// Parse errors
assert_err!("until 1\ndo 2 end");
assert_err!("until 1do2; 3end");
// Success cases
assert_ok!(
"until 1; 2; 3; end",
Node::loop_(
LoopKind::Until,
Node::int(1),
Node::Block(vec![Node::int(2), Node::int(3)]),
vec![]
)
);
}
}
|
use lazy_static::lazy_static;
use std::collections::HashMap;
#[derive(Debug, Eq, PartialEq, Clone, Copy, Hash)]
pub enum TokenType {
Plus,
Minus,
Asterisk,
Slash,
Assign,
Bang,
LessThan,
GreaterThan,
Equal,
NotEqual,
Comma,
Semicolon,
LParen,
RParen,
LBrace,
RBrace,
True,
False,
Let,
Function,
If,
Else,
Return,
Int,
Ident,
EOF,
Illegal,
}
impl TokenType {
pub fn is_keyword(self) -> bool {
match self {
TokenType::True
| TokenType::False
| TokenType::Let
| TokenType::Function
| TokenType::If
| TokenType::Else
| TokenType::Return
| TokenType::Ident => true,
_ => false,
}
}
pub fn is_int(self) -> bool {
self == TokenType::Int
}
pub fn is_eof(self) -> bool {
self == TokenType::EOF
}
}
impl Default for TokenType {
fn default() -> Self {
TokenType::Illegal
}
}
impl std::fmt::Display for TokenType {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
write!(
f,
"{}",
match self {
TokenType::Plus => "Plus",
TokenType::Minus => "Minus",
TokenType::Asterisk => "Asterisk",
TokenType::Slash => "Slash",
TokenType::Assign => "Assign",
TokenType::Bang => "Bang",
TokenType::LessThan => "LessThan",
TokenType::GreaterThan => "GreaterThan",
TokenType::Equal => "Equal",
TokenType::NotEqual => "NotEqual",
TokenType::LParen => "LParen",
TokenType::RParen => "RParen",
TokenType::LBrace => "LBrace",
TokenType::RBrace => "RBrace",
TokenType::Comma => "Comma",
TokenType::Semicolon => "Semicolon",
TokenType::True => "True",
TokenType::False => "False",
TokenType::Let => "Let",
TokenType::Function => "Function",
TokenType::If => "If",
TokenType::Else => "Else",
TokenType::Return => "Return",
TokenType::Int => "Int",
TokenType::Ident => "Ident",
TokenType::EOF => "EOF",
TokenType::Illegal => "Illegal",
}
)
}
}
lazy_static! {
pub static ref KEYWORDS: HashMap<&'static str, TokenType> = [
("true", TokenType::True),
("false", TokenType::False),
("let", TokenType::Let),
("fn", TokenType::Function),
("if", TokenType::If),
("else", TokenType::Else),
("return", TokenType::Return),
]
.iter()
.cloned()
.collect();
}
|
use tokenizer::consumers::*;
use tokenizer::symbol::Symbol;
pub mod keyword;
pub mod symbol;
pub mod consumers;
#[derive(Debug, PartialEq)]
pub enum Token {
Float(f32),
Integer(i32),
Symbol(symbol::Symbol),
Keyword(keyword::Keyword),
Constant(String),
String(String),
Comment(String),
}
pub fn tokenize(contents: &String) -> Result<Vec<Token>, Vec<String>> {
let mut it = contents.chars().peekable();
let mut tokens: Vec<Token> = vec![];
let mut line = 1;
let mut errors: Vec<String> = vec![];
loop {
match it.peek() {
Some(&ch) => match ch {
'0'...'9' => consume_number(&mut it, &mut tokens, &mut errors, line),
'-' | '*' | '+' | '/' | '<' | '>' | '=' | '!' | '&' | '|' | '%' => consume_operator(&mut it, &mut tokens),
'~' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::Arrow)),
'(' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::LParen)),
')' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::RParen)),
'[' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::LSquareBracket)),
']' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::RSquareBracket)),
'{' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::LCurlyBracket)),
'}' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::RCurlyBracket)),
'#' => consume_comment(&mut it, &mut tokens),
',' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::Comma)),
' ' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::Space)),
'\r' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::CR)),
'\n' => {
consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::LB));
line = line + 1;
}
'\'' => consume_string(&mut it, &mut tokens),
'A'...'Z' | 'a'...'z' => consume_constant(&mut it, &mut tokens),
'_' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::Underscore)),
':' => consume_token(&mut it, &mut tokens, Token::Symbol(Symbol::Colon)),
_ => {
let ch = it.next().unwrap();
errors.push(format!("Unknown character \"{}\" on Line {}", ch, line))
}
},
None => break
}
}
if errors.len() > 0 {
Err(errors)
} else {
Ok(tokens)
}
}
|
extern crate pest;
use pest::error::Error;
use pest::Parser;
#[derive(Parser)]
#[grammar = "grammars/ck2txt.pest"]
pub struct CK2Parser;
use crate::json::JSONValue;
pub fn parse(ck2txt: &str) -> Result<JSONValue, Error<Rule>> {
let parsing_iter = CK2Parser::parse(Rule::file, ck2txt)?.skip(1).next().unwrap();
use pest::iterators::Pair;
fn parse_value(pair: Pair<Rule>) -> JSONValue {
match pair.as_rule() {
Rule::object
| Rule::body => JSONValue::Object(
pair.into_inner()
.map(|pair| {
let mut inner_rules = pair.into_inner();
let inner_pair = inner_rules
.next()
.expect("inner_pair was None");
let name = inner_pair.as_str();
let value = parse_value(inner_rules.next().expect("inner_rules.next() was None"));
(name, value)
})
.collect(),
),
Rule::array => JSONValue::Array(pair.into_inner().map(parse_value).collect()),
Rule::string
| Rule::date => JSONValue::String(pair.into_inner().next().unwrap().as_str()),
Rule::tag => JSONValue::String(pair.as_str()),
Rule::number => JSONValue::Number(pair.as_str().parse().unwrap()),
Rule::boolean => JSONValue::Boolean(pair.as_str() == "yes"),
Rule::file
| Rule::EOI
| Rule::header
| Rule::identifier
| Rule::checksum
| Rule::pair
| Rule::value
| Rule::inner
| Rule::char
| Rule::int
| Rule::float
| Rule::date_inner
| Rule::WHITESPACE => {
println!("Rule: {:?}", pair.as_rule());
println!("Span: {:?}", pair.as_span());
println!("Text: {}", pair.as_str());
unreachable!()
}
}
}
Ok(parse_value(parsing_iter))
}
|
use otspec::{read_field, stateful_deserializer};
use serde::de::{DeserializeSeed, SeqAccess, Visitor};
use serde::{Serialize, Serializer};
#[derive(Debug, PartialEq)]
pub struct loca {
pub indices: Vec<Option<u32>>,
}
stateful_deserializer!(
loca,
LocaDeserializer,
{ locaIs32Bit: bool },
fn visit_seq<A>(self, mut seq: A) -> std::result::Result<loca, A::Error>
where
A: SeqAccess<'de>,
{
let mut res = loca {
indices: Vec::new(),
};
let raw_indices: Vec<u32> = if self.locaIs32Bit {
read_field!(seq, Vec<u32>, "a glyph offset")
} else {
read_field!(seq, Vec<u16>, "a glyph offset")
.iter()
.map(|x| (*x as u32) * 2)
.collect()
};
if raw_indices.is_empty() {
// No glyphs, eh?
return Ok(res);
}
for ab in raw_indices.windows(2) {
if let [a, b] = ab {
if *a == *b {
res.indices.push(None);
} else {
res.indices.push(Some(*a));
}
}
}
Ok(res)
}
);
impl Serialize for loca {
fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
panic!(
"loca cannot be serialized directly. Call compile_glyf_loca_maxp on the font instead"
)
// But we still want an impl here to dispatch the Table serializer in Font
}
}
pub fn from_bytes(s: &[u8], locaIs32Bit: bool) -> otspec::error::Result<loca> {
let mut deserializer = otspec::de::Deserializer::from_bytes(s);
let cs: LocaDeserializer = LocaDeserializer { locaIs32Bit };
cs.deserialize(&mut deserializer)
}
#[cfg(test)]
mod tests {
use crate::loca;
#[test]
fn loca_de_16bit() {
let binary_loca = vec![0x00, 0x00, 0x01, 0x30, 0x01, 0x30, 0x01, 0x4c];
let floca = loca::from_bytes(&binary_loca, false).unwrap();
let locations = [Some(0), None, Some(608)];
// println!("{:?}", floca);
assert_eq!(floca.indices, locations);
}
}
|
mod utils;
// we only compile js if we target wasm
#[cfg(target_arch = "wasm32")]
pub mod js;
// we only compile python if we target python build
#[cfg(feature = "python")]
pub mod python;
pub use x25519_dalek::PublicKey;
pub use x25519_dalek::StaticSecret;
use rand::CryptoRng;
use rand::Rng;
use chacha20poly1305::aead::{generic_array::GenericArray, Aead, NewAead};
use chacha20poly1305::{Tag, XChaCha20Poly1305};
use std::convert::From;
pub struct Nonce {
pub bytes: GenericArray<u8, <chacha20poly1305::XChaCha20Poly1305 as Aead>::NonceSize>,
}
impl From<&[u8]> for Nonce {
fn from(rand: &[u8]) -> Self {
let slice = &rand
.get(0..24)
.expect("Make sure the nonce is 192bits. We don't apply padding.");
Self {
bytes: GenericArray::clone_from_slice(&slice),
}
}
}
impl Nonce {
pub fn from_random() -> Self {
let nonce = utils::getrandom_192bits();
Self {
bytes: GenericArray::clone_from_slice(&nonce),
}
}
}
/// An x25519 keypair.
pub struct Keypair {
/// The secret half of this keypair.
pub secret: StaticSecret,
/// The public half of this keypair.
pub public: PublicKey,
}
impl Clone for Keypair {
fn clone(&self) -> Keypair {
Keypair::from_secret_key(self.secret.clone())
}
}
impl Keypair {
pub fn from_random<R>(rand: &mut R) -> Keypair
where
R: CryptoRng + Rng,
{
let secret = StaticSecret::new(rand);
Self::from_secret_key(secret)
}
pub fn generate() -> Keypair {
let mut rand = utils::getrandom();
Self::from_random(&mut rand)
}
pub fn from_secret_key(secret: StaticSecret) -> Keypair {
let public = PublicKey::from(&secret);
Keypair { secret, public }
}
}
pub struct Cipher(XChaCha20Poly1305);
impl Cipher {
pub fn new(my_secret_key: &StaticSecret, their_pub_key: &PublicKey) -> Cipher {
let shared_secret = my_secret_key.diffie_hellman(&their_pub_key);
let aead = XChaCha20Poly1305::new(GenericArray::clone_from_slice(shared_secret.as_bytes()));
Cipher(aead)
}
#[must_use]
pub fn encrypt(&self, msg: &[u8], nonce: &Nonce) -> Vec<u8> {
self.0
.encrypt(&nonce.bytes, msg)
.expect("Encryption failed")
}
#[must_use]
pub fn decrypt(&self, msg: &[u8], nonce: &Nonce) -> Vec<u8> {
self.0
.decrypt(&nonce.bytes, msg)
.expect("Decryption failed")
}
pub fn encrypt_in_place_detached(&self, msg: &mut [u8], aad: &[u8], nonce: &Nonce) -> Tag {
self.0
.encrypt_in_place_detached(&nonce.bytes, aad, msg)
.expect("Encryption failed")
}
pub fn decrypt_in_place_detached(&self, msg: &mut [u8], aad: &[u8], nonce: &Nonce, tag: &Tag) {
self.0
.decrypt_in_place_detached(&nonce.bytes, aad, msg, tag)
.expect("Decryption failed")
}
}
#[cfg(test)]
mod tests {
use super::*;
// use ascii::AsciiStr;
// use hex;
#[test]
fn test_commutative_diffie_hellman() {
let alice = Keypair::generate();
let bob = Keypair::generate();
let shared_secret1 = alice.secret.diffie_hellman(&bob.public);
let shared_secret2 = bob.secret.diffie_hellman(&alice.public);
assert_eq!(shared_secret1.as_bytes(), shared_secret2.as_bytes())
}
#[test]
fn test_cipher_identity() {
let alice = Keypair::generate();
let bob = Keypair::generate();
let plaintext = b"corona sucks";
let mut buffer = plaintext.to_vec();
let nonce = Nonce::from_random();
let mut cipher = Cipher::new(&alice.secret, &bob.public);
let tag = cipher.encrypt_in_place_detached(&mut buffer, b"", &nonce);
// let ascii_str_cipher = hex::encode(&buffer);
// println!("Cipher: {:#?}", &ascii_str_cipher);
cipher.decrypt_in_place_detached(&mut buffer, b"", &nonce, &tag);
// let ascii_str_decrypted = AsciiStr::from_ascii(&decrypted).unwrap();
// println!("Encrypted {:#?}", &ascii_str_decrypted);
assert_eq!(plaintext.to_vec(), buffer);
}
#[test]
fn test_js_integration() {
let alice_secret: [u8; 32] = [
56, 4, 190, 47, 42, 57, 72, 25, 194, 75, 105, 248, 146, 43, 60, 53, 55, 165, 30, 61,
122, 57, 95, 197, 210, 123, 95, 97, 215, 28, 193, 92,
];
let bob_secret: [u8; 32] = [
64, 218, 126, 251, 171, 87, 50, 212, 196, 55, 166, 65, 195, 199, 64, 229, 128, 129,
243, 144, 211, 52, 77, 159, 48, 167, 45, 8, 79, 228, 116, 101,
];
let nonce: Nonce = [0u8; 24].as_ref().into();
let alice = Keypair::from_secret_key(alice_secret.into());
let bob = Keypair::from_secret_key(bob_secret.into());
let mut cipher = Cipher::new(&alice.secret, &bob.public);
let plaintext: [u8; 2] = [21, 31];
let mut buffer = plaintext.to_vec();
let tag = cipher.encrypt_in_place_detached(&mut buffer, b"", &nonce);
println!("Enc: {:#?}", &buffer);
assert_eq!([63 as u8, 106 as u8].to_vec(), buffer);
}
#[test]
#[should_panic]
#[allow(unused_variables)]
fn test_slice_out_of_bounds() {
let bytes = [0 as u8; 23].as_ref();
let nonce: Nonce = bytes.into();
}
}
|
#[derive(Clone, Debug, PartialEq)]
pub struct Game {
pub random_seed: i64,
pub tick_count: i32,
pub map_size: f64,
pub skills_enabled: bool,
pub raw_messages_enabled: bool,
pub friendly_fire_damage_factor: f64,
pub building_damage_score_factor: f64,
pub building_elimination_score_factor: f64,
pub minion_damage_score_factor: f64,
pub minion_elimination_score_factor: f64,
pub wizard_damage_score_factor: f64,
pub wizard_elimination_score_factor: f64,
pub team_working_score_factor: f64,
pub victory_score: i32,
pub score_gain_range: f64,
pub raw_message_max_length: i32,
pub raw_message_transmission_speed: f64,
pub wizard_radius: f64,
pub wizard_cast_range: f64,
pub wizard_vision_range: f64,
pub wizard_forward_speed: f64,
pub wizard_backward_speed: f64,
pub wizard_strafe_speed: f64,
pub wizard_base_life: i32,
pub wizard_life_growth_per_level: i32,
pub wizard_base_mana: i32,
pub wizard_mana_growth_per_level: i32,
pub wizard_base_life_regeneration: f64,
pub wizard_life_regeneration_growth_per_level: f64,
pub wizard_base_mana_regeneration: f64,
pub wizard_mana_regeneration_growth_per_level: f64,
pub wizard_max_turn_angle: f64,
pub wizard_max_resurrection_delay_ticks: i32,
pub wizard_min_resurrection_delay_ticks: i32,
pub wizard_action_cooldown_ticks: i32,
pub staff_cooldown_ticks: i32,
pub magic_missile_cooldown_ticks: i32,
pub frost_bolt_cooldown_ticks: i32,
pub fireball_cooldown_ticks: i32,
pub haste_cooldown_ticks: i32,
pub shield_cooldown_ticks: i32,
pub magic_missile_manacost: i32,
pub frost_bolt_manacost: i32,
pub fireball_manacost: i32,
pub haste_manacost: i32,
pub shield_manacost: i32,
pub staff_damage: i32,
pub staff_sector: f64,
pub staff_range: f64,
pub level_up_xp_values: Vec<i32>,
pub minion_radius: f64,
pub minion_vision_range: f64,
pub minion_speed: f64,
pub minion_max_turn_angle: f64,
pub minion_life: i32,
pub faction_minion_appearance_interval_ticks: i32,
pub orc_woodcutter_action_cooldown_ticks: i32,
pub orc_woodcutter_damage: i32,
pub orc_woodcutter_attack_sector: f64,
pub orc_woodcutter_attack_range: f64,
pub fetish_blowdart_action_cooldown_ticks: i32,
pub fetish_blowdart_attack_range: f64,
pub fetish_blowdart_attack_sector: f64,
pub bonus_radius: f64,
pub bonus_appearance_interval_ticks: i32,
pub bonus_score_amount: i32,
pub dart_radius: f64,
pub dart_speed: f64,
pub dart_direct_damage: i32,
pub magic_missile_radius: f64,
pub magic_missile_speed: f64,
pub magic_missile_direct_damage: i32,
pub frost_bolt_radius: f64,
pub frost_bolt_speed: f64,
pub frost_bolt_direct_damage: i32,
pub fireball_radius: f64,
pub fireball_speed: f64,
pub fireball_explosion_max_damage_range: f64,
pub fireball_explosion_min_damage_range: f64,
pub fireball_explosion_max_damage: i32,
pub fireball_explosion_min_damage: i32,
pub guardian_tower_radius: f64,
pub guardian_tower_vision_range: f64,
pub guardian_tower_life: f64,
pub guardian_tower_attack_range: f64,
pub guardian_tower_damage: i32,
pub guardian_tower_cooldown_ticks: i32,
pub faction_base_radius: f64,
pub faction_base_vision_range: f64,
pub faction_base_life: f64,
pub faction_base_attack_range: f64,
pub faction_base_damage: i32,
pub faction_base_cooldown_ticks: i32,
pub burning_duration_ticks: i32,
pub burning_summary_damage: i32,
pub empowered_duration_ticks: i32,
pub empowered_damage_factor: f64,
pub frozen_duration_ticks: i32,
pub hastened_duration_ticks: i32,
pub hastened_bonus_duration_factor: f64,
pub hastened_movement_bonus_factor: f64,
pub hastened_rotation_bonus_factor: f64,
pub shielded_duration_ticks: i32,
pub shielded_bonus_duration_factor: f64,
pub shielded_direct_damage_absorption_factor: f64,
pub aura_skill_range: f64,
pub range_bonus_per_skill_level: f64,
pub magical_damage_bonus_per_skill_level: i32,
pub staff_damage_bonus_per_skill_level: i32,
pub movement_bonus_factor_per_skill_level: f64,
pub magical_damage_absorption_per_skill_level: i32,
}
|
use crate::cpu::Cpu;
use crate::opcode::addressing_mode::{AddRegister, AddressMode};
use crate::opcode::*;
use std::string::ToString;
pub struct Load {
/// Addressing mode.
mode: AddressMode,
/// Which register to load from.
register: Register,
/// Convenience to store the op code.
opcode: u8,
}
impl Load {
pub fn new(opcode: u8, cpu: &Cpu) -> Option<Self> {
let register = Load::get_register(opcode)?;
Some(Load {
mode: Load::get_mode(opcode, cpu),
register,
opcode,
})
}
/// Get the register from the Load opcode.
fn get_register(opcode: u8) -> Option<Register> {
match opcode {
0xA9 | 0xA5 | 0xB5 | 0xAD | 0xBD | 0xB9 | 0xA1 | 0xB1 => Some(Register::A),
0xA2 | 0xA6 | 0xB6 | 0xAE | 0xBE => Some(Register::X),
0xA0 | 0xA4 | 0xB4 | 0xAC | 0xBC => Some(Register::Y),
_ => None,
}
}
/// Get the mode from the opcode.
fn get_mode(opcode: u8, cpu: &Cpu) -> AddressMode {
let pc = cpu.program_counter as usize;
let value = cpu.memory[pc + 1];
match opcode {
0xA9 | 0xA2 | 0xA0 => AddressMode::Immediate { value },
0xA5 | 0xA6 | 0xA4 => AddressMode::ZeroPage {
register: AddRegister::None,
offset: value,
},
0xB5 | 0xB4 => AddressMode::ZeroPage {
register: AddRegister::X,
offset: value,
},
0xB6 => AddressMode::ZeroPage {
register: AddRegister::Y,
offset: value,
},
0xAD | 0xAE | 0xAC => AddressMode::Absolute {
register: AddRegister::None,
address: bytes_to_addr(value, cpu.memory[pc + 2]),
},
0xBD | 0xBC => AddressMode::Absolute {
register: AddRegister::X,
address: bytes_to_addr(value, cpu.memory[pc + 2]),
},
0xB9 | 0xBE => AddressMode::Absolute {
register: AddRegister::X,
address: bytes_to_addr(value, cpu.memory[pc + 2]),
},
0xA1 => AddressMode::Indirect {
register: AddRegister::X,
address_to_read_indirect: bytes_to_addr(value, cpu.memory[pc + 2]),
},
0xB1 => AddressMode::Indirect {
register: AddRegister::Y,
address_to_read_indirect: bytes_to_addr(value, cpu.memory[pc + 2]),
},
_ => panic!("Unexpected opcode {:X}", opcode),
}
}
fn get_cycles(&self, cpu: &Cpu) -> u64 {
match &self.mode {
AddressMode::Immediate { value: _ } => 2,
AddressMode::ZeroPage {
register: AddRegister::None,
offset: _,
} => 3,
AddressMode::ZeroPage {
register: _,
offset: _,
} => 4,
AddressMode::Absolute {
register: AddRegister::None,
address: _,
} => 4,
AddressMode::Absolute {
register: _,
address,
} => 4 + is_on_different_pages(*address, *address + cpu.x as u16) as u64,
AddressMode::Indirect {
register: AddRegister::X,
address_to_read_indirect: _,
} => 6,
AddressMode::Indirect {
register: AddRegister::Y,
address_to_read_indirect: address,
} => 5 + is_on_different_pages(*address, *address + cpu.y as u16) as u64,
_ => panic!("Unexpected!"),
}
}
fn get_bytes(&self) -> u16 {
match &self.mode {
AddressMode::Immediate { value: _ } => 2,
AddressMode::ZeroPage {
register: _,
offset: _,
} => 2,
AddressMode::Absolute {
register: _,
address: _,
} => 3,
AddressMode::Indirect {
register: _,
address_to_read_indirect: _,
} => 2,
_ => panic!("Unexpected!"),
}
}
}
impl Operation for Load {
/// JMP simply moves to the address.
fn execute(&self, cpu: &mut Cpu) {
cpu.program_counter += self.get_bytes();
cpu.cycles += self.get_cycles(cpu);
let value = self.mode.to_value(cpu);
let target_cpu = match self.register {
Register::X => &mut cpu.x,
Register::Y => &mut cpu.y,
Register::A => &mut cpu.a,
};
*target_cpu = value;
cpu.status.update_load(*target_cpu);
}
fn dump(&self, cpu: &Cpu) -> String {
format!(
"{:02X} {} LD{} {}",
self.opcode,
self.mode.value_to_string(),
self.register.to_string(),
self.mode.to_string(cpu)
)
}
}
|
use crate::hierarchy::SceneGraph;
use crate::traits::required::*;
use crate::{
components::*,
views::{LocalTransformDataMut, LocalTransformStoragesMut},
};
use shipyard::*;
use shipyard_hierarchy::*;
use std::collections::HashSet;
pub fn local_transform_sys<V, Q, M, N>(
mut local_trs_storages_mut: LocalTransformStoragesMut<V, Q, M, N>,
mut dirty_transforms: ViewMut<DirtyTransform>,
) where
V: Vec3Ext<N> + Send + Sync + 'static,
Q: QuatExt<N> + Send + Sync + 'static,
M: Matrix4Ext<N> + Send + Sync + 'static,
N: Copy + Send + Sync + 'static,
{
//First gather all the unique ids that have been tainted by trso changes
let mut trso_ids: HashSet<EntityId> = local_trs_storages_mut
.translations
.modified()
.iter()
.ids()
.chain(
local_trs_storages_mut
.rotations
.modified()
.iter()
.ids()
.chain(
local_trs_storages_mut
.scales
.modified()
.iter()
.ids()
.chain(local_trs_storages_mut.origins.modified().iter().ids()),
),
)
.collect();
//Stash these in a full list which will also include the localtransform changes
let mut all_ids = trso_ids.clone();
//Adapt the list from LocalTransform, and set their TRSO values
local_trs_storages_mut
.local_transforms
.modified()
.iter()
.ids()
.for_each(|id| {
//TODO - derive the TRSO values and set them on the components!
//Right now all we're doing is marking-dirty direct changes to LocalTransform
//but the actual values are not being propogated
//until this is done, LocalTransform should modified in tandem with trso on the same component
//but sticking with either-or is totally fine
//don't want to re-set the transform again, it's already done!
trso_ids.remove(&id);
//but do need to mark dirty
all_ids.insert(id);
});
//For the remaining trso_ids, set the LocalTransforms
trso_ids.iter().for_each(|id| {
let LocalTransformDataMut {
translation,
rotation,
scale,
origin,
mut local_transform,
} = (&mut local_trs_storages_mut).get(*id).unwrap();
local_transform.reset_from_trs_origin(
translation.as_slice(),
rotation.as_slice(),
scale.as_slice(),
origin.as_slice(),
);
});
//Mark everything that was dirty
all_ids.iter().for_each(|id| {
let mut dirty_transform = (&mut dirty_transforms).get(*id).unwrap();
dirty_transform.0 = true;
});
//we only needed to track modified for the sake of this system
//should be cleared immediately
local_trs_storages_mut.clear_all_modified();
}
//See: https://gameprogrammingpatterns.com/dirty-flag.html
//the overall idea is we walk the tree and skip over nodes that are not dirty
//whenever we encounter a dirty node, we must also mark all of its children dirty
//finally, for each dirty node, its world transform is its parent's world transform
//multiplied by its local transform
//or in other words, it's the local transform, offset by its parent in world space
pub fn world_transform_sys<M, N>(
root: UniqueView<TransformRoot>,
parent_storage: View<Parent<SceneGraph>>,
child_storage: View<Child<SceneGraph>>,
local_transform_storage: View<LocalTransform<M, N>>,
mut dirty_transform_storage: ViewMut<DirtyTransform>,
mut world_transform_storage: ViewMut<WorldTransform<M, N>>,
) where
M: Matrix4Ext<N> + Clone + Send + Sync + 'static,
N: Copy + Send + Sync + 'static,
{
fn update<M, N>(
id: EntityId,
mut dirty: bool,
parent: EntityId,
parent_storage: &View<Parent<SceneGraph>>,
child_storage: &View<Child<SceneGraph>>,
local_transform_storage: &View<LocalTransform<M, N>>,
dirty_transform_storage: &mut ViewMut<DirtyTransform>,
world_transform_storage: &mut ViewMut<WorldTransform<M, N>>,
) where
M: Matrix4Ext<N> + Clone + Send + Sync + 'static,
N: Copy + Send + Sync + 'static,
{
let dirty_transform = &mut dirty_transform_storage[id];
let is_dirty: bool = dirty_transform.0;
dirty_transform.0 = false;
dirty |= is_dirty;
if dirty {
world_transform_storage.apply_mut(id, parent, |world_transform, parent_transform| {
*world_transform = parent_transform.clone()
});
world_transform_storage[id].mul_assign(&local_transform_storage[id]);
}
(parent_storage, child_storage)
.children(id)
.for_each(|child| {
update(
child,
dirty,
id,
parent_storage,
child_storage,
local_transform_storage,
dirty_transform_storage,
world_transform_storage,
);
});
}
//first propogate the root transform if it changed
let root_id = root.0;
let dirty_transform = &mut dirty_transform_storage[root_id];
let is_dirty: bool = dirty_transform.0;
dirty_transform.0 = false;
if is_dirty {
world_transform_storage[root_id]
.copy_from_slice(local_transform_storage[root_id].as_slice());
}
//then recursively update all the children
(&parent_storage, &child_storage)
.children(root_id)
.for_each(|child| {
update(
child,
is_dirty,
root_id,
&parent_storage,
&child_storage,
&local_transform_storage,
&mut dirty_transform_storage,
&mut world_transform_storage,
);
});
}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
crate::utils::skip,
bitfield::bitfield,
byteorder::{BigEndian, ByteOrder, LittleEndian},
num::{One, Unsigned},
num_derive::{FromPrimitive, ToPrimitive},
num_traits::{FromPrimitive, ToPrimitive},
std::{marker::PhantomData, ops::Deref},
zerocopy::{AsBytes, ByteSlice, FromBytes, LayoutVerified, Unaligned},
};
#[macro_export]
macro_rules! frame_len {
() => { 0 };
($only:ty) => { std::mem::size_of::<$only>() };
($first:ty, $($tail:ty),*) => {
std::mem::size_of::<$first>() + frame_len!($($tail),*)
};
}
type MacAddr = [u8; 6];
pub const BCAST_ADDR: MacAddr = [0xFF; 6];
// IEEE Std 802.11-2016, 9.2.4.1.3
// Frame types:
pub const FRAME_TYPE_MGMT: u16 = 0;
pub const FRAME_TYPE_DATA: u16 = 2;
// Management subtypes:
pub const MGMT_SUBTYPE_ASSOC_RESP: u16 = 0x01;
pub const MGMT_SUBTYPE_BEACON: u16 = 0x08;
pub const MGMT_SUBTYPE_AUTH: u16 = 0x0B;
pub const MGMT_SUBTYPE_DEAUTH: u16 = 0x0C;
// Data subtypes:
pub const DATA_SUBTYPE_DATA: u16 = 0x00;
pub const DATA_SUBTYPE_NULL_DATA: u16 = 0x04;
pub const DATA_SUBTYPE_QOS_DATA: u16 = 0x08;
pub const DATA_SUBTYPE_NULL_QOS_DATA: u16 = 0x0C;
// IEEE Std 802.11-2016, 9.2.4.1.3, Table 9-1
pub const BITMASK_NULL: u16 = 1 << 2;
pub const BITMASK_QOS: u16 = 1 << 3;
// RFC 1042
pub const LLC_SNAP_EXTENSION: u8 = 0xAA;
pub const LLC_SNAP_UNNUMBERED_INFO: u8 = 0x03;
pub const LLC_SNAP_OUI: [u8; 3] = [0, 0, 0];
// RFC 704, Appendix B.2
// https://www.iana.org/assignments/ieee-802-numbers/ieee-802-numbers.xhtml
pub const ETHER_TYPE_EAPOL: u16 = 0x888E;
// IEEE Std 802.11-2016, 9.2.4.1.1
bitfield! {
#[derive(PartialEq)]
pub struct FrameControl(u16);
impl Debug;
pub protocol_version, set_protocol_version: 1, 0;
pub frame_type, set_frame_type: 3, 2;
pub frame_subtype, set_frame_subtype: 7, 4;
pub to_ds, set_to_ds: 8;
pub from_ds, set_from_ds: 9;
pub more_frag, set_more_frag: 19;
pub retry, set_retry: 11;
pub pwr_mgmt, set_pwr_mgmt: 12;
pub more_data, set_more_data: 13;
pub protected, set_protected: 14;
pub htc_order, set_htc_order: 15;
pub value, _: 15,0;
}
impl FrameControl {
pub fn from_bytes(bytes: &[u8]) -> Option<FrameControl> {
if bytes.len() < 2 {
None
} else {
Some(FrameControl(LittleEndian::read_u16(bytes)))
}
}
}
// IEEE Std 802.11-2016, 9.2.4.4
bitfield! {
pub struct SequenceControl(u16);
impl Debug;
pub frag_num, set_frag_num: 3, 0;
pub seq_num, set_seq_num: 15, 4;
pub value, _: 15,0;
}
impl SequenceControl {
pub fn from_bytes(bytes: &[u8]) -> Option<SequenceControl> {
if bytes.len() < 2 {
None
} else {
Some(SequenceControl(LittleEndian::read_u16(bytes)))
}
}
}
// IEEE Std 802.11-2016, 9.2.4.6
bitfield! {
#[derive(PartialEq)]
pub struct HtControl(u32);
impl Debug;
pub vht, set_vht: 0;
// Structure of this middle section is defined in 9.2.4.6.2 for HT,
// and 9.2.4.6.3 for VHT.
pub middle, set_middle: 29, 1;
pub ac_constraint, set_ac_constraint: 30;
pub rdg_more_ppdu, setrdg_more_ppdu: 31;
pub value, _: 31,0;
}
// IEEE Std 802.11-2016, 9.4.1.4
type RawCapabilityInfo = [u8; 2];
bitfield! {
pub struct CapabilityInfo(u16);
impl Debug;
pub ess, set_ess: 0;
pub ibss, set_ibss: 1;
pub cf_pollable, set_cf_pollable: 2;
pub cf_poll_req, set_cf_poll_req: 3;
pub privacy, set_privacy: 4;
pub short_preamble, set_short_preamble: 5;
// bit 6-7 reserved
pub spectrum_mgmt, set_spectrum_mgmt: 8;
pub qos, set_qos: 9;
pub short_slot_time, set_short_slot_time: 10;
pub apsd, set_apsd: 11;
pub radio_msmt, set_radio_msmt: 12;
// bit 13 reserved
pub delayed_block_ack, set_delayed_block_ack: 14;
pub immediate_block_ack, set_immediate_block_ack: 15;
pub value, _: 15, 0;
}
// IEEE Std 802.11-2016, 9.2.4.5.1, Table 9-6
bitfield! {
pub struct QosControl(u16);
impl Debug;
pub tid, set_tid: 3, 0;
pub eosp, set_eosp: 4;
pub ack_policy, set_ack_policy: 6, 5;
pub amsdu_present, set_amsdu_present: 7;
// TODO(hahnr): Support various interpretations for remaining 8 bits.
pub value, _: 15, 0;
}
#[derive(PartialEq, Eq)]
pub struct Presence<T: ?Sized>(bool, PhantomData<T>);
pub trait OptionalField {
const PRESENT: Presence<Self> = Presence::<Self>(true, PhantomData);
const ABSENT: Presence<Self> = Presence::<Self>(false, PhantomData);
}
impl<T: ?Sized> OptionalField for T {}
// IEEE Std 802.11-2016, 9.3.3.2
#[derive(FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct MgmtHdr {
pub frame_ctrl: [u8; 2],
pub duration: [u8; 2],
pub addr1: MacAddr,
pub addr2: MacAddr,
pub addr3: MacAddr,
pub seq_ctrl: [u8; 2],
}
impl MgmtHdr {
pub fn frame_ctrl(&self) -> u16 {
LittleEndian::read_u16(&self.frame_ctrl)
}
pub fn duration(&self) -> u16 {
LittleEndian::read_u16(&self.duration)
}
pub fn seq_ctrl(&self) -> u16 {
LittleEndian::read_u16(&self.seq_ctrl)
}
pub fn set_frame_ctrl(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.frame_ctrl, val)
}
pub fn set_duration(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.duration, val)
}
pub fn set_seq_ctrl(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.seq_ctrl, val)
}
/// Returns the length in bytes of a mgmt header including all its fixed and optional
/// fields (if they are present).
pub fn len(has_ht_ctrl: Presence<HtControl>) -> usize {
let mut bytes = std::mem::size_of::<DataHdr>();
bytes += match has_ht_ctrl {
HtControl::PRESENT => std::mem::size_of::<RawHtControl>(),
HtControl::ABSENT => 0,
};
bytes
}
}
pub type Addr4 = MacAddr;
// IEEE Std 802.11-2016, 9.3.2.1
#[derive(FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct DataHdr {
pub frame_ctrl: [u8; 2],
pub duration: [u8; 2],
pub addr1: MacAddr,
pub addr2: MacAddr,
pub addr3: MacAddr,
pub seq_ctrl: [u8; 2],
}
impl DataHdr {
pub fn frame_ctrl(&self) -> u16 {
LittleEndian::read_u16(&self.frame_ctrl)
}
pub fn duration(&self) -> u16 {
LittleEndian::read_u16(&self.duration)
}
pub fn seq_ctrl(&self) -> u16 {
LittleEndian::read_u16(&self.seq_ctrl)
}
pub fn set_frame_ctrl(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.frame_ctrl, val)
}
pub fn set_duration(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.duration, val)
}
pub fn set_seq_ctrl(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.seq_ctrl, val)
}
/// Returns the length in bytes of a data header including all its fixed and optional
/// fields (if they are present).
pub fn len(
has_addr4: Presence<Addr4>,
has_qos_ctrl: Presence<QosControl>,
has_ht_ctrl: Presence<HtControl>,
) -> usize {
let mut bytes = std::mem::size_of::<DataHdr>();
bytes += match has_addr4 {
Addr4::PRESENT => std::mem::size_of::<MacAddr>(),
Addr4::ABSENT => 0,
};
bytes += match has_qos_ctrl {
QosControl::PRESENT => std::mem::size_of::<RawQosControl>(),
QosControl::ABSENT => 0,
};
bytes += match has_ht_ctrl {
HtControl::PRESENT => std::mem::size_of::<RawHtControl>(),
HtControl::ABSENT => 0,
};
bytes
}
}
#[derive(FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct RawHtControl([u8; 4]);
impl RawHtControl {
pub fn get(&self) -> u32 {
LittleEndian::read_u32(&self.0)
}
pub fn set(&mut self, val: u32) {
LittleEndian::write_u32(&mut self.0, val)
}
}
impl Deref for RawHtControl {
type Target = [u8; 4];
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[derive(FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct RawQosControl([u8; 2]);
impl RawQosControl {
pub fn get(&self) -> u16 {
LittleEndian::read_u16(&self.0)
}
pub fn set(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.0, val)
}
}
impl Deref for RawQosControl {
type Target = [u8; 2];
fn deref(&self) -> &Self::Target {
&self.0
}
}
pub enum MacFrame<B> {
Mgmt {
// Management Header: fixed fields
mgmt_hdr: LayoutVerified<B, MgmtHdr>,
// Management Header: optional fields
ht_ctrl: Option<LayoutVerified<B, RawHtControl>>,
// Body
body: B,
},
Data {
// Data Header: fixed fields
data_hdr: LayoutVerified<B, DataHdr>,
// Data Header: optional fields
addr4: Option<LayoutVerified<B, Addr4>>,
qos_ctrl: Option<LayoutVerified<B, RawQosControl>>,
ht_ctrl: Option<LayoutVerified<B, RawHtControl>>,
// Body
body: B,
},
Unsupported {
type_: u16,
},
}
impl<B: ByteSlice> MacFrame<B> {
/// If `body_aligned` is |true| the frame's body is expected to be 4 byte aligned.
pub fn parse(bytes: B, body_aligned: bool) -> Option<MacFrame<B>> {
let fc = FrameControl::from_bytes(&bytes[..])?;
match fc.frame_type() {
FRAME_TYPE_MGMT => {
// Parse fixed header fields:
let (mgmt_hdr, body) = LayoutVerified::new_unaligned_from_prefix(bytes)?;
// Parse optional header fields:
let (ht_ctrl, body) = parse_ht_ctrl_if_present(&fc, body)?;
// Skip optional padding if body alignment is used.
let body = if body_aligned {
let full_hdr_len = MgmtHdr::len(if ht_ctrl.is_some() {
HtControl::PRESENT
} else {
HtControl::ABSENT
});
skip_body_alignment_padding(full_hdr_len, body)?
} else {
body
};
Some(MacFrame::Mgmt { mgmt_hdr, ht_ctrl, body })
}
FRAME_TYPE_DATA => {
// Parse fixed header fields:
let (data_hdr, body) = LayoutVerified::new_unaligned_from_prefix(bytes)?;
// Parse optional header fields:
let (addr4, body) = parse_addr4_if_present(&fc, body)?;
let (qos_ctrl, body) = parse_qos_if_present(&fc, body)?;
let (ht_ctrl, body) = parse_ht_ctrl_if_present(&fc, body)?;
// Skip optional padding if body alignment is used.
let body = if body_aligned {
let full_hdr_len = DataHdr::len(
if addr4.is_some() { Addr4::PRESENT } else { Addr4::ABSENT },
if qos_ctrl.is_some() { QosControl::PRESENT } else { QosControl::ABSENT },
if ht_ctrl.is_some() { HtControl::PRESENT } else { HtControl::ABSENT },
);
skip_body_alignment_padding(full_hdr_len, body)?
} else {
body
};
Some(MacFrame::Data { data_hdr, addr4, qos_ctrl, ht_ctrl, body })
}
type_ => Some(MacFrame::Unsupported { type_ }),
}
}
}
/// Returns |None| if parsing fails. Otherwise returns |Some(tuple)| with `tuple` holding a
/// `MacAddr` if it is present and the remaining bytes.
fn parse_addr4_if_present<B: ByteSlice>(
fc: &FrameControl,
bytes: B,
) -> Option<(Option<LayoutVerified<B, Addr4>>, B)> {
if fc.to_ds() && fc.from_ds() {
let (addr4, bytes) = LayoutVerified::new_unaligned_from_prefix(bytes)?;
Some((Some(addr4), bytes))
} else {
Some((None, bytes))
}
}
/// Returns |None| if parsing fails. Otherwise returns |Some(tuple)| with `tuple` holding the
/// `QosControl` if it is present and the remaining bytes.
fn parse_qos_if_present<B: ByteSlice>(
fc: &FrameControl,
bytes: B,
) -> Option<(Option<LayoutVerified<B, RawQosControl>>, B)> {
if fc.frame_subtype() & BITMASK_QOS != 0 {
let (qos_ctrl, bytes) = LayoutVerified::new_unaligned_from_prefix(bytes)?;
Some((Some(qos_ctrl), bytes))
} else {
Some((None, bytes))
}
}
/// Returns |None| if parsing fails. Otherwise returns |Some(tuple)| with `tuple` holding the
/// `HtControl` if it is present and the remaining bytes.
fn parse_ht_ctrl_if_present<B: ByteSlice>(
fc: &FrameControl,
bytes: B,
) -> Option<(Option<LayoutVerified<B, RawHtControl>>, B)> {
if fc.htc_order() {
let (ht_ctrl, bytes) = LayoutVerified::new_unaligned_from_prefix(bytes)?;
Some((Some(ht_ctrl), bytes))
} else {
Some((None, bytes))
}
}
/// Skips optional padding required for body alignment.
fn skip_body_alignment_padding<B: ByteSlice>(hdr_len: usize, bytes: B) -> Option<B> {
const OPTIONAL_BODY_ALIGNMENT_BYTES: usize = 4;
let padded_len = round_up(hdr_len, OPTIONAL_BODY_ALIGNMENT_BYTES);
let padding = padded_len - hdr_len;
skip(bytes, padding)
}
// IEEE Std 802.11-2016, 9.3.3.3
#[derive(FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct BeaconHdr {
pub timestamp: [u8; 8],
pub beacon_interval: [u8; 2],
// IEEE Std 802.11-2016, 9.4.1.4
pub capabilities: RawCapabilityInfo,
}
impl BeaconHdr {
pub fn timestamp(&self) -> u64 {
LittleEndian::read_u64(&self.timestamp)
}
pub fn beacon_interval(&self) -> u16 {
LittleEndian::read_u16(&self.beacon_interval)
}
pub fn capabilities(&self) -> u16 {
LittleEndian::read_u16(&self.capabilities)
}
}
// IEEE Std 802.11-2016, 9.4.1.1
#[repr(u16)]
#[derive(Copy, Clone)]
pub enum AuthAlgorithm {
Open = 0,
_SharedKey = 1,
_FastBssTransition = 2,
Sae = 3,
// 4-65534 Reserved
_VendorSpecific = 65535,
}
/// IEEE Std 802.11-2016, 9.4.1.7
#[allow(unused)] // Some ReasonCodes are not used yet.
#[derive(Debug, PartialOrd, PartialEq, FromPrimitive, ToPrimitive)]
#[repr(C)]
pub enum ReasonCode {
// 0 Reserved
UnspecifiedReason = 1,
InvalidAuthentication = 2,
LeavingNetworkDeauth = 3,
ReasonInactivity = 4,
NoMoreStas = 5,
InvalidClass2Frame = 6,
InvalidClass3Frame = 7,
LeavingNetworkDisassoc = 8,
NotAuthenticated = 9,
UnacceptablePowerCapability = 10,
UnacceptableSupportedChannels = 11,
BssTransitionDisassoc = 12,
ReasonInvalidElement = 13,
MicFailure = 14,
FourwayHandshakeTimeout = 15,
GkHandshakeTimeout = 16,
HandshakeElementMismatch = 17,
ReasonInvalidGroupCipher = 18,
ReasonInvalidPairwiseCipher = 19,
ReasonInvalidAkmp = 20,
UnsupportedRsneVersion = 21,
InvalidRsneCapabilities = 22,
Ieee8021XAuthFailed = 23,
ReasonCipherOutOfPolicy = 24,
TdlsPeerUnreachable = 25,
TdlsUnspecifiedReason = 26,
SspRequestedDisassoc = 27,
NoSspRoamingAgreement = 28,
BadCipherOrAkm = 29,
NotAuthorizedThisLocation = 30,
ServiceChangePrecludesTs = 31,
UnspecifiedQosReason = 32,
NotEnoughBandwidth = 33,
MissingAcks = 34,
ExceededTxop = 35,
StaLeaving = 36,
EndTsBaDls = 37,
UnknownTsBa = 38,
Timeout = 39,
// 40 - 44 Reserved.
PeerkeyMismatch = 45,
PeerInitiated = 46,
ApInitiated = 47,
ReasonInvalidFtActionFrameCount = 48,
ReasonInvalidPmkid = 49,
ReasonInvalidMde = 50,
ReasonInvalidFte = 51,
MeshPeeringCanceled = 52,
MeshMaxPeers = 53,
MeshConfigurationPolicyViolation = 54,
MeshCloseRcvd = 55,
MeshMaxRetries = 56,
MeshConfirmTimeout = 57,
MeshInvalidGtk = 58,
MeshInconsistentParameters = 59,
MeshInvalidSecurityCapability = 60,
MeshPathErrorNoProxyInformation = 61,
MeshPathErrorNoForwardingInformation = 62,
MeshPathErrorDestinationUnreachable = 63,
MacAddressAlreadyExistsInMbss = 64,
MeshChannelSwitchRegulatoryRequirements = 65,
MeshChannelSwitchUnspecified = 66,
// 67-65535 Reserved
}
// IEEE Std 802.11-2016, 9.3.3.12
#[derive(Default, FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct AuthHdr {
pub auth_alg_num: [u8; 2],
pub auth_txn_seq_num: [u8; 2],
pub status_code: [u8; 2],
}
impl AuthHdr {
pub fn auth_alg_num(&self) -> u16 {
LittleEndian::read_u16(&self.auth_alg_num)
}
pub fn set_auth_alg_num(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.auth_alg_num, val)
}
pub fn auth_txn_seq_num(&self) -> u16 {
LittleEndian::read_u16(&self.auth_txn_seq_num)
}
pub fn set_auth_txn_seq_num(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.auth_txn_seq_num, val)
}
pub fn status_code(&self) -> u16 {
LittleEndian::read_u16(&self.status_code)
}
pub fn set_status_code(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.status_code, val)
}
}
// IEEE Std 802.11-2016, 9.3.3.13
#[derive(Default, FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct DeauthHdr {
pub reason_code: [u8; 2],
}
impl DeauthHdr {
pub fn reason_code(&self) -> u16 {
LittleEndian::read_u16(&self.reason_code)
}
pub fn set_reason_code(&mut self, val: u16) {
LittleEndian::write_u16(&mut self.reason_code, val)
}
}
// IEEE Std 802.11-2016, 9.3.3.6
#[derive(FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct AssocRespHdr {
// IEEE Std 802.11-2016, 9.4.1.4
pub capabilities: [u8; 2],
pub status_code: [u8; 2],
pub aid: [u8; 2],
}
impl AssocRespHdr {
pub fn capabilities(&self) -> u16 {
LittleEndian::read_u16(&self.capabilities)
}
pub fn status_code(&self) -> u16 {
LittleEndian::read_u16(&self.status_code)
}
pub fn aid(&self) -> u16 {
LittleEndian::read_u16(&self.aid)
}
}
pub enum MgmtSubtype<B> {
Beacon { bcn_hdr: LayoutVerified<B, BeaconHdr>, elements: B },
Authentication { auth_hdr: LayoutVerified<B, AuthHdr>, elements: B },
AssociationResp { assoc_resp_hdr: LayoutVerified<B, AssocRespHdr>, elements: B },
Unsupported { subtype: u16 },
}
impl<B: ByteSlice> MgmtSubtype<B> {
pub fn parse(subtype: u16, bytes: B) -> Option<MgmtSubtype<B>> {
match subtype {
MGMT_SUBTYPE_BEACON => {
let (bcn_hdr, elements) = LayoutVerified::new_unaligned_from_prefix(bytes)?;
Some(MgmtSubtype::Beacon { bcn_hdr, elements })
}
MGMT_SUBTYPE_AUTH => {
let (auth_hdr, elements) = LayoutVerified::new_unaligned_from_prefix(bytes)?;
Some(MgmtSubtype::Authentication { auth_hdr, elements })
}
MGMT_SUBTYPE_ASSOC_RESP => {
let (assoc_resp_hdr, elements) = LayoutVerified::new_unaligned_from_prefix(bytes)?;
Some(MgmtSubtype::AssociationResp { assoc_resp_hdr, elements })
}
subtype => Some(MgmtSubtype::Unsupported { subtype }),
}
}
}
// IEEE Std 802.2-1998, 3.2
// IETF RFC 1042
#[derive(FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
#[derive(Default)]
pub struct LlcHdr {
pub dsap: u8,
pub ssap: u8,
pub control: u8,
pub oui: [u8; 3],
pub protocol_id_be: [u8; 2], // In network byte order (big endian).
}
impl LlcHdr {
pub fn protocol_id(&self) -> u16 {
BigEndian::read_u16(&self.protocol_id_be)
}
pub fn set_protocol_id(&mut self, val: u16) {
BigEndian::write_u16(&mut self.protocol_id_be, val);
}
}
// IEEE Std 802.3-2015, 3.1.1
#[derive(FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct EthernetIIHdr {
pub da: MacAddr,
pub sa: MacAddr,
pub ether_type_be: [u8; 2], // In network byte order (big endian).
}
impl EthernetIIHdr {
pub fn ether_type(&self) -> u16 {
BigEndian::read_u16(&self.ether_type_be)
}
pub fn set_ether_type(&mut self, val: u16) {
BigEndian::write_u16(&mut self.ether_type_be, val)
}
}
// IEEE Std 802.11-2016, 9.3.2.2.2
#[derive(FromBytes, AsBytes, Unaligned)]
#[repr(C, packed)]
pub struct AmsduSubframeHdr {
// Note this is the same as the IEEE 802.3 frame format.
pub da: MacAddr,
pub sa: MacAddr,
pub msdu_len_be: [u8; 2], // In network byte order (big endian).
}
impl AmsduSubframeHdr {
pub fn msdu_len(&self) -> u16 {
BigEndian::read_u16(&self.msdu_len_be)
}
}
/// Iterates through an A-MSDU frame and provides access to
/// individual MSDUs.
/// The reader expects the byte stream to start with an
/// `AmsduSubframeHdr`.
pub struct AmsduReader<'a>(&'a [u8]);
impl<'a> AmsduReader<'a> {
pub fn has_remaining(&self) -> bool {
!self.0.is_empty()
}
pub fn remaining(&self) -> &'a [u8] {
self.0
}
}
impl<'a> Iterator for AmsduReader<'a> {
type Item = &'a [u8];
fn next(&mut self) -> Option<Self::Item> {
let (amsdu_subframe_hdr, msdu) =
LayoutVerified::<_, AmsduSubframeHdr>::new_unaligned_from_prefix(&self.0[..])?;
let msdu_len = amsdu_subframe_hdr.msdu_len() as usize;
if msdu.len() < msdu_len {
// A-MSDU subframe header is valid, but MSDU doesn't fit into the buffer.
None
} else {
let (msdu, next_padded) = msdu.split_at(msdu_len);
// Padding following the last MSDU is optional.
if next_padded.is_empty() {
self.0 = next_padded;
Some(msdu)
} else {
let base_len = std::mem::size_of::<AmsduSubframeHdr>() + msdu_len;
let padded_len = round_up(base_len, 4);
let padding_len = padded_len - base_len;
if next_padded.len() < padding_len {
// Corrupted: buffer to short to hold padding.
None
} else {
let (_padding, next) = next_padded.split_at(padding_len);
self.0 = next;
Some(msdu)
}
}
}
}
}
pub enum DataSubtype<B> {
// QoS or regular data type.
Data { is_qos: bool, hdr: LayoutVerified<B, LlcHdr>, payload: B },
Unsupported { subtype: u16 },
}
impl<B: ByteSlice> DataSubtype<B> {
pub fn parse(subtype: u16, bytes: B) -> Option<DataSubtype<B>> {
match subtype {
DATA_SUBTYPE_DATA | DATA_SUBTYPE_QOS_DATA => {
let (hdr, payload) = LayoutVerified::new_unaligned_from_prefix(bytes)?;
let is_qos = subtype == DATA_SUBTYPE_QOS_DATA;
Some(DataSubtype::Data { hdr, is_qos, payload })
}
subtype => Some(DataSubtype::Unsupported { subtype }),
}
}
}
/// IEEE Std 802.11-2016, 9.4.1.9, Table 9-46
#[allow(unused)] // Some StatusCodes are not used yet.
#[derive(Debug, PartialOrd, PartialEq, FromPrimitive, ToPrimitive)]
#[repr(C)]
pub enum StatusCode {
Success = 0,
Refused = 1,
TdlsRejectedAlternativeProvided = 2,
TdlsRejected = 3,
// 4 Reserved
SecurityDisabled = 5,
UnacceptableLifetime = 6,
NotInSameBss = 7,
// 8-9 Reserved
RefusedCapabilitiesMismatch = 10,
DeniedNoAssociationExists = 11,
DeniedOtherReason = 12,
UnsupportedAuthAlgorithm = 13,
TransactionSequenceError = 14,
ChallengeFailure = 15,
RejectedSequenceTimeout = 16,
DeniedNoMoreStas = 17,
RefusedBasicRatesMismatch = 18,
DeniedNoShortPreambleSupport = 19,
// 20-21 Reserved
RejectedSpectrumManagementRequired = 22,
RejectedBadPowerCapability = 23,
RejectedBadSupportedChannels = 24,
DeniedNoShortSlotTimeSupport = 25,
// 26 Reserved
DeniedNoHtSupport = 27,
R0khUnreachable = 28,
DeniedPcoTimeNotSupported = 29,
RefusedTemporarily = 30,
RobustManagementPolicyViolation = 31,
UnspecifiedQosFailure = 32,
DeniedInsufficientBandwidth = 33,
DeniedPoorChannelConditions = 34,
DeniedQosNotSupported = 35,
// 36 Reserved
RequestDeclined = 37,
InvalidParameters = 38,
RejectedWithSuggestedChanges = 39,
StatusInvalidElement = 40,
StatusInvalidGroupCipher = 41,
StatusInvalidPairwiseCipher = 42,
StatusInvalidAkmp = 43,
UnsupportedRsneVersion = 44,
InvalidRsneCapabilities = 45,
StatusCipherOutOfPolicy = 46,
RejectedForDelayPeriod = 47,
DlsNotAllowed = 48,
NotPresent = 49,
NotQosSta = 50,
DeniedListenIntervalTooLarge = 51,
StatusInvalidFtActionFrameCount = 52,
StatusInvalidPmkid = 53,
StatusInvalidMde = 54,
StatusInvalidFte = 55,
RequestedTclasNotSupported56 = 56, // see RequestedTclasNotSupported80 below
InsufficientTclasProcessingResources = 57,
TryAnotherBss = 58,
GasAdvertisementProtocolNotSupported = 59,
NoOutstandingGasRequest = 60,
GasResponseNotReceivedFromServer = 61,
GasQueryTimeout = 62,
GasQueryResponseTooLarge = 63,
RejectedHomeWithSuggestedChanges = 64,
ServerUnreachable = 65,
// 66 Reserved
RejectedForSspPermissions = 67,
RefusedUnauthenticatedAccessNotSupported = 68,
// 69-71 Reserved
InvalidRsne = 72,
UApsdCoexistanceNotSupported = 73,
UApsdCoexModeNotSupported = 74,
BadIntervalWithUApsdCoex = 75,
AntiCloggingTokenRequired = 76,
UnsupportedFiniteCyclicGroup = 77,
CannotFindAlternativeTbtt = 78,
TransmissionFailure = 79,
RequestedTclasNotSupported80 = 80, // see RequestedTclasNotSupported56 above
TclasResourcesExhausted = 81,
RejectedWithSuggestedBssTransition = 82,
RejectWithSchedule = 83,
RejectNoWakeupSpecified = 84,
SuccessPowerSaveMode = 85,
PendingAdmittingFstSession = 86,
PerformingFstNow = 87,
PendingGapInBaWindow = 88,
RejectUPidSetting = 89,
// 90-91 Reserved
RefusedExternalReason = 92,
RefusedApOutOfMemory = 93,
RejectedEmergencyServicesNotSupported = 94,
QueryResponseOutstanding = 95,
RejectDseBand = 96,
TclasProcessingTerminated = 97,
TsScheduleConflict = 98,
DeniedWithSuggestedBandAndChannel = 99,
MccaopReservationConflict = 100,
MafLimitExceeded = 101,
MccaTrackLimitExceeded = 102,
DeniedDueToSpectrumManagement = 103,
DeniedVhtNotSupported = 104,
EnablementDenied = 105,
RestrictionFromAuthorizedGdb = 106,
AuthorizationDeenabled = 107,
// 108-65535 Reserved
}
fn round_up<T: Unsigned + Copy>(value: T, multiple: T) -> T {
let overshoot = value + multiple - T::one();
overshoot - overshoot % multiple
}
#[cfg(test)]
mod tests {
use super::*;
use std::mem::transmute;
fn make_mgmt_frame(ht_ctrl: bool) -> Vec<u8> {
#[rustfmt::skip]
let mut bytes = vec![
1, if ht_ctrl { 128 } else { 1 }, // fc
2, 2, // duration
3, 3, 3, 3, 3, 3, // addr1
4, 4, 4, 4, 4, 4, // addr2
5, 5, 5, 5, 5, 5, // addr3
6, 6, // sequence control
];
if ht_ctrl {
bytes.extend_from_slice(&[8, 8, 8, 8]);
}
bytes.extend_from_slice(&[9, 9, 9]);
bytes
}
fn make_data_frame(addr4: Option<[u8; 6]>, ht_ctrl: Option<[u8; 4]>) -> Vec<u8> {
let mut fc = FrameControl(0);
fc.set_frame_type(FRAME_TYPE_DATA);
fc.set_frame_subtype(DATA_SUBTYPE_QOS_DATA);
fc.set_from_ds(addr4.is_some());
fc.set_to_ds(addr4.is_some());
fc.set_htc_order(ht_ctrl.is_some());
let fc: [u8; 2] = unsafe { transmute(fc.value().to_le()) };
#[rustfmt::skip]
let mut bytes = vec![
// Data Header
fc[0], fc[1], // fc
2, 2, // duration
3, 3, 3, 3, 3, 3, // addr1
4, 4, 4, 4, 4, 4, // addr2
5, 5, 5, 5, 5, 5, // addr3
6, 6, // sequence control
];
if let Some(addr4) = addr4 {
bytes.extend_from_slice(&addr4);
}
// QoS Control
bytes.extend_from_slice(&[1, 1]);
if let Some(ht_ctrl) = ht_ctrl {
bytes.extend_from_slice(&ht_ctrl);
}
bytes.extend_from_slice(&[
// LLC Header
7, 7, 7, // DSAP, SSAP & control
8, 8, 8, // OUI
9, 10, // eth type
// Trailing bytes
11, 11, 11,
]);
bytes
}
fn make_data_frame_with_padding() -> Vec<u8> {
let mut fc = FrameControl(0);
fc.set_frame_type(FRAME_TYPE_DATA);
fc.set_frame_subtype(DATA_SUBTYPE_QOS_DATA);
let fc: [u8; 2] = unsafe { transmute(fc.value().to_le()) };
#[rustfmt::skip]
let bytes = vec![
// Data Header
fc[0], fc[1], // fc
2, 2, // duration
3, 3, 3, 3, 3, 3, // addr1
4, 4, 4, 4, 4, 4, // addr2
5, 5, 5, 5, 5, 5, // addr3
6, 6, // sequence control
// QoS Control
1, 1,
// Padding
2, 2,
// Body
7, 7, 7,
];
bytes
}
#[test]
fn mgmt_hdr_len() {
assert_eq!(MgmtHdr::len(HtControl::ABSENT), 24);
assert_eq!(MgmtHdr::len(HtControl::PRESENT), 28);
}
#[test]
fn data_hdr_len() {
assert_eq!(DataHdr::len(Addr4::ABSENT, QosControl::ABSENT, HtControl::ABSENT), 24);
assert_eq!(DataHdr::len(Addr4::PRESENT, QosControl::ABSENT, HtControl::ABSENT), 30);
assert_eq!(DataHdr::len(Addr4::ABSENT, QosControl::PRESENT, HtControl::ABSENT), 26);
assert_eq!(DataHdr::len(Addr4::ABSENT, QosControl::ABSENT, HtControl::PRESENT), 28);
assert_eq!(DataHdr::len(Addr4::PRESENT, QosControl::PRESENT, HtControl::ABSENT), 32);
assert_eq!(DataHdr::len(Addr4::ABSENT, QosControl::PRESENT, HtControl::PRESENT), 30);
assert_eq!(DataHdr::len(Addr4::PRESENT, QosControl::ABSENT, HtControl::PRESENT), 34);
assert_eq!(DataHdr::len(Addr4::PRESENT, QosControl::PRESENT, HtControl::PRESENT), 36);
}
#[test]
fn parse_mgmt_frame() {
let bytes = make_mgmt_frame(false);
match MacFrame::parse(&bytes[..], false) {
Some(MacFrame::Mgmt { mgmt_hdr, ht_ctrl, body }) => {
assert_eq!([1, 1], mgmt_hdr.frame_ctrl);
assert_eq!([2, 2], mgmt_hdr.duration);
assert_eq!([3, 3, 3, 3, 3, 3], mgmt_hdr.addr1);
assert_eq!([4, 4, 4, 4, 4, 4], mgmt_hdr.addr2);
assert_eq!([5, 5, 5, 5, 5, 5], mgmt_hdr.addr3);
assert_eq!([6, 6], mgmt_hdr.seq_ctrl);
assert!(ht_ctrl.is_none());
assert_eq!(&body[..], &[9, 9, 9]);
}
_ => panic!("failed parsing mgmt frame"),
};
}
#[test]
fn parse_mgmt_frame_too_short_unsupported() {
// Valid MGMT header must have a minium length of 24 bytes.
assert!(MacFrame::parse(&[0; 22][..], false).is_none());
// Unsupported frame type.
match MacFrame::parse(&[0xFF; 24][..], false) {
Some(MacFrame::Unsupported { type_ }) => assert_eq!(3, type_),
_ => panic!("didn't detect unsupported frame"),
};
}
#[test]
fn parse_beacon_frame() {
#[rustfmt::skip]
let bytes = vec![
1,1,1,1,1,1,1,1, // timestamp
2,2, // beacon_interval
3,3, // capabilities
0,5,1,2,3,4,5 // SSID IE: "12345"
];
match MgmtSubtype::parse(MGMT_SUBTYPE_BEACON, &bytes[..]) {
Some(MgmtSubtype::Beacon { bcn_hdr, elements }) => {
assert_eq!(0x0101010101010101, bcn_hdr.timestamp());
assert_eq!(0x0202, bcn_hdr.beacon_interval());
assert_eq!(0x0303, bcn_hdr.capabilities());
assert_eq!(&[0, 5, 1, 2, 3, 4, 5], &elements[..]);
}
_ => panic!("failed parsing beacon frame"),
};
}
#[test]
fn parse_data_frame() {
let bytes = make_data_frame(None, None);
match MacFrame::parse(&bytes[..], false) {
Some(MacFrame::Data { data_hdr, addr4, qos_ctrl, ht_ctrl, body }) => {
assert_eq!([0b10001000, 0], data_hdr.frame_ctrl);
assert_eq!([2, 2], data_hdr.duration);
assert_eq!([3, 3, 3, 3, 3, 3], data_hdr.addr1);
assert_eq!([4, 4, 4, 4, 4, 4], data_hdr.addr2);
assert_eq!([5, 5, 5, 5, 5, 5], data_hdr.addr3);
assert_eq!([6, 6], data_hdr.seq_ctrl);
assert!(addr4.is_none());
match qos_ctrl {
None => panic!("qos_ctrl expected to be present"),
Some(qos_ctrl) => {
assert_eq!(&[1, 1][..], &qos_ctrl[..]);
}
};
assert!(ht_ctrl.is_none());
assert_eq!(&body[..], &[7, 7, 7, 8, 8, 8, 9, 10, 11, 11, 11]);
}
_ => panic!("failed parsing data frame"),
};
}
#[test]
fn parse_data_frame_with_padding() {
let bytes = make_data_frame_with_padding();
match MacFrame::parse(&bytes[..], true) {
Some(MacFrame::Data { qos_ctrl, body, .. }) => {
assert_eq!([1, 1], qos_ctrl.expect("qos_ctrl not present").0);
assert_eq!(&[7, 7, 7], &body[..]);
}
_ => panic!("failed parsing data frame"),
};
}
#[test]
fn parse_llc_with_addr4_ht_ctrl() {
let bytes = make_data_frame(Some([1, 2, 3, 4, 5, 6]), Some([4, 3, 2, 1]));
match MacFrame::parse(&bytes[..], false) {
Some(MacFrame::Data { data_hdr, body, .. }) => {
let fc = FrameControl(data_hdr.frame_ctrl());
match DataSubtype::parse(fc.frame_subtype(), &body[..]) {
Some(DataSubtype::Data { hdr, payload, is_qos }) => {
assert!(is_qos);
assert_eq!(7, hdr.dsap);
assert_eq!(7, hdr.ssap);
assert_eq!(7, hdr.control);
assert_eq!([8, 8, 8], hdr.oui);
assert_eq!([9, 10], hdr.protocol_id_be);
assert_eq!(0x090A, hdr.protocol_id());
assert_eq!(&[11, 11, 11], payload);
}
_ => panic!("failed parsing LLC"),
}
}
_ => panic!("failed parsing data frame"),
};
}
#[test]
fn test_llc_set_protocol_id() {
let mut hdr: LlcHdr = Default::default();
hdr.set_protocol_id(0xAABB);
assert_eq!([0xAA, 0xBB], hdr.protocol_id_be);
assert_eq!(0xAABB, hdr.protocol_id());
}
#[test]
fn parse_amsdu() {
#[rustfmt::skip]
let first_msdu = vec![
// LLC header
0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00,
// Payload
0x33, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04,
];
#[rustfmt::skip]
let second_msdu = vec![
// LLC header
0xaa, 0xaa, 0x03, 0x00, 0x00, 0x00, 0x08, 0x00,
// Payload
0x99, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
];
#[rustfmt::skip]
let mut amsdu_frame = vec![
// A-MSDU Subframe #1
0x78, 0x8a, 0x20, 0x0d, 0x67, 0x03, 0xb4, 0xf7,
0xa1, 0xbe, 0xb9, 0xab,
0x00, 0x74, // MSDU length
];
amsdu_frame.extend(&first_msdu[..]);
#[rustfmt::skip]
amsdu_frame.extend(vec![
// Padding
0x00, 0x00,
// A-MSDU Subframe #2
0x78, 0x8a, 0x20, 0x0d, 0x67, 0x03, 0xb4, 0xf7,
0xa1, 0xbe, 0xb9, 0xab, 0x00,
0x66, // MSDU length
]);
amsdu_frame.extend(&second_msdu[..]);
let mut found_msdus = (false, false);
let mut rdr = AmsduReader(&amsdu_frame[..]);
for msdu in &mut rdr {
match found_msdus {
(false, false) => {
assert_eq!(msdu, &first_msdu[..]);
found_msdus = (true, false);
}
(true, false) => {
assert_eq!(msdu, &second_msdu[..]);
found_msdus = (true, true);
}
_ => panic!("unexpected MSDU: {:x?}", msdu),
}
}
assert_eq!((true, true), found_msdus);
}
#[test]
fn eth_hdr_big_endian() {
let mut bytes: Vec<u8> = vec![
1, 2, 3, 4, 5, 6, // dst_addr
7, 8, 9, 10, 11, 12, // src_addr
13, 14, // ether_type
99, 99, // trailing bytes
];
let (mut hdr, body) =
LayoutVerified::<_, EthernetIIHdr>::new_unaligned_from_prefix(&mut bytes[..])
.expect("cannot create ethernet header.");
assert_eq!(hdr.da, [1u8, 2, 3, 4, 5, 6]);
assert_eq!(hdr.sa, [7u8, 8, 9, 10, 11, 12]);
assert_eq!(hdr.ether_type(), 13 << 8 | 14);
assert_eq!(hdr.ether_type_be, [13u8, 14]);
assert_eq!(body, [99, 99]);
hdr.set_ether_type(0x888e);
assert_eq!(hdr.ether_type_be, [0x88, 0x8e]);
#[rustfmt::skip]
assert_eq!(
&[1u8, 2, 3, 4, 5, 6,
7, 8, 9, 10, 11, 12,
0x88, 0x8e,
99, 99],
&bytes[..]);
}
}
|
use projecteuler::digits;
use projecteuler::helper;
/*
Find the smallest positive integer, x, such that 2x, 3x, 4x, 5x, and 6x, contain the same digits
Note:
x must start with the digit 1. Suppose it starts with a digit >1 => 6x would contain more digits than x.
*/
fn main() {
helper::check_bench(|| {
solve();
});
dbg!(solve());
}
fn solve() -> usize {
for exp in 5.. {
let ten = 10usize.pow(exp as u32);
for i in 0..ten {
let i = ten + i;
let mut digits = digits::digits(i);
digits.sort();
for jf in 2..=6 {
let j = i * jf;
let mut digits_j = digits::digits(j);
digits_j.sort();
if digits != digits_j {
break;
} else if jf == 6 {
return i;
}
}
}
}
unreachable!();
}
|
extern crate find_folder;
extern crate image;
extern crate piston_window;
use image::*;
use piston_window::*;
use rand::distributions::{Distribution, Uniform};
use std::time::Instant;
fn main() {
const WINDOW_WIDTH: u32 = 1050;
const WINDOW_HEIGHT: u32 = 1050;
const CLEAR_COLOR: [f32; 4] = [1.0; 4];
const FERN_COLOR_OPT_ONE: [u8; 4] = [51, 153, 137, 255];
const FERN_COLOR_OPT_TWO: [u8; 4] = [0, 108, 103, 255];
const FERN_COLOR_OPT_THREE: [u8; 4] = [40, 150, 114, 255];
const FERN_BACKGROUND_COLOR_OPT_ONE: [u8; 4] = [43, 44, 40, 255];
const FERN_BACKGROUND_COLOR_OPT_TWO: [u8; 4] = [19, 21, 21, 255];
const FERN_BACKGROUND_COLOR_OPT_THREE: [u8; 4] = [54, 69, 71, 255];
const FONT_COLOR: [f32; 4] = [0.92, 0.92, 0.92, 1.0];
/*
* Window setup
*/
let mut window: PistonWindow = WindowSettings::new("Fern", [WINDOW_WIDTH, WINDOW_HEIGHT])
.exit_on_esc(true)
.build()
.unwrap();
/*
* Font loading
*/
let assets = find_folder::Search::ParentsThenKids(3, 3)
.for_folder("assets")
.unwrap();
let mut glyphs = window
.load_font(assets.join("font/RobotoCondensed-Light.ttf"))
.unwrap();
glyphs.preload_printable_ascii(15).unwrap();
/*
* Text variables setup
*/
let mut average_frame_time_string: String;
let mut max_frame_time_string: String;
let mut iterated_count_text: String;
/*
* Fern values setup
*/
let temp_fern_image: RgbaImage = ImageBuffer::new(WINDOW_WIDTH, WINDOW_HEIGHT);
let temp_fern_coords: Vec<[u32; 2]> = Vec::new();
let temp_fern_iterated_count: u128 = 0;
let temp_fern_values: FernValues = FernValues {
current_img: temp_fern_image,
current_x: 0.0,
current_y: 0.0,
current_calculated_coords: temp_fern_coords,
};
let mut fern: Fern = Fern {
values: temp_fern_values,
background_drawn: false,
iterated_count: temp_fern_iterated_count,
};
/*
* Fern render setup
*/
let window_texture_context = &mut window.create_texture_context();
let fern_texture_settings: TextureSettings = TextureSettings::new();
let mut fern_texture = fern.get_render_target(window_texture_context, fern_texture_settings);
let mut current_fern_color: [u8; 4] = FERN_COLOR_OPT_ONE;
let mut current_fern_background_color: [u8; 4] = FERN_BACKGROUND_COLOR_OPT_ONE;
fern.gen_fern(
100,
WINDOW_WIDTH,
WINDOW_HEIGHT,
current_fern_color,
current_fern_background_color,
false,
);
/*
* Timing system setup
*/
const TICK_TIME: u128 = 10;
const MAX_SAVED_FRAME_TIMES: u64 = 30;
let mut tick_clock = Instant::now();
let mut time_stamp_frame_start: Instant;
let mut _time_stamp_frame_end: Instant = Instant::now();
let mut current_frame_time_us: u128 = 0;
let mut last_frame_times_us: Vec<u128> = Vec::new();
let mut average_frame_time: u128 = 0;
let mut max_frame_time: u128 = 0;
let mut generation_paused: bool = false;
/*
* Main loop
*/
while let Some(event) = window.next() {
time_stamp_frame_start = Instant::now();
/*
* Input
*/
if let Some(button) = event.release_args() {
match button {
Button::Keyboard(key) => {
if key == Key::Space {
if generation_paused {
generation_paused = false;
} else {
generation_paused = true;
}
}
else if key == Key::R {
fern.reset();
}
else if key == Key::D1 {
fern.reset();
current_fern_color = FERN_COLOR_OPT_ONE;
current_fern_background_color = FERN_BACKGROUND_COLOR_OPT_ONE;
}
else if key == Key::D2 {
fern.reset();
current_fern_color = FERN_COLOR_OPT_TWO;
current_fern_background_color = FERN_BACKGROUND_COLOR_OPT_TWO;
}
else if key == Key::D3 {
fern.reset();
current_fern_color = FERN_COLOR_OPT_THREE;
current_fern_background_color = FERN_BACKGROUND_COLOR_OPT_THREE;
}
}
Button::Mouse(_) => {}
Button::Controller(_) => {}
Button::Hat(_) => {}
}
}
/*
* Fern update
*/
if tick_clock.elapsed().as_millis() >= TICK_TIME && !generation_paused {
fern.gen_fern(
1000,
WINDOW_WIDTH,
WINDOW_HEIGHT,
current_fern_color,
current_fern_background_color,
false,
);
tick_clock = Instant::now();
}
/*
* Max frame time calculation
*/
if average_frame_time > 0
&& last_frame_times_us.len() > 1
&& last_frame_times_us[last_frame_times_us.len() - 1] < current_frame_time_us
&& current_frame_time_us > max_frame_time
{
max_frame_time = current_frame_time_us;
}
/*
* Average frame time calculation
*/
if last_frame_times_us.len() as u64 > MAX_SAVED_FRAME_TIMES {
let mut combined_frame_times: u128 = 0;
for time_ms in last_frame_times_us.iter() {
combined_frame_times += time_ms
}
average_frame_time = combined_frame_times / MAX_SAVED_FRAME_TIMES as u128;
last_frame_times_us.clear();
} else {
last_frame_times_us.push(current_frame_time_us);
}
/*
* Text variables update
*/
average_frame_time_string =
"Average frame time: ".to_string() + &format!("{:.4}", (f64::from(average_frame_time as u32) * 0.001).to_string().to_owned()) + "ms";
max_frame_time_string =
"Max frame time: ".to_string() + &format!("{:.4}", (f64::from(max_frame_time as u32) * 0.001).to_string().to_owned()) + "ms";
iterated_count_text =
"Iterations: ".to_string() + &fern.iterated_count.to_string().to_owned();
/*
* Rendering
*/
window.draw_2d(&event, |context, graphics, _device| {
clear(CLEAR_COLOR, graphics);
/*
* Fern image render
*/
fern_texture = fern.get_render_target(window_texture_context, fern_texture_settings);
image(&fern_texture, context.transform, graphics);
/*
* Text render
*/
glyphs.factory.encoder.flush(_device);
/*
? Caption
*/
text::Text::new_color(FONT_COLOR, 22)
.draw(
"Barnsley Fern",
&mut glyphs,
&context.draw_state,
context.transform.trans(5.0, 23.0),
graphics,
)
.unwrap();
/*
? Average frame time
*/
text::Text::new_color(FONT_COLOR, 15)
.draw(
&average_frame_time_string,
&mut glyphs,
&context.draw_state,
context.transform.trans(8.0, 55.0),
graphics,
)
.unwrap();
/*
? Max frame time
*/
text::Text::new_color(FONT_COLOR, 15)
.draw(
&max_frame_time_string,
&mut glyphs,
&context.draw_state,
context.transform.trans(8.0, 80.0),
graphics,
)
.unwrap();
/*
? Total iterations
*/
text::Text::new_color(FONT_COLOR, 15)
.draw(
&iterated_count_text,
&mut glyphs,
&context.draw_state,
context.transform.trans(8.0, 105.0),
graphics,
)
.unwrap();
});
/*
* Frame time calculation
*/
_time_stamp_frame_end = Instant::now();
current_frame_time_us = _time_stamp_frame_end
.saturating_duration_since(time_stamp_frame_start)
.as_micros();
}
}
struct Fern {
pub values: FernValues,
pub background_drawn: bool,
pub iterated_count: u128,
}
impl Fern {
pub fn gen_fern(
&mut self,
iterations: u64,
width: u32,
height: u32,
color: [u8; 4],
background_color: [u8; 4],
save_file: bool,
) {
/*
* Plot values setup
*/
let mut plot_x: f64;
let mut plot_y: f64;
let mut next_x: f64;
let mut next_y: f64;
self.values.current_calculated_coords.clear();
/*
* Random setup
*/
let mut random_gen = rand::thread_rng();
let random_range = Uniform::from(1..1000000000);
let mut random_num: f32;
/*
* Image background set
*/
if !self.background_drawn {
for (_, _, pixel) in self.values.current_img.enumerate_pixels_mut() {
*pixel = image::Rgba(background_color);
}
self.background_drawn = true;
}
/*
* Generation
*/
self.iterated_count += iterations as u128;
for _ in 0..iterations {
/*
* Random number sample
*/
random_num = (random_range.sample(&mut random_gen) as f32) * 0.000000001;
/*
* Magic
*/
if random_num < 0.01 {
next_x = 0.0;
next_y = 0.16 * self.values.current_y;
} else if random_num < 0.86 {
next_x = 0.85 * self.values.current_x + 0.04 * self.values.current_y;
next_y = -0.04 * self.values.current_x + 0.85 * self.values.current_y + 1.6;
} else if random_num < 0.93 {
next_x = 0.20 * self.values.current_x - 0.26 * self.values.current_y;
next_y = 0.23 * self.values.current_x + 0.22 * self.values.current_y + 1.6;
} else {
next_x = -0.15 * self.values.current_x + 0.28 * self.values.current_y;
next_y = 0.26 * self.values.current_x + 0.24 * self.values.current_y + 0.44;
}
/*
* Scaling, assignment
*/
plot_x = width as f64 * (self.values.current_x + 3.0) / 6.0;
plot_y = height as f64 - height as f64 * ((self.values.current_y + 2.0) / 14.0);
self.values.current_x = next_x;
self.values.current_y = next_y;
/*
* Save targeted pixel coords
*/
self.values
.current_calculated_coords
.push([plot_x as u32, plot_y as u32]);
}
/*
* Write targeted pixels
*/
for pix_coord in self.values.current_calculated_coords.iter() {
self.values
.current_img
.put_pixel(pix_coord[0], pix_coord[1], image::Rgba(color));
}
/*
* Save copy of image
*/
if save_file {
self.values
.current_img
.save(format!("fern{}x{}_iter_{}.png", width, height, iterations))
.unwrap();
}
}
fn get_render_target(
&self,
texture_context: &mut G2dTextureContext,
texture_settings: TextureSettings,
) -> G2dTexture {
let fern_texture: G2dTexture =
Texture::from_image(texture_context, &self.values.current_img, &texture_settings)
.unwrap();
return fern_texture;
}
fn reset(&mut self ) {
self.background_drawn = false;
self.iterated_count = 0;
self.values.current_calculated_coords.clear();
self.values.current_x = 0.0;
self.values.current_y = 0.0;
}
}
struct FernValues {
pub current_img: RgbaImage,
pub current_calculated_coords: Vec<[u32; 2]>,
pub current_x: f64,
pub current_y: f64,
} |
use std::{
env::var,
io::{stderr, stdout, Write},
process::{exit, Command, Output},
};
const DEFAULT_BRANCH: &str = "default";
const DEFAULT_REMOTE: &str = "origin";
fn main() {
git_version();
git_init();
git_remote();
git_fetch();
git_checkout();
git_log();
}
fn git_version() {
let command = "git --version";
let output = exec(command);
stdout().write_all(&output.stdout).unwrap_or_else(|error| {
eprintln!("stdout error: {}", error);
exit(1);
});
}
fn git_init() {
let command = format!("git init --initial-branch={}", DEFAULT_BRANCH);
exec(command);
}
fn git_remote() {
let server = env("GITHUB_SERVER_URL");
let repository = env("GITHUB_REPOSITORY");
let command = format!(
"git remote add {} {}/{}",
DEFAULT_REMOTE, server, repository
);
exec(command);
}
fn git_fetch() {
let refspec = env("GITHUB_REF");
let command = format!(
"git fetch \
--depth=1 \
--no-tags \
--update-head-ok \
{} +{}:{}",
DEFAULT_REMOTE, refspec, DEFAULT_BRANCH
);
exec(command);
}
fn git_checkout() {
let command = "git checkout";
exec(command);
}
fn git_log() {
let command = "git --no-pager log --date=iso --no-decorate";
let output = exec(command);
stdout().write_all(&output.stdout).unwrap_or_else(|error| {
eprintln!("stdout error: {}", error);
exit(1);
});
}
fn exec<S: AsRef<str>>(command: S) -> Output {
let command = command.as_ref();
println!("❯ {}", command);
let split: Vec<_> = command.trim().split_whitespace().collect();
let (executable, arguments) = split.split_first().unwrap();
let output = Command::new(executable).args(arguments).output().unwrap();
if output.status.success() {
output
} else {
eprintln!("--- status ---");
eprintln!("{}", output.status);
eprintln!();
eprintln!("--- stdout ---");
stderr().write_all(&output.stdout).unwrap_or_else(|error| {
eprintln!("stderr error: {}", error);
exit(1);
});
eprintln!();
eprintln!("--- stderr ---");
stderr().write_all(&output.stderr).unwrap_or_else(|error| {
eprintln!("stderr error: {}", error);
exit(1);
});
eprintln!();
exit(1);
}
}
fn env(name: &str) -> String {
var(name).unwrap_or_else(|error| {
eprintln!("environment variable error: {}", error);
exit(1);
})
}
|
#[doc = r"Value read from the register"]
pub struct R {
bits: u8,
}
#[doc = r"Value to write to the register"]
pub struct W {
bits: u8,
}
impl super::RXTYPE5 {
#[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() -> u8 {
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 USB_RXTYPE5_TEPR {
bits: u8,
}
impl USB_RXTYPE5_TEPR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r"Proxy"]
pub struct _USB_RXTYPE5_TEPW<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXTYPE5_TEPW<'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 u8) & 15) << 0;
self.w
}
}
#[doc = "Possible values of the field `USB_RXTYPE5_PROTO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_RXTYPE5_PROTOR {
#[doc = "Control"]
USB_RXTYPE5_PROTO_CTRL,
#[doc = "Isochronous"]
USB_RXTYPE5_PROTO_ISOC,
#[doc = "Bulk"]
USB_RXTYPE5_PROTO_BULK,
#[doc = "Interrupt"]
USB_RXTYPE5_PROTO_INT,
}
impl USB_RXTYPE5_PROTOR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_CTRL => 0,
USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_ISOC => 1,
USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_BULK => 2,
USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_INT => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> USB_RXTYPE5_PROTOR {
match value {
0 => USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_CTRL,
1 => USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_ISOC,
2 => USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_BULK,
3 => USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_INT,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `USB_RXTYPE5_PROTO_CTRL`"]
#[inline(always)]
pub fn is_usb_rxtype5_proto_ctrl(&self) -> bool {
*self == USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_CTRL
}
#[doc = "Checks if the value of the field is `USB_RXTYPE5_PROTO_ISOC`"]
#[inline(always)]
pub fn is_usb_rxtype5_proto_isoc(&self) -> bool {
*self == USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_ISOC
}
#[doc = "Checks if the value of the field is `USB_RXTYPE5_PROTO_BULK`"]
#[inline(always)]
pub fn is_usb_rxtype5_proto_bulk(&self) -> bool {
*self == USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_BULK
}
#[doc = "Checks if the value of the field is `USB_RXTYPE5_PROTO_INT`"]
#[inline(always)]
pub fn is_usb_rxtype5_proto_int(&self) -> bool {
*self == USB_RXTYPE5_PROTOR::USB_RXTYPE5_PROTO_INT
}
}
#[doc = "Values that can be written to the field `USB_RXTYPE5_PROTO`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_RXTYPE5_PROTOW {
#[doc = "Control"]
USB_RXTYPE5_PROTO_CTRL,
#[doc = "Isochronous"]
USB_RXTYPE5_PROTO_ISOC,
#[doc = "Bulk"]
USB_RXTYPE5_PROTO_BULK,
#[doc = "Interrupt"]
USB_RXTYPE5_PROTO_INT,
}
impl USB_RXTYPE5_PROTOW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
USB_RXTYPE5_PROTOW::USB_RXTYPE5_PROTO_CTRL => 0,
USB_RXTYPE5_PROTOW::USB_RXTYPE5_PROTO_ISOC => 1,
USB_RXTYPE5_PROTOW::USB_RXTYPE5_PROTO_BULK => 2,
USB_RXTYPE5_PROTOW::USB_RXTYPE5_PROTO_INT => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _USB_RXTYPE5_PROTOW<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXTYPE5_PROTOW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USB_RXTYPE5_PROTOW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Control"]
#[inline(always)]
pub fn usb_rxtype5_proto_ctrl(self) -> &'a mut W {
self.variant(USB_RXTYPE5_PROTOW::USB_RXTYPE5_PROTO_CTRL)
}
#[doc = "Isochronous"]
#[inline(always)]
pub fn usb_rxtype5_proto_isoc(self) -> &'a mut W {
self.variant(USB_RXTYPE5_PROTOW::USB_RXTYPE5_PROTO_ISOC)
}
#[doc = "Bulk"]
#[inline(always)]
pub fn usb_rxtype5_proto_bulk(self) -> &'a mut W {
self.variant(USB_RXTYPE5_PROTOW::USB_RXTYPE5_PROTO_BULK)
}
#[doc = "Interrupt"]
#[inline(always)]
pub fn usb_rxtype5_proto_int(self) -> &'a mut W {
self.variant(USB_RXTYPE5_PROTOW::USB_RXTYPE5_PROTO_INT)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 4);
self.w.bits |= ((value as u8) & 3) << 4;
self.w
}
}
#[doc = "Possible values of the field `USB_RXTYPE5_SPEED`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_RXTYPE5_SPEEDR {
#[doc = "Default"]
USB_RXTYPE5_SPEED_DFLT,
#[doc = "High"]
USB_RXTYPE5_SPEED_HIGH,
#[doc = "Full"]
USB_RXTYPE5_SPEED_FULL,
#[doc = "Low"]
USB_RXTYPE5_SPEED_LOW,
}
impl USB_RXTYPE5_SPEEDR {
#[doc = r"Value of the field as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
match *self {
USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_DFLT => 0,
USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_HIGH => 1,
USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_FULL => 2,
USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_LOW => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _from(value: u8) -> USB_RXTYPE5_SPEEDR {
match value {
0 => USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_DFLT,
1 => USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_HIGH,
2 => USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_FULL,
3 => USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_LOW,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `USB_RXTYPE5_SPEED_DFLT`"]
#[inline(always)]
pub fn is_usb_rxtype5_speed_dflt(&self) -> bool {
*self == USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_DFLT
}
#[doc = "Checks if the value of the field is `USB_RXTYPE5_SPEED_HIGH`"]
#[inline(always)]
pub fn is_usb_rxtype5_speed_high(&self) -> bool {
*self == USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_HIGH
}
#[doc = "Checks if the value of the field is `USB_RXTYPE5_SPEED_FULL`"]
#[inline(always)]
pub fn is_usb_rxtype5_speed_full(&self) -> bool {
*self == USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_FULL
}
#[doc = "Checks if the value of the field is `USB_RXTYPE5_SPEED_LOW`"]
#[inline(always)]
pub fn is_usb_rxtype5_speed_low(&self) -> bool {
*self == USB_RXTYPE5_SPEEDR::USB_RXTYPE5_SPEED_LOW
}
}
#[doc = "Values that can be written to the field `USB_RXTYPE5_SPEED`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum USB_RXTYPE5_SPEEDW {
#[doc = "Default"]
USB_RXTYPE5_SPEED_DFLT,
#[doc = "High"]
USB_RXTYPE5_SPEED_HIGH,
#[doc = "Full"]
USB_RXTYPE5_SPEED_FULL,
#[doc = "Low"]
USB_RXTYPE5_SPEED_LOW,
}
impl USB_RXTYPE5_SPEEDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline(always)]
pub fn _bits(&self) -> u8 {
match *self {
USB_RXTYPE5_SPEEDW::USB_RXTYPE5_SPEED_DFLT => 0,
USB_RXTYPE5_SPEEDW::USB_RXTYPE5_SPEED_HIGH => 1,
USB_RXTYPE5_SPEEDW::USB_RXTYPE5_SPEED_FULL => 2,
USB_RXTYPE5_SPEEDW::USB_RXTYPE5_SPEED_LOW => 3,
}
}
}
#[doc = r"Proxy"]
pub struct _USB_RXTYPE5_SPEEDW<'a> {
w: &'a mut W,
}
impl<'a> _USB_RXTYPE5_SPEEDW<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: USB_RXTYPE5_SPEEDW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "Default"]
#[inline(always)]
pub fn usb_rxtype5_speed_dflt(self) -> &'a mut W {
self.variant(USB_RXTYPE5_SPEEDW::USB_RXTYPE5_SPEED_DFLT)
}
#[doc = "High"]
#[inline(always)]
pub fn usb_rxtype5_speed_high(self) -> &'a mut W {
self.variant(USB_RXTYPE5_SPEEDW::USB_RXTYPE5_SPEED_HIGH)
}
#[doc = "Full"]
#[inline(always)]
pub fn usb_rxtype5_speed_full(self) -> &'a mut W {
self.variant(USB_RXTYPE5_SPEEDW::USB_RXTYPE5_SPEED_FULL)
}
#[doc = "Low"]
#[inline(always)]
pub fn usb_rxtype5_speed_low(self) -> &'a mut W {
self.variant(USB_RXTYPE5_SPEEDW::USB_RXTYPE5_SPEED_LOW)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bits(self, value: u8) -> &'a mut W {
self.w.bits &= !(3 << 6);
self.w.bits |= ((value as u8) & 3) << 6;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u8 {
self.bits
}
#[doc = "Bits 0:3 - Target Endpoint Number"]
#[inline(always)]
pub fn usb_rxtype5_tep(&self) -> USB_RXTYPE5_TEPR {
let bits = ((self.bits >> 0) & 15) as u8;
USB_RXTYPE5_TEPR { bits }
}
#[doc = "Bits 4:5 - Protocol"]
#[inline(always)]
pub fn usb_rxtype5_proto(&self) -> USB_RXTYPE5_PROTOR {
USB_RXTYPE5_PROTOR::_from(((self.bits >> 4) & 3) as u8)
}
#[doc = "Bits 6:7 - Operating Speed"]
#[inline(always)]
pub fn usb_rxtype5_speed(&self) -> USB_RXTYPE5_SPEEDR {
USB_RXTYPE5_SPEEDR::_from(((self.bits >> 6) & 3) as u8)
}
}
impl W {
#[doc = r"Writes raw bits to the register"]
#[inline(always)]
pub unsafe fn bits(&mut self, bits: u8) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:3 - Target Endpoint Number"]
#[inline(always)]
pub fn usb_rxtype5_tep(&mut self) -> _USB_RXTYPE5_TEPW {
_USB_RXTYPE5_TEPW { w: self }
}
#[doc = "Bits 4:5 - Protocol"]
#[inline(always)]
pub fn usb_rxtype5_proto(&mut self) -> _USB_RXTYPE5_PROTOW {
_USB_RXTYPE5_PROTOW { w: self }
}
#[doc = "Bits 6:7 - Operating Speed"]
#[inline(always)]
pub fn usb_rxtype5_speed(&mut self) -> _USB_RXTYPE5_SPEEDW {
_USB_RXTYPE5_SPEEDW { w: self }
}
}
|
#![allow(dead_code)]
use std::borrow::Borrow;
#[derive(Debug, PartialEq, Clone)]
pub enum Code {
Acc,
Jmp,
Nop,
}
#[derive(Debug, PartialEq, Clone)]
pub struct Instruction {
pub code: Code,
pub val: i32,
}
fn str_to_instruction(ss: &str) -> Instruction {
let mut ss = ss.split(' ');
let code = ss.next().unwrap();
let val = ss.next().unwrap();
let code = match code {
"acc" => Code::Acc,
"jmp" => Code::Jmp,
"nop" => Code::Nop,
_ => panic!("invalid code"),
};
let val = val.parse().unwrap();
Instruction { code, val }
}
#[test]
fn str_to_instruction_test() {
let i = str_to_instruction("jmp +392");
assert_eq!(i.code, Code::Jmp);
assert_eq!(i.val, 392);
let i = str_to_instruction("acc -1");
assert_eq!(i.code, Code::Acc);
assert_eq!(i.val, -1);
}
pub fn get_instructions() -> Vec<Instruction> {
include_str!("../input.txt")
.lines()
.map(|s| s.borrow())
.map(str_to_instruction)
.collect()
}
|
use std::collections::vec_deque::VecDeque;
use std::fmt::{self, Debug, Display};
use crate::erts::ModuleFunctionArity;
use crate::process::Frame;
#[derive(Default)]
pub struct Stack(VecDeque<Frame>);
impl Stack {
pub fn len(&self) -> usize {
self.0.len()
}
pub fn pop(&mut self) -> Option<Frame> {
self.0.pop_front()
}
pub fn popn(&mut self, n: usize) {
for _ in 0..n {
self.0.pop_front().unwrap();
}
}
pub fn push(&mut self, frame: Frame) {
self.0.push_front(frame);
}
pub fn top(&self) -> Option<&Frame> {
self.0.get(0)
}
pub fn trace(&self) -> Trace {
let mut stacktrace = Vec::with_capacity(self.len());
for frame in self.0.iter() {
stacktrace.push(frame.module_function_arity())
}
Trace(stacktrace)
}
}
#[cfg(debug_assertions)]
impl Debug for Stack {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
writeln!(f, "{{")?;
writeln!(f, " let stack: Stack = Default::default();")?;
for frame in self.0.iter().rev() {
writeln!(f, " stack.push({:?});", frame)?;
}
writeln!(f, " stack")?;
write!(f, "}}")
}
}
pub struct Trace(Vec<ModuleFunctionArity>);
impl Debug for Trace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for module_function_arity in self.0.iter() {
writeln!(f, " {}", module_function_arity)?;
}
Ok(())
}
}
impl Display for Trace {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
for module_function_arity in self.0.iter() {
writeln!(f, " {}", module_function_arity)?;
}
Ok(())
}
}
|
//老师想给孩子们分发糖果,有 N 个孩子站成了一条直线,老师会根据每个孩子的表现,预先给他们评分。
//
// 你需要按照以下要求,帮助老师给这些孩子分发糖果:
//
//
// 每个孩子至少分配到 1 个糖果。
// 相邻的孩子中,评分高的孩子必须获得更多的糖果。
//
//
// 那么这样下来,老师至少需要准备多少颗糖果呢?
//
// 示例 1:
//
// 输入: [1,0,2]
//输出: 5
//解释: 你可以分别给这三个孩子分发 2、1、2 颗糖果。
//
//
// 示例 2:
//
// 输入: [1,2,2]
//输出: 4
//解释: 你可以分别给这三个孩子分发 1、2、1 颗糖果。
// 第三个孩子只得到 1 颗糖果,这已满足上述两个条件。
// Related Topics 贪心算法
//leetcode submit region begin(Prohibit modification and deletion)
impl Solution {
pub fn candy(ratings: Vec<i32>) -> i32 {
let n = ratings.len();
let mut candies = vec![1; n];
for i in 1..n {
//从前往后遍历ratings数组
if ratings[i] > ratings[i - 1] {
candies[i] = candies[i - 1] + 1;
}
}
for i in (0..(n - 2)).rev() {
//从后往前遍历ratings数组
if candies[i] <= candies[i + 1] && ratings[i] > ratings[i + 1] {
candies[i] = candies[i + 1] + 1;
}
}
println!("{:?}", &ratings);
println!("{:?}", &candies);
let sum = candies.iter().sum();
dbg!(sum);
println!();
return sum;
}
}
//leetcode submit region end(Prohibit modification and deletion)
fn main() {
assert_eq!(4, Solution::candy(vec![1, 2, 2]));
assert_eq!(5, Solution::candy(vec![1, 0, 2]));
Solution::candy(vec![1, 0, 2, 2, 3]);
}
struct Solution {}
|
use chrono::Utc;
use serde::{Deserialize, Serialize};
use std::{
fs::{DirEntry, File},
io::Read,
};
use crate::markdown::Markdown;
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct ArticleMeta {
pub category: String,
#[serde(default)]
pub tags: Vec<String>,
#[serde(default)]
pub aliases: Vec<String>,
#[serde(default)]
pub author: Option<String>,
#[serde(default)]
pub last_update: Option<chrono::DateTime<Utc>>,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Article {
pub section: String,
// filename may different with name, that's why we need disambiguation
pub name: String,
pub summary: String,
#[serde(flatten)]
pub metadata: ArticleMeta,
// #[serde(skip_serializing)]
pub content: Markdown,
}
impl Article {
pub fn new(content: Markdown, meta: ArticleMeta, section: String) -> Self {
Self {
section,
summary: content.summary(),
name: content.name(),
content,
metadata: meta,
}
}
pub fn load(entry: DirEntry) -> Self {
let section = entry
.path()
.parent()
.unwrap()
.file_name()
.unwrap()
.to_str()
.unwrap()
.to_string();
let filename = entry
.file_name()
.into_string()
.unwrap()
.trim_end_matches(".md")
.to_string();
let mut file = File::open(entry.path()).unwrap();
let mut content = String::new();
file.read_to_string(&mut content).unwrap();
let mut iter = content.split("---");
iter.next();
let meta_str = iter.next().unwrap();
let meta = serde_yaml::from_str(meta_str).unwrap();
let content = Markdown::new(filename, iter.next().unwrap());
Self::new(content, meta, section)
}
}
|
use std::fmt;
use crate::ir;
use fxhash::FxHashSet;
use itertools::Itertools;
use serde::{Deserialize, Serialize};
/// Unique identifier for `InductionVar`
#[derive(
Debug, Clone, Copy, Hash, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize,
)]
pub struct IndVarId(pub u32);
/// A multidimentional induction variable. No dimension should appear twice in dims.
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct InductionVar<L = ir::LoweringMap> {
dims: Vec<(ir::DimId, ir::PartialSize)>,
base: ir::Operand<L>,
}
impl<L> InductionVar<L> {
/// Creates a new induction var. Size represents the increment over each diemnsion
/// taken independenly.
pub fn new(
dims: Vec<(ir::DimId, ir::PartialSize)>,
base: ir::Operand<L>,
) -> Result<Self, ir::Error> {
ir::TypeError::check_integer(base.t())?;
// Assert dimensions are unique.
let mut dim_ids = FxHashSet::default();
for &(id, _) in &dims {
if !dim_ids.insert(id) {
return Err(ir::Error::DuplicateIncrement { dim: id });
}
}
// TODO(cleanup): return errors instead of panicing
match base {
ir::Operand::Reduce(..) => {
panic!("induction variables cannot perform reductions")
}
ir::Operand::Inst(.., ir::DimMapScope::Global(..)) =>
// TODO(search_space): allow dim map lowering for induction variables
{
unimplemented!(
"dim map lowering for induction vars is not implemented yet"
)
}
_ => (),
}
Ok(InductionVar { dims, base })
}
/// Renames a dimension.
pub fn merge_dims(&mut self, lhs: ir::DimId, rhs: ir::DimId) {
self.base.merge_dims(lhs, rhs);
}
/// Returns the base operand of the induction variable.
pub fn base(&self) -> &ir::Operand<L> {
&self.base
}
/// Returns the list of induction dimensions along with the corresponding increments.
pub fn dims(&self) -> &[(ir::DimId, ir::PartialSize)] {
&self.dims
}
}
impl InductionVar<()> {
pub fn freeze(self, cnt: &mut ir::Counter) -> InductionVar {
InductionVar {
dims: self.dims,
base: self.base.freeze(cnt),
}
}
}
impl<L> ir::IrDisplay<L> for InductionVar<L> {
fn fmt(&self, fmt: &mut fmt::Formatter, function: &ir::Function<L>) -> fmt::Result {
write!(
fmt,
"{}[{}]",
self.base.display(function),
self.dims.iter().map(|(id, _)| id).format(", ")
)
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
pub const CLSID_WMPMediaPluginRegistrar: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1433004021,
data2: 16971,
data3: 19347,
data4: [137, 202, 121, 209, 121, 36, 104, 154],
};
pub const CLSID_WMPSkinManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2997353810,
data2: 12319,
data3: 17224,
data4: [185, 58, 99, 140, 109, 228, 146, 41],
};
pub const CLSID_XFeedsManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4268429763, data2: 50990, data3: 16481, data4: [134, 198, 157, 22, 49, 33, 242, 41] };
pub const DISPID_DELTA: u32 = 50u32;
pub const DISPID_FEEDENCLOSURE_AsyncDownload: u32 = 24579u32;
pub const DISPID_FEEDENCLOSURE_CancelAsyncDownload: u32 = 24580u32;
pub const DISPID_FEEDENCLOSURE_DownloadMimeType: u32 = 24586u32;
pub const DISPID_FEEDENCLOSURE_DownloadStatus: u32 = 24581u32;
pub const DISPID_FEEDENCLOSURE_DownloadUrl: u32 = 24585u32;
pub const DISPID_FEEDENCLOSURE_LastDownloadError: u32 = 24582u32;
pub const DISPID_FEEDENCLOSURE_Length: u32 = 24578u32;
pub const DISPID_FEEDENCLOSURE_LocalPath: u32 = 24583u32;
pub const DISPID_FEEDENCLOSURE_Parent: u32 = 24584u32;
pub const DISPID_FEEDENCLOSURE_RemoveFile: u32 = 24587u32;
pub const DISPID_FEEDENCLOSURE_SetFile: u32 = 24588u32;
pub const DISPID_FEEDENCLOSURE_Type: u32 = 24577u32;
pub const DISPID_FEEDENCLOSURE_Url: u32 = 24576u32;
pub const DISPID_FEEDEVENTS_Error: u32 = 32768u32;
pub const DISPID_FEEDEVENTS_FeedDeleted: u32 = 32769u32;
pub const DISPID_FEEDEVENTS_FeedDownloadCompleted: u32 = 32774u32;
pub const DISPID_FEEDEVENTS_FeedDownloading: u32 = 32773u32;
pub const DISPID_FEEDEVENTS_FeedItemCountChanged: u32 = 32775u32;
pub const DISPID_FEEDEVENTS_FeedMoved: u32 = 32772u32;
pub const DISPID_FEEDEVENTS_FeedRenamed: u32 = 32770u32;
pub const DISPID_FEEDEVENTS_FeedUrlChanged: u32 = 32771u32;
pub const DISPID_FEEDFOLDEREVENTS_Error: u32 = 28672u32;
pub const DISPID_FEEDFOLDEREVENTS_FeedAdded: u32 = 28679u32;
pub const DISPID_FEEDFOLDEREVENTS_FeedDeleted: u32 = 28680u32;
pub const DISPID_FEEDFOLDEREVENTS_FeedDownloadCompleted: u32 = 28686u32;
pub const DISPID_FEEDFOLDEREVENTS_FeedDownloading: u32 = 28685u32;
pub const DISPID_FEEDFOLDEREVENTS_FeedItemCountChanged: u32 = 28687u32;
pub const DISPID_FEEDFOLDEREVENTS_FeedMovedFrom: u32 = 28683u32;
pub const DISPID_FEEDFOLDEREVENTS_FeedMovedTo: u32 = 28684u32;
pub const DISPID_FEEDFOLDEREVENTS_FeedRenamed: u32 = 28681u32;
pub const DISPID_FEEDFOLDEREVENTS_FeedUrlChanged: u32 = 28682u32;
pub const DISPID_FEEDFOLDEREVENTS_FolderAdded: u32 = 28673u32;
pub const DISPID_FEEDFOLDEREVENTS_FolderDeleted: u32 = 28674u32;
pub const DISPID_FEEDFOLDEREVENTS_FolderItemCountChanged: u32 = 28678u32;
pub const DISPID_FEEDFOLDEREVENTS_FolderMovedFrom: u32 = 28676u32;
pub const DISPID_FEEDFOLDEREVENTS_FolderMovedTo: u32 = 28677u32;
pub const DISPID_FEEDFOLDEREVENTS_FolderRenamed: u32 = 28675u32;
pub const DISPID_FEEDFOLDER_CreateFeed: u32 = 12290u32;
pub const DISPID_FEEDFOLDER_CreateSubfolder: u32 = 12291u32;
pub const DISPID_FEEDFOLDER_Delete: u32 = 12296u32;
pub const DISPID_FEEDFOLDER_ExistsFeed: u32 = 12292u32;
pub const DISPID_FEEDFOLDER_ExistsSubfolder: u32 = 12294u32;
pub const DISPID_FEEDFOLDER_Feeds: u32 = 12288u32;
pub const DISPID_FEEDFOLDER_GetFeed: u32 = 12293u32;
pub const DISPID_FEEDFOLDER_GetSubfolder: u32 = 12295u32;
pub const DISPID_FEEDFOLDER_GetWatcher: u32 = 12305u32;
pub const DISPID_FEEDFOLDER_IsRoot: u32 = 12302u32;
pub const DISPID_FEEDFOLDER_Move: u32 = 12300u32;
pub const DISPID_FEEDFOLDER_Name: u32 = 12297u32;
pub const DISPID_FEEDFOLDER_Parent: u32 = 12301u32;
pub const DISPID_FEEDFOLDER_Path: u32 = 12299u32;
pub const DISPID_FEEDFOLDER_Rename: u32 = 12298u32;
pub const DISPID_FEEDFOLDER_Subfolders: u32 = 12289u32;
pub const DISPID_FEEDFOLDER_TotalItemCount: u32 = 12304u32;
pub const DISPID_FEEDFOLDER_TotalUnreadItemCount: u32 = 12303u32;
pub const DISPID_FEEDITEM_Author: u32 = 20487u32;
pub const DISPID_FEEDITEM_Comments: u32 = 20486u32;
pub const DISPID_FEEDITEM_Delete: u32 = 20492u32;
pub const DISPID_FEEDITEM_Description: u32 = 20484u32;
pub const DISPID_FEEDITEM_DownloadUrl: u32 = 20493u32;
pub const DISPID_FEEDITEM_EffectiveId: u32 = 20496u32;
pub const DISPID_FEEDITEM_Enclosure: u32 = 20488u32;
pub const DISPID_FEEDITEM_Guid: u32 = 20483u32;
pub const DISPID_FEEDITEM_IsRead: u32 = 20489u32;
pub const DISPID_FEEDITEM_LastDownloadTime: u32 = 20494u32;
pub const DISPID_FEEDITEM_Link: u32 = 20482u32;
pub const DISPID_FEEDITEM_LocalId: u32 = 20490u32;
pub const DISPID_FEEDITEM_Modified: u32 = 20495u32;
pub const DISPID_FEEDITEM_Parent: u32 = 20491u32;
pub const DISPID_FEEDITEM_PubDate: u32 = 20485u32;
pub const DISPID_FEEDITEM_Title: u32 = 20481u32;
pub const DISPID_FEEDITEM_Xml: u32 = 20480u32;
pub const DISPID_FEEDSENUM_Count: u32 = 8192u32;
pub const DISPID_FEEDSENUM_Item: u32 = 8193u32;
pub const DISPID_FEEDS_AsyncSyncAll: u32 = 4108u32;
pub const DISPID_FEEDS_BackgroundSync: u32 = 4105u32;
pub const DISPID_FEEDS_BackgroundSyncStatus: u32 = 4106u32;
pub const DISPID_FEEDS_DefaultInterval: u32 = 4107u32;
pub const DISPID_FEEDS_DeleteFeed: u32 = 4102u32;
pub const DISPID_FEEDS_DeleteFolder: u32 = 4103u32;
pub const DISPID_FEEDS_ExistsFeed: u32 = 4098u32;
pub const DISPID_FEEDS_ExistsFolder: u32 = 4100u32;
pub const DISPID_FEEDS_GetFeed: u32 = 4099u32;
pub const DISPID_FEEDS_GetFeedByUrl: u32 = 4104u32;
pub const DISPID_FEEDS_GetFolder: u32 = 4101u32;
pub const DISPID_FEEDS_IsSubscribed: u32 = 4097u32;
pub const DISPID_FEEDS_ItemCountLimit: u32 = 4110u32;
pub const DISPID_FEEDS_Normalize: u32 = 4109u32;
pub const DISPID_FEEDS_RootFolder: u32 = 4096u32;
pub const DISPID_FEED_AsyncDownload: u32 = 16395u32;
pub const DISPID_FEED_CancelAsyncDownload: u32 = 16396u32;
pub const DISPID_FEED_ClearCredentials: u32 = 16428u32;
pub const DISPID_FEED_Copyright: u32 = 16411u32;
pub const DISPID_FEED_Delete: u32 = 16393u32;
pub const DISPID_FEED_Description: u32 = 16404u32;
pub const DISPID_FEED_Download: u32 = 16394u32;
pub const DISPID_FEED_DownloadEnclosuresAutomatically: u32 = 16412u32;
pub const DISPID_FEED_DownloadStatus: u32 = 16413u32;
pub const DISPID_FEED_DownloadUrl: u32 = 16416u32;
pub const DISPID_FEED_GetItem: u32 = 16402u32;
pub const DISPID_FEED_GetItemByEffectiveId: u32 = 16423u32;
pub const DISPID_FEED_GetWatcher: u32 = 16419u32;
pub const DISPID_FEED_Image: u32 = 16406u32;
pub const DISPID_FEED_Interval: u32 = 16397u32;
pub const DISPID_FEED_IsList: u32 = 16417u32;
pub const DISPID_FEED_ItemCount: u32 = 16421u32;
pub const DISPID_FEED_Items: u32 = 16401u32;
pub const DISPID_FEED_Language: u32 = 16410u32;
pub const DISPID_FEED_LastBuildDate: u32 = 16407u32;
pub const DISPID_FEED_LastDownloadError: u32 = 16414u32;
pub const DISPID_FEED_LastDownloadTime: u32 = 16399u32;
pub const DISPID_FEED_LastItemDownloadTime: u32 = 16424u32;
pub const DISPID_FEED_LastWriteTime: u32 = 16392u32;
pub const DISPID_FEED_Link: u32 = 16405u32;
pub const DISPID_FEED_LocalEnclosurePath: u32 = 16400u32;
pub const DISPID_FEED_LocalId: u32 = 16388u32;
pub const DISPID_FEED_MarkAllItemsRead: u32 = 16418u32;
pub const DISPID_FEED_MaxItemCount: u32 = 16422u32;
pub const DISPID_FEED_Merge: u32 = 16415u32;
pub const DISPID_FEED_Move: u32 = 16390u32;
pub const DISPID_FEED_Name: u32 = 16385u32;
pub const DISPID_FEED_Parent: u32 = 16391u32;
pub const DISPID_FEED_Password: u32 = 16426u32;
pub const DISPID_FEED_Path: u32 = 16389u32;
pub const DISPID_FEED_PubDate: u32 = 16408u32;
pub const DISPID_FEED_Rename: u32 = 16386u32;
pub const DISPID_FEED_SetCredentials: u32 = 16427u32;
pub const DISPID_FEED_SyncSetting: u32 = 16398u32;
pub const DISPID_FEED_Title: u32 = 16403u32;
pub const DISPID_FEED_Ttl: u32 = 16409u32;
pub const DISPID_FEED_UnreadItemCount: u32 = 16420u32;
pub const DISPID_FEED_Url: u32 = 16387u32;
pub const DISPID_FEED_Username: u32 = 16425u32;
pub const DISPID_FEED_Xml: u32 = 16384u32;
pub const DISPID_WMPCDROMCOLLECTION_BASE: u32 = 300u32;
pub const DISPID_WMPCDROMCOLLECTION_COUNT: u32 = 301u32;
pub const DISPID_WMPCDROMCOLLECTION_GETBYDRIVESPECIFIER: u32 = 303u32;
pub const DISPID_WMPCDROMCOLLECTION_ITEM: u32 = 302u32;
pub const DISPID_WMPCDROMCOLLECTION_STARTMONITORINGCDROMS: u32 = 304u32;
pub const DISPID_WMPCDROMCOLLECTION_STOPMONITORINGCDROMS: u32 = 305u32;
pub const DISPID_WMPCDROM_BASE: u32 = 250u32;
pub const DISPID_WMPCDROM_DRIVESPECIFIER: u32 = 251u32;
pub const DISPID_WMPCDROM_EJECT: u32 = 253u32;
pub const DISPID_WMPCDROM_PLAYLIST: u32 = 252u32;
pub const DISPID_WMPCLOSEDCAPTION2_GETLANGCOUNT: u32 = 955u32;
pub const DISPID_WMPCLOSEDCAPTION2_GETLANGID: u32 = 957u32;
pub const DISPID_WMPCLOSEDCAPTION2_GETLANGNAME: u32 = 956u32;
pub const DISPID_WMPCLOSEDCAPTION2_GETSTYLECOUNT: u32 = 958u32;
pub const DISPID_WMPCLOSEDCAPTION2_GETSTYLENAME: u32 = 959u32;
pub const DISPID_WMPCLOSEDCAPTION_BASE: u32 = 950u32;
pub const DISPID_WMPCLOSEDCAPTION_CAPTIONINGID: u32 = 954u32;
pub const DISPID_WMPCLOSEDCAPTION_SAMIFILENAME: u32 = 953u32;
pub const DISPID_WMPCLOSEDCAPTION_SAMILANG: u32 = 952u32;
pub const DISPID_WMPCLOSEDCAPTION_SAMISTYLE: u32 = 951u32;
pub const DISPID_WMPCONTROLS2_STEP: u32 = 64u32;
pub const DISPID_WMPCONTROLS3_AUDIOLANGUAGECOUNT: u32 = 65u32;
pub const DISPID_WMPCONTROLS3_CURRENTAUDIOLANGUAGE: u32 = 68u32;
pub const DISPID_WMPCONTROLS3_CURRENTAUDIOLANGUAGEINDEX: u32 = 69u32;
pub const DISPID_WMPCONTROLS3_CURRENTPOSITIONTIMECODE: u32 = 71u32;
pub const DISPID_WMPCONTROLS3_GETAUDIOLANGUAGEDESC: u32 = 67u32;
pub const DISPID_WMPCONTROLS3_GETAUDIOLANGUAGEID: u32 = 66u32;
pub const DISPID_WMPCONTROLS3_GETLANGUAGENAME: u32 = 70u32;
pub const DISPID_WMPCONTROLSFAKE_TIMECOMPRESSION: u32 = 72u32;
pub const DISPID_WMPCONTROLS_BASE: u32 = 50u32;
pub const DISPID_WMPCONTROLS_CURRENTITEM: u32 = 60u32;
pub const DISPID_WMPCONTROLS_CURRENTMARKER: u32 = 61u32;
pub const DISPID_WMPCONTROLS_CURRENTPOSITION: u32 = 56u32;
pub const DISPID_WMPCONTROLS_CURRENTPOSITIONSTRING: u32 = 57u32;
pub const DISPID_WMPCONTROLS_FASTFORWARD: u32 = 54u32;
pub const DISPID_WMPCONTROLS_FASTREVERSE: u32 = 55u32;
pub const DISPID_WMPCONTROLS_ISAVAILABLE: u32 = 62u32;
pub const DISPID_WMPCONTROLS_NEXT: u32 = 58u32;
pub const DISPID_WMPCONTROLS_PAUSE: u32 = 53u32;
pub const DISPID_WMPCONTROLS_PLAY: u32 = 51u32;
pub const DISPID_WMPCONTROLS_PLAYITEM: u32 = 63u32;
pub const DISPID_WMPCONTROLS_PREVIOUS: u32 = 59u32;
pub const DISPID_WMPCONTROLS_STOP: u32 = 52u32;
pub const DISPID_WMPCORE2_BASE: u32 = 39u32;
pub const DISPID_WMPCORE2_DVD: u32 = 40u32;
pub const DISPID_WMPCORE3_NEWMEDIA: u32 = 42u32;
pub const DISPID_WMPCORE3_NEWPLAYLIST: u32 = 41u32;
pub const DISPID_WMPCOREEVENT_AUDIOLANGUAGECHANGE: u32 = 5102u32;
pub const DISPID_WMPCOREEVENT_BUFFERING: u32 = 5402u32;
pub const DISPID_WMPCOREEVENT_CDROMMEDIACHANGE: u32 = 5701u32;
pub const DISPID_WMPCOREEVENT_CURRENTITEMCHANGE: u32 = 5806u32;
pub const DISPID_WMPCOREEVENT_CURRENTMEDIAITEMAVAILABLE: u32 = 5803u32;
pub const DISPID_WMPCOREEVENT_CURRENTPLAYLISTCHANGE: u32 = 5804u32;
pub const DISPID_WMPCOREEVENT_CURRENTPLAYLISTITEMAVAILABLE: u32 = 5805u32;
pub const DISPID_WMPCOREEVENT_DISCONNECT: u32 = 5401u32;
pub const DISPID_WMPCOREEVENT_DOMAINCHANGE: u32 = 5822u32;
pub const DISPID_WMPCOREEVENT_DURATIONUNITCHANGE: u32 = 5204u32;
pub const DISPID_WMPCOREEVENT_ENDOFSTREAM: u32 = 5201u32;
pub const DISPID_WMPCOREEVENT_ERROR: u32 = 5501u32;
pub const DISPID_WMPCOREEVENT_MARKERHIT: u32 = 5203u32;
pub const DISPID_WMPCOREEVENT_MEDIACHANGE: u32 = 5802u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONATTRIBUTESTRINGADDED: u32 = 5808u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONATTRIBUTESTRINGCHANGED: u32 = 5820u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONATTRIBUTESTRINGREMOVED: u32 = 5809u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONCHANGE: u32 = 5807u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONCONTENTSCANADDEDITEM: u32 = 5813u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONCONTENTSCANPROGRESS: u32 = 5814u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONMEDIAADDED: u32 = 5825u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONMEDIAREMOVED: u32 = 5826u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONSEARCHCOMPLETE: u32 = 5817u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONSEARCHFOUNDITEM: u32 = 5815u32;
pub const DISPID_WMPCOREEVENT_MEDIACOLLECTIONSEARCHPROGRESS: u32 = 5816u32;
pub const DISPID_WMPCOREEVENT_MEDIAERROR: u32 = 5821u32;
pub const DISPID_WMPCOREEVENT_MODECHANGE: u32 = 5819u32;
pub const DISPID_WMPCOREEVENT_NEWSTREAM: u32 = 5403u32;
pub const DISPID_WMPCOREEVENT_OPENPLAYLISTSWITCH: u32 = 5823u32;
pub const DISPID_WMPCOREEVENT_OPENSTATECHANGE: u32 = 5001u32;
pub const DISPID_WMPCOREEVENT_PLAYLISTCHANGE: u32 = 5801u32;
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONCHANGE: u32 = 5810u32;
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONPLAYLISTADDED: u32 = 5811u32;
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONPLAYLISTREMOVED: u32 = 5812u32;
pub const DISPID_WMPCOREEVENT_PLAYLISTCOLLECTIONPLAYLISTSETASDELETED: u32 = 5818u32;
pub const DISPID_WMPCOREEVENT_PLAYSTATECHANGE: u32 = 5101u32;
pub const DISPID_WMPCOREEVENT_POSITIONCHANGE: u32 = 5202u32;
pub const DISPID_WMPCOREEVENT_SCRIPTCOMMAND: u32 = 5301u32;
pub const DISPID_WMPCOREEVENT_STATUSCHANGE: u32 = 5002u32;
pub const DISPID_WMPCOREEVENT_STRINGCOLLECTIONCHANGE: u32 = 5824u32;
pub const DISPID_WMPCOREEVENT_WARNING: u32 = 5601u32;
pub const DISPID_WMPCORE_BASE: u32 = 0u32;
pub const DISPID_WMPCORE_CDROMCOLLECTION: u32 = 14u32;
pub const DISPID_WMPCORE_CLOSE: u32 = 3u32;
pub const DISPID_WMPCORE_CLOSEDCAPTION: u32 = 15u32;
pub const DISPID_WMPCORE_CONTROLS: u32 = 4u32;
pub const DISPID_WMPCORE_CURRENTMEDIA: u32 = 6u32;
pub const DISPID_WMPCORE_CURRENTPLAYLIST: u32 = 13u32;
pub const DISPID_WMPCORE_ERROR: u32 = 17u32;
pub const DISPID_WMPCORE_ISONLINE: u32 = 16u32;
pub const DISPID_WMPCORE_LAST: u32 = 18u32;
pub const DISPID_WMPCORE_LAUNCHURL: u32 = 12u32;
pub const DISPID_WMPCORE_MAX: u32 = 1454u32;
pub const DISPID_WMPCORE_MEDIACOLLECTION: u32 = 8u32;
pub const DISPID_WMPCORE_MIN: u32 = 1u32;
pub const DISPID_WMPCORE_NETWORK: u32 = 7u32;
pub const DISPID_WMPCORE_OPENSTATE: u32 = 2u32;
pub const DISPID_WMPCORE_PLAYLISTCOLLECTION: u32 = 9u32;
pub const DISPID_WMPCORE_PLAYSTATE: u32 = 10u32;
pub const DISPID_WMPCORE_SETTINGS: u32 = 5u32;
pub const DISPID_WMPCORE_STATUS: u32 = 18u32;
pub const DISPID_WMPCORE_URL: u32 = 1u32;
pub const DISPID_WMPCORE_VERSIONINFO: u32 = 11u32;
pub const DISPID_WMPDOWNLOADCOLLECTION_BASE: u32 = 1200u32;
pub const DISPID_WMPDOWNLOADCOLLECTION_CLEAR: u32 = 1206u32;
pub const DISPID_WMPDOWNLOADCOLLECTION_COUNT: u32 = 1202u32;
pub const DISPID_WMPDOWNLOADCOLLECTION_ID: u32 = 1201u32;
pub const DISPID_WMPDOWNLOADCOLLECTION_ITEM: u32 = 1203u32;
pub const DISPID_WMPDOWNLOADCOLLECTION_REMOVEITEM: u32 = 1205u32;
pub const DISPID_WMPDOWNLOADCOLLECTION_STARTDOWNLOAD: u32 = 1204u32;
pub const DISPID_WMPDOWNLOADITEM2_BASE: u32 = 1300u32;
pub const DISPID_WMPDOWNLOADITEM2_GETITEMINFO: u32 = 1301u32;
pub const DISPID_WMPDOWNLOADITEM_BASE: u32 = 1250u32;
pub const DISPID_WMPDOWNLOADITEM_CANCEL: u32 = 1258u32;
pub const DISPID_WMPDOWNLOADITEM_DOWNLOADSTATE: u32 = 1255u32;
pub const DISPID_WMPDOWNLOADITEM_PAUSE: u32 = 1256u32;
pub const DISPID_WMPDOWNLOADITEM_PROGRESS: u32 = 1254u32;
pub const DISPID_WMPDOWNLOADITEM_RESUME: u32 = 1257u32;
pub const DISPID_WMPDOWNLOADITEM_SIZE: u32 = 1252u32;
pub const DISPID_WMPDOWNLOADITEM_SOURCEURL: u32 = 1251u32;
pub const DISPID_WMPDOWNLOADITEM_TYPE: u32 = 1253u32;
pub const DISPID_WMPDOWNLOADMANAGER_BASE: u32 = 1150u32;
pub const DISPID_WMPDOWNLOADMANAGER_CREATEDOWNLOADCOLLECTION: u32 = 1152u32;
pub const DISPID_WMPDOWNLOADMANAGER_GETDOWNLOADCOLLECTION: u32 = 1151u32;
pub const DISPID_WMPDVD_BACK: u32 = 1005u32;
pub const DISPID_WMPDVD_BASE: u32 = 1000u32;
pub const DISPID_WMPDVD_DOMAIN: u32 = 1002u32;
pub const DISPID_WMPDVD_ISAVAILABLE: u32 = 1001u32;
pub const DISPID_WMPDVD_RESUME: u32 = 1006u32;
pub const DISPID_WMPDVD_TITLEMENU: u32 = 1004u32;
pub const DISPID_WMPDVD_TOPMENU: u32 = 1003u32;
pub const DISPID_WMPERRORITEM2_CONDITION: u32 = 906u32;
pub const DISPID_WMPERRORITEM_BASE: u32 = 900u32;
pub const DISPID_WMPERRORITEM_CUSTOMURL: u32 = 905u32;
pub const DISPID_WMPERRORITEM_ERRORCODE: u32 = 901u32;
pub const DISPID_WMPERRORITEM_ERRORCONTEXT: u32 = 903u32;
pub const DISPID_WMPERRORITEM_ERRORDESCRIPTION: u32 = 902u32;
pub const DISPID_WMPERRORITEM_REMEDY: u32 = 904u32;
pub const DISPID_WMPERROR_BASE: u32 = 850u32;
pub const DISPID_WMPERROR_CLEARERRORQUEUE: u32 = 851u32;
pub const DISPID_WMPERROR_ERRORCOUNT: u32 = 852u32;
pub const DISPID_WMPERROR_ITEM: u32 = 853u32;
pub const DISPID_WMPERROR_WEBHELP: u32 = 854u32;
pub const DISPID_WMPMEDIA2_ERROR: u32 = 768u32;
pub const DISPID_WMPMEDIA3_GETATTRIBUTECOUNTBYTYPE: u32 = 769u32;
pub const DISPID_WMPMEDIA3_GETITEMINFOBYTYPE: u32 = 770u32;
pub const DISPID_WMPMEDIACOLLECTION2_BASE: u32 = 1400u32;
pub const DISPID_WMPMEDIACOLLECTION2_CREATEQUERY: u32 = 1401u32;
pub const DISPID_WMPMEDIACOLLECTION2_GETBYATTRANDMEDIATYPE: u32 = 1404u32;
pub const DISPID_WMPMEDIACOLLECTION2_GETPLAYLISTBYQUERY: u32 = 1402u32;
pub const DISPID_WMPMEDIACOLLECTION2_GETSTRINGCOLLBYQUERY: u32 = 1403u32;
pub const DISPID_WMPMEDIACOLLECTION_ADD: u32 = 452u32;
pub const DISPID_WMPMEDIACOLLECTION_BASE: u32 = 450u32;
pub const DISPID_WMPMEDIACOLLECTION_FREEZECOLLECTIONCHANGE: u32 = 474u32;
pub const DISPID_WMPMEDIACOLLECTION_GETALL: u32 = 453u32;
pub const DISPID_WMPMEDIACOLLECTION_GETATTRIBUTESTRINGCOLLECTION: u32 = 461u32;
pub const DISPID_WMPMEDIACOLLECTION_GETBYALBUM: u32 = 457u32;
pub const DISPID_WMPMEDIACOLLECTION_GETBYATTRIBUTE: u32 = 458u32;
pub const DISPID_WMPMEDIACOLLECTION_GETBYAUTHOR: u32 = 456u32;
pub const DISPID_WMPMEDIACOLLECTION_GETBYGENRE: u32 = 455u32;
pub const DISPID_WMPMEDIACOLLECTION_GETBYNAME: u32 = 454u32;
pub const DISPID_WMPMEDIACOLLECTION_GETBYQUERYDESCRIPTION: u32 = 473u32;
pub const DISPID_WMPMEDIACOLLECTION_GETMEDIAATOM: u32 = 470u32;
pub const DISPID_WMPMEDIACOLLECTION_ISDELETED: u32 = 472u32;
pub const DISPID_WMPMEDIACOLLECTION_NEWQUERY: u32 = 462u32;
pub const DISPID_WMPMEDIACOLLECTION_POSTCOLLECTIONCHANGE: u32 = 476u32;
pub const DISPID_WMPMEDIACOLLECTION_REMOVE: u32 = 459u32;
pub const DISPID_WMPMEDIACOLLECTION_SETDELETED: u32 = 471u32;
pub const DISPID_WMPMEDIACOLLECTION_STARTCONTENTSCAN: u32 = 465u32;
pub const DISPID_WMPMEDIACOLLECTION_STARTMONITORING: u32 = 463u32;
pub const DISPID_WMPMEDIACOLLECTION_STARTSEARCH: u32 = 467u32;
pub const DISPID_WMPMEDIACOLLECTION_STOPCONTENTSCAN: u32 = 466u32;
pub const DISPID_WMPMEDIACOLLECTION_STOPMONITORING: u32 = 464u32;
pub const DISPID_WMPMEDIACOLLECTION_STOPSEARCH: u32 = 468u32;
pub const DISPID_WMPMEDIACOLLECTION_UNFREEZECOLLECTIONCHANGE: u32 = 475u32;
pub const DISPID_WMPMEDIACOLLECTION_UPDATEMETADATA: u32 = 469u32;
pub const DISPID_WMPMEDIA_ATTRIBUTECOUNT: u32 = 759u32;
pub const DISPID_WMPMEDIA_BASE: u32 = 750u32;
pub const DISPID_WMPMEDIA_DURATION: u32 = 757u32;
pub const DISPID_WMPMEDIA_DURATIONSTRING: u32 = 758u32;
pub const DISPID_WMPMEDIA_GETATTRIBUTENAME: u32 = 760u32;
pub const DISPID_WMPMEDIA_GETITEMINFO: u32 = 761u32;
pub const DISPID_WMPMEDIA_GETITEMINFOBYATOM: u32 = 765u32;
pub const DISPID_WMPMEDIA_GETMARKERNAME: u32 = 756u32;
pub const DISPID_WMPMEDIA_GETMARKERTIME: u32 = 755u32;
pub const DISPID_WMPMEDIA_IMAGESOURCEHEIGHT: u32 = 753u32;
pub const DISPID_WMPMEDIA_IMAGESOURCEWIDTH: u32 = 752u32;
pub const DISPID_WMPMEDIA_ISIDENTICAL: u32 = 763u32;
pub const DISPID_WMPMEDIA_ISMEMBEROF: u32 = 766u32;
pub const DISPID_WMPMEDIA_ISREADONLYITEM: u32 = 767u32;
pub const DISPID_WMPMEDIA_MARKERCOUNT: u32 = 754u32;
pub const DISPID_WMPMEDIA_NAME: u32 = 764u32;
pub const DISPID_WMPMEDIA_SETITEMINFO: u32 = 762u32;
pub const DISPID_WMPMEDIA_SOURCEURL: u32 = 751u32;
pub const DISPID_WMPMETADATA_BASE: u32 = 1050u32;
pub const DISPID_WMPMETADATA_PICTURE_DESCRIPTION: u32 = 1053u32;
pub const DISPID_WMPMETADATA_PICTURE_MIMETYPE: u32 = 1051u32;
pub const DISPID_WMPMETADATA_PICTURE_PICTURETYPE: u32 = 1052u32;
pub const DISPID_WMPMETADATA_PICTURE_URL: u32 = 1054u32;
pub const DISPID_WMPMETADATA_TEXT_DESCRIPTION: u32 = 1056u32;
pub const DISPID_WMPMETADATA_TEXT_TEXT: u32 = 1055u32;
pub const DISPID_WMPNETWORK_BANDWIDTH: u32 = 801u32;
pub const DISPID_WMPNETWORK_BASE: u32 = 800u32;
pub const DISPID_WMPNETWORK_BITRATE: u32 = 812u32;
pub const DISPID_WMPNETWORK_BUFFERINGCOUNT: u32 = 807u32;
pub const DISPID_WMPNETWORK_BUFFERINGPROGRESS: u32 = 808u32;
pub const DISPID_WMPNETWORK_BUFFERINGTIME: u32 = 809u32;
pub const DISPID_WMPNETWORK_DOWNLOADPROGRESS: u32 = 824u32;
pub const DISPID_WMPNETWORK_ENCODEDFRAMERATE: u32 = 825u32;
pub const DISPID_WMPNETWORK_FRAMERATE: u32 = 810u32;
pub const DISPID_WMPNETWORK_FRAMESSKIPPED: u32 = 826u32;
pub const DISPID_WMPNETWORK_GETPROXYBYPASSFORLOCAL: u32 = 821u32;
pub const DISPID_WMPNETWORK_GETPROXYEXCEPTIONLIST: u32 = 819u32;
pub const DISPID_WMPNETWORK_GETPROXYNAME: u32 = 815u32;
pub const DISPID_WMPNETWORK_GETPROXYPORT: u32 = 817u32;
pub const DISPID_WMPNETWORK_GETPROXYSETTINGS: u32 = 813u32;
pub const DISPID_WMPNETWORK_LOSTPACKETS: u32 = 805u32;
pub const DISPID_WMPNETWORK_MAXBANDWIDTH: u32 = 823u32;
pub const DISPID_WMPNETWORK_MAXBITRATE: u32 = 811u32;
pub const DISPID_WMPNETWORK_RECEIVEDPACKETS: u32 = 804u32;
pub const DISPID_WMPNETWORK_RECEPTIONQUALITY: u32 = 806u32;
pub const DISPID_WMPNETWORK_RECOVEREDPACKETS: u32 = 802u32;
pub const DISPID_WMPNETWORK_SETPROXYBYPASSFORLOCAL: u32 = 822u32;
pub const DISPID_WMPNETWORK_SETPROXYEXCEPTIONLIST: u32 = 820u32;
pub const DISPID_WMPNETWORK_SETPROXYNAME: u32 = 816u32;
pub const DISPID_WMPNETWORK_SETPROXYPORT: u32 = 818u32;
pub const DISPID_WMPNETWORK_SETPROXYSETTINGS: u32 = 814u32;
pub const DISPID_WMPNETWORK_SOURCEPROTOCOL: u32 = 803u32;
pub const DISPID_WMPOCX2_BASE: u32 = 23u32;
pub const DISPID_WMPOCX2_STRETCHTOFIT: u32 = 24u32;
pub const DISPID_WMPOCX2_WINDOWLESSVIDEO: u32 = 25u32;
pub const DISPID_WMPOCX4_ISREMOTE: u32 = 26u32;
pub const DISPID_WMPOCX4_OPENPLAYER: u32 = 28u32;
pub const DISPID_WMPOCX4_PLAYERAPPLICATION: u32 = 27u32;
pub const DISPID_WMPOCXEVENT_CDROMBURNERROR: u32 = 6523u32;
pub const DISPID_WMPOCXEVENT_CDROMBURNMEDIAERROR: u32 = 6522u32;
pub const DISPID_WMPOCXEVENT_CDROMBURNSTATECHANGE: u32 = 6521u32;
pub const DISPID_WMPOCXEVENT_CDROMRIPMEDIAERROR: u32 = 6520u32;
pub const DISPID_WMPOCXEVENT_CDROMRIPSTATECHANGE: u32 = 6519u32;
pub const DISPID_WMPOCXEVENT_CLICK: u32 = 6505u32;
pub const DISPID_WMPOCXEVENT_CREATEPARTNERSHIPCOMPLETE: u32 = 6518u32;
pub const DISPID_WMPOCXEVENT_DEVICECONNECT: u32 = 6513u32;
pub const DISPID_WMPOCXEVENT_DEVICEDISCONNECT: u32 = 6514u32;
pub const DISPID_WMPOCXEVENT_DEVICEESTIMATION: u32 = 6527u32;
pub const DISPID_WMPOCXEVENT_DEVICESTATUSCHANGE: u32 = 6515u32;
pub const DISPID_WMPOCXEVENT_DEVICESYNCERROR: u32 = 6517u32;
pub const DISPID_WMPOCXEVENT_DEVICESYNCSTATECHANGE: u32 = 6516u32;
pub const DISPID_WMPOCXEVENT_DOUBLECLICK: u32 = 6506u32;
pub const DISPID_WMPOCXEVENT_FOLDERSCANSTATECHANGE: u32 = 6526u32;
pub const DISPID_WMPOCXEVENT_KEYDOWN: u32 = 6507u32;
pub const DISPID_WMPOCXEVENT_KEYPRESS: u32 = 6508u32;
pub const DISPID_WMPOCXEVENT_KEYUP: u32 = 6509u32;
pub const DISPID_WMPOCXEVENT_LIBRARYCONNECT: u32 = 6524u32;
pub const DISPID_WMPOCXEVENT_LIBRARYDISCONNECT: u32 = 6525u32;
pub const DISPID_WMPOCXEVENT_MOUSEDOWN: u32 = 6510u32;
pub const DISPID_WMPOCXEVENT_MOUSEMOVE: u32 = 6511u32;
pub const DISPID_WMPOCXEVENT_MOUSEUP: u32 = 6512u32;
pub const DISPID_WMPOCXEVENT_PLAYERDOCKEDSTATECHANGE: u32 = 6503u32;
pub const DISPID_WMPOCXEVENT_PLAYERRECONNECT: u32 = 6504u32;
pub const DISPID_WMPOCXEVENT_SWITCHEDTOCONTROL: u32 = 6502u32;
pub const DISPID_WMPOCXEVENT_SWITCHEDTOPLAYERAPPLICATION: u32 = 6501u32;
pub const DISPID_WMPOCX_BASE: u32 = 18u32;
pub const DISPID_WMPOCX_ENABLECONTEXTMENU: u32 = 22u32;
pub const DISPID_WMPOCX_ENABLED: u32 = 19u32;
pub const DISPID_WMPOCX_FULLSCREEN: u32 = 21u32;
pub const DISPID_WMPOCX_LAST: u32 = 23u32;
pub const DISPID_WMPOCX_TRANSPARENTATSTART: u32 = 20u32;
pub const DISPID_WMPOCX_UIMODE: u32 = 23u32;
pub const DISPID_WMPPLAYERAPP_BASE: u32 = 1100u32;
pub const DISPID_WMPPLAYERAPP_HASDISPLAY: u32 = 1104u32;
pub const DISPID_WMPPLAYERAPP_PLAYERDOCKED: u32 = 1103u32;
pub const DISPID_WMPPLAYERAPP_REMOTESTATUS: u32 = 1105u32;
pub const DISPID_WMPPLAYERAPP_SWITCHTOCONTROL: u32 = 1102u32;
pub const DISPID_WMPPLAYERAPP_SWITCHTOPLAYERAPPLICATION: u32 = 1101u32;
pub const DISPID_WMPPLAYLISTARRAY_BASE: u32 = 500u32;
pub const DISPID_WMPPLAYLISTARRAY_COUNT: u32 = 501u32;
pub const DISPID_WMPPLAYLISTARRAY_ITEM: u32 = 502u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_BASE: u32 = 550u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_GETALL: u32 = 553u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_GETBYNAME: u32 = 554u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_GETBYQUERYDESCRIPTION: u32 = 555u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_IMPORTPLAYLIST: u32 = 562u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_ISDELETED: u32 = 561u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_NEWPLAYLIST: u32 = 552u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_NEWQUERY: u32 = 557u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_REMOVE: u32 = 556u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_SETDELETED: u32 = 560u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_STARTMONITORING: u32 = 558u32;
pub const DISPID_WMPPLAYLISTCOLLECTION_STOPMONITORING: u32 = 559u32;
pub const DISPID_WMPPLAYLIST_APPENDITEM: u32 = 207u32;
pub const DISPID_WMPPLAYLIST_ATTRIBUTECOUNT: u32 = 210u32;
pub const DISPID_WMPPLAYLIST_ATTRIBUTENAME: u32 = 211u32;
pub const DISPID_WMPPLAYLIST_BASE: u32 = 200u32;
pub const DISPID_WMPPLAYLIST_CLEAR: u32 = 205u32;
pub const DISPID_WMPPLAYLIST_COUNT: u32 = 201u32;
pub const DISPID_WMPPLAYLIST_GETITEMINFO: u32 = 203u32;
pub const DISPID_WMPPLAYLIST_INSERTITEM: u32 = 206u32;
pub const DISPID_WMPPLAYLIST_ISIDENTICAL: u32 = 213u32;
pub const DISPID_WMPPLAYLIST_ITEM: u32 = 212u32;
pub const DISPID_WMPPLAYLIST_MOVEITEM: u32 = 209u32;
pub const DISPID_WMPPLAYLIST_NAME: u32 = 202u32;
pub const DISPID_WMPPLAYLIST_REMOVEITEM: u32 = 208u32;
pub const DISPID_WMPPLAYLIST_SETITEMINFO: u32 = 204u32;
pub const DISPID_WMPQUERY_ADDCONDITION: u32 = 1351u32;
pub const DISPID_WMPQUERY_BASE: u32 = 1350u32;
pub const DISPID_WMPQUERY_BEGINNEXTGROUP: u32 = 1352u32;
pub const DISPID_WMPSETTINGS2_DEFAULTAUDIOLANGUAGE: u32 = 114u32;
pub const DISPID_WMPSETTINGS2_LIBRARYACCESSRIGHTS: u32 = 115u32;
pub const DISPID_WMPSETTINGS2_REQUESTLIBRARYACCESSRIGHTS: u32 = 116u32;
pub const DISPID_WMPSETTINGS_AUTOSTART: u32 = 101u32;
pub const DISPID_WMPSETTINGS_BALANCE: u32 = 102u32;
pub const DISPID_WMPSETTINGS_BASE: u32 = 100u32;
pub const DISPID_WMPSETTINGS_BASEURL: u32 = 108u32;
pub const DISPID_WMPSETTINGS_DEFAULTFRAME: u32 = 109u32;
pub const DISPID_WMPSETTINGS_ENABLEERRORDIALOGS: u32 = 112u32;
pub const DISPID_WMPSETTINGS_GETMODE: u32 = 110u32;
pub const DISPID_WMPSETTINGS_INVOKEURLS: u32 = 103u32;
pub const DISPID_WMPSETTINGS_ISAVAILABLE: u32 = 113u32;
pub const DISPID_WMPSETTINGS_MUTE: u32 = 104u32;
pub const DISPID_WMPSETTINGS_PLAYCOUNT: u32 = 105u32;
pub const DISPID_WMPSETTINGS_RATE: u32 = 106u32;
pub const DISPID_WMPSETTINGS_SETMODE: u32 = 111u32;
pub const DISPID_WMPSETTINGS_VOLUME: u32 = 107u32;
pub const DISPID_WMPSTRINGCOLLECTION2_BASE: u32 = 1450u32;
pub const DISPID_WMPSTRINGCOLLECTION2_GETATTRCOUNTBYTYPE: u32 = 1453u32;
pub const DISPID_WMPSTRINGCOLLECTION2_GETITEMINFO: u32 = 1452u32;
pub const DISPID_WMPSTRINGCOLLECTION2_GETITEMINFOBYTYPE: u32 = 1454u32;
pub const DISPID_WMPSTRINGCOLLECTION2_ISIDENTICAL: u32 = 1451u32;
pub const DISPID_WMPSTRINGCOLLECTION_BASE: u32 = 400u32;
pub const DISPID_WMPSTRINGCOLLECTION_COUNT: u32 = 401u32;
pub const DISPID_WMPSTRINGCOLLECTION_ITEM: u32 = 402u32;
pub const EFFECT2_FULLSCREENEXCLUSIVE: u32 = 16u32;
pub const EFFECT_CANGOFULLSCREEN: u32 = 1u32;
pub const EFFECT_HASPROPERTYPAGE: u32 = 2u32;
pub const EFFECT_VARIABLEFREQSTEP: u32 = 4u32;
pub const EFFECT_WINDOWEDONLY: u32 = 8u32;
pub type FEEDS_BACKGROUNDSYNC_ACTION = i32;
pub const FBSA_DISABLE: FEEDS_BACKGROUNDSYNC_ACTION = 0i32;
pub const FBSA_ENABLE: FEEDS_BACKGROUNDSYNC_ACTION = 1i32;
pub const FBSA_RUNNOW: FEEDS_BACKGROUNDSYNC_ACTION = 2i32;
pub type FEEDS_BACKGROUNDSYNC_STATUS = i32;
pub const FBSS_DISABLED: FEEDS_BACKGROUNDSYNC_STATUS = 0i32;
pub const FBSS_ENABLED: FEEDS_BACKGROUNDSYNC_STATUS = 1i32;
pub type FEEDS_DOWNLOAD_ERROR = i32;
pub const FDE_NONE: FEEDS_DOWNLOAD_ERROR = 0i32;
pub const FDE_DOWNLOAD_FAILED: FEEDS_DOWNLOAD_ERROR = 1i32;
pub const FDE_INVALID_FEED_FORMAT: FEEDS_DOWNLOAD_ERROR = 2i32;
pub const FDE_NORMALIZATION_FAILED: FEEDS_DOWNLOAD_ERROR = 3i32;
pub const FDE_PERSISTENCE_FAILED: FEEDS_DOWNLOAD_ERROR = 4i32;
pub const FDE_DOWNLOAD_BLOCKED: FEEDS_DOWNLOAD_ERROR = 5i32;
pub const FDE_CANCELED: FEEDS_DOWNLOAD_ERROR = 6i32;
pub const FDE_UNSUPPORTED_AUTH: FEEDS_DOWNLOAD_ERROR = 7i32;
pub const FDE_BACKGROUND_DOWNLOAD_DISABLED: FEEDS_DOWNLOAD_ERROR = 8i32;
pub const FDE_NOT_EXIST: FEEDS_DOWNLOAD_ERROR = 9i32;
pub const FDE_UNSUPPORTED_MSXML: FEEDS_DOWNLOAD_ERROR = 10i32;
pub const FDE_UNSUPPORTED_DTD: FEEDS_DOWNLOAD_ERROR = 11i32;
pub const FDE_DOWNLOAD_SIZE_LIMIT_EXCEEDED: FEEDS_DOWNLOAD_ERROR = 12i32;
pub const FDE_ACCESS_DENIED: FEEDS_DOWNLOAD_ERROR = 13i32;
pub const FDE_AUTH_FAILED: FEEDS_DOWNLOAD_ERROR = 14i32;
pub const FDE_INVALID_AUTH: FEEDS_DOWNLOAD_ERROR = 15i32;
pub type FEEDS_DOWNLOAD_STATUS = i32;
pub const FDS_NONE: FEEDS_DOWNLOAD_STATUS = 0i32;
pub const FDS_PENDING: FEEDS_DOWNLOAD_STATUS = 1i32;
pub const FDS_DOWNLOADING: FEEDS_DOWNLOAD_STATUS = 2i32;
pub const FDS_DOWNLOADED: FEEDS_DOWNLOAD_STATUS = 3i32;
pub const FDS_DOWNLOAD_FAILED: FEEDS_DOWNLOAD_STATUS = 4i32;
pub type FEEDS_ERROR_CODE = i32;
pub const FEC_E_ERRORBASE: FEEDS_ERROR_CODE = -1073479168i32;
pub const FEC_E_INVALIDMSXMLPROPERTY: FEEDS_ERROR_CODE = -1073479168i32;
pub const FEC_E_DOWNLOADSIZELIMITEXCEEDED: FEEDS_ERROR_CODE = -1073479167i32;
pub type FEEDS_EVENTS_ITEM_COUNT_FLAGS = i32;
pub const FEICF_READ_ITEM_COUNT_CHANGED: FEEDS_EVENTS_ITEM_COUNT_FLAGS = 1i32;
pub const FEICF_UNREAD_ITEM_COUNT_CHANGED: FEEDS_EVENTS_ITEM_COUNT_FLAGS = 2i32;
pub type FEEDS_EVENTS_MASK = i32;
pub const FEM_FOLDEREVENTS: FEEDS_EVENTS_MASK = 1i32;
pub const FEM_FEEDEVENTS: FEEDS_EVENTS_MASK = 2i32;
pub type FEEDS_EVENTS_SCOPE = i32;
pub const FES_ALL: FEEDS_EVENTS_SCOPE = 0i32;
pub const FES_SELF_ONLY: FEEDS_EVENTS_SCOPE = 1i32;
pub const FES_SELF_AND_CHILDREN_ONLY: FEEDS_EVENTS_SCOPE = 2i32;
pub type FEEDS_SYNC_SETTING = i32;
pub const FSS_DEFAULT: FEEDS_SYNC_SETTING = 0i32;
pub const FSS_INTERVAL: FEEDS_SYNC_SETTING = 1i32;
pub const FSS_MANUAL: FEEDS_SYNC_SETTING = 2i32;
pub const FSS_SUGGESTED: FEEDS_SYNC_SETTING = 3i32;
pub type FEEDS_XML_FILTER_FLAGS = i32;
pub const FXFF_ALL: FEEDS_XML_FILTER_FLAGS = 0i32;
pub const FXFF_UNREAD: FEEDS_XML_FILTER_FLAGS = 1i32;
pub const FXFF_READ: FEEDS_XML_FILTER_FLAGS = 2i32;
pub type FEEDS_XML_INCLUDE_FLAGS = i32;
pub const FXIF_NONE: FEEDS_XML_INCLUDE_FLAGS = 0i32;
pub const FXIF_CF_EXTENSIONS: FEEDS_XML_INCLUDE_FLAGS = 1i32;
pub type FEEDS_XML_SORT_ORDER = i32;
pub const FXSO_NONE: FEEDS_XML_SORT_ORDER = 0i32;
pub const FXSO_ASCENDING: FEEDS_XML_SORT_ORDER = 1i32;
pub const FXSO_DESCENDING: FEEDS_XML_SORT_ORDER = 2i32;
pub type FEEDS_XML_SORT_PROPERTY = i32;
pub const FXSP_NONE: FEEDS_XML_SORT_PROPERTY = 0i32;
pub const FXSP_PUBDATE: FEEDS_XML_SORT_PROPERTY = 1i32;
pub const FXSP_DOWNLOADTIME: FEEDS_XML_SORT_PROPERTY = 2i32;
pub const FeedFolderWatcher: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 672137709,
data2: 30565,
data3: 19632,
data4: [132, 175, 233, 179, 135, 175, 1, 255],
};
pub const FeedWatcher: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 413561723,
data2: 62515,
data3: 18055,
data4: [137, 188, 161, 180, 223, 185, 241, 35],
};
pub const FeedsManager: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 4209726660,
data2: 63087,
data3: 18438,
data4: [131, 160, 128, 82, 153, 245, 227, 173],
};
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 const IOCTL_WMP_DEVICE_CAN_SYNC: u32 = 844123479u32;
pub const IOCTL_WMP_METADATA_ROUND_TRIP: u32 = 827346263u32;
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 const PLUGIN_FLAGS_ACCEPTSMEDIA: u32 = 268435456u32;
pub const PLUGIN_FLAGS_ACCEPTSPLAYLISTS: u32 = 134217728u32;
pub const PLUGIN_FLAGS_HASPRESETS: u32 = 67108864u32;
pub const PLUGIN_FLAGS_HASPROPERTYPAGE: u32 = 2147483648u32;
pub const PLUGIN_FLAGS_HIDDEN: u32 = 33554432u32;
pub const PLUGIN_FLAGS_INSTALLAUTORUN: u32 = 1073741824u32;
pub const PLUGIN_FLAGS_LAUNCHPROPERTYPAGE: u32 = 536870912u32;
pub const PLUGIN_TYPE_BACKGROUND: u32 = 1u32;
pub const PLUGIN_TYPE_DISPLAYAREA: u32 = 3u32;
pub const PLUGIN_TYPE_METADATAAREA: u32 = 5u32;
pub const PLUGIN_TYPE_SEPARATEWINDOW: u32 = 2u32;
pub const PLUGIN_TYPE_SETTINGSAREA: u32 = 4u32;
pub type PlayerState = i32;
pub const stop_state: PlayerState = 0i32;
pub const pause_state: PlayerState = 1i32;
pub const play_state: PlayerState = 2i32;
pub const SA_BUFFER_SIZE: u32 = 1024u32;
pub const SUBSCRIPTION_CAP_ALLOWCDBURN: u32 = 2u32;
pub const SUBSCRIPTION_CAP_ALLOWPDATRANSFER: u32 = 4u32;
pub const SUBSCRIPTION_CAP_ALLOWPLAY: u32 = 1u32;
pub const SUBSCRIPTION_CAP_ALTLOGIN: u32 = 128u32;
pub const SUBSCRIPTION_CAP_BACKGROUNDPROCESSING: u32 = 8u32;
pub const SUBSCRIPTION_CAP_DEVICEAVAILABLE: u32 = 16u32;
pub const SUBSCRIPTION_CAP_IS_CONTENTPARTNER: u32 = 64u32;
pub const SUBSCRIPTION_CAP_PREPAREFORSYNC: u32 = 32u32;
pub const SUBSCRIPTION_CAP_UILESSMODE_ALLOWPLAY: u32 = 256u32;
pub const SUBSCRIPTION_V1_CAPS: u32 = 15u32;
#[repr(C)]
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
}
}
pub type WMPAccountType = i32;
pub const wmpatBuyOnly: WMPAccountType = 1i32;
pub const wmpatSubscription: WMPAccountType = 2i32;
pub const wmpatJanus: WMPAccountType = 3i32;
pub type WMPBurnFormat = i32;
pub const wmpbfAudioCD: WMPBurnFormat = 0i32;
pub const wmpbfDataCD: WMPBurnFormat = 1i32;
pub type WMPBurnState = i32;
pub const wmpbsUnknown: WMPBurnState = 0i32;
pub const wmpbsBusy: WMPBurnState = 1i32;
pub const wmpbsReady: WMPBurnState = 2i32;
pub const wmpbsWaitingForDisc: WMPBurnState = 3i32;
pub const wmpbsRefreshStatusPending: WMPBurnState = 4i32;
pub const wmpbsPreparingToBurn: WMPBurnState = 5i32;
pub const wmpbsBurning: WMPBurnState = 6i32;
pub const wmpbsStopped: WMPBurnState = 7i32;
pub const wmpbsErasing: WMPBurnState = 8i32;
pub const wmpbsDownloading: WMPBurnState = 9i32;
pub const WMPCOREEVENT_BASE: u32 = 5000u32;
pub const WMPCOREEVENT_CDROM_BASE: u32 = 5700u32;
pub const WMPCOREEVENT_CONTENT_BASE: u32 = 5300u32;
pub const WMPCOREEVENT_CONTROL_BASE: u32 = 5100u32;
pub const WMPCOREEVENT_ERROR_BASE: u32 = 5500u32;
pub const WMPCOREEVENT_NETWORK_BASE: u32 = 5400u32;
pub const WMPCOREEVENT_PLAYLIST_BASE: u32 = 5800u32;
pub const WMPCOREEVENT_SEEK_BASE: u32 = 5200u32;
pub const WMPCOREEVENT_WARNING_BASE: u32 = 5600u32;
pub type WMPCallbackNotification = i32;
pub const wmpcnLoginStateChange: WMPCallbackNotification = 1i32;
pub const wmpcnAuthResult: WMPCallbackNotification = 2i32;
pub const wmpcnLicenseUpdated: WMPCallbackNotification = 3i32;
pub const wmpcnNewCatalogAvailable: WMPCallbackNotification = 4i32;
pub const wmpcnNewPluginAvailable: WMPCallbackNotification = 5i32;
pub const wmpcnDisableRadioSkipping: WMPCallbackNotification = 6i32;
#[repr(C)]
#[cfg(feature = "Win32_Foundation")]
pub struct WMPContextMenuInfo {
pub dwID: u32,
pub bstrMenuText: super::super::Foundation::BSTR,
pub bstrHelpText: super::super::Foundation::BSTR,
}
#[cfg(feature = "Win32_Foundation")]
impl ::core::marker::Copy for WMPContextMenuInfo {}
#[cfg(feature = "Win32_Foundation")]
impl ::core::clone::Clone for WMPContextMenuInfo {
fn clone(&self) -> Self {
*self
}
}
pub type WMPDeviceStatus = i32;
pub const wmpdsUnknown: WMPDeviceStatus = 0i32;
pub const wmpdsPartnershipExists: WMPDeviceStatus = 1i32;
pub const wmpdsPartnershipDeclined: WMPDeviceStatus = 2i32;
pub const wmpdsPartnershipAnother: WMPDeviceStatus = 3i32;
pub const wmpdsManualDevice: WMPDeviceStatus = 4i32;
pub const wmpdsNewDevice: WMPDeviceStatus = 5i32;
pub const wmpdsLast: WMPDeviceStatus = 6i32;
pub type WMPFolderScanState = i32;
pub const wmpfssUnknown: WMPFolderScanState = 0i32;
pub const wmpfssScanning: WMPFolderScanState = 1i32;
pub const wmpfssUpdating: WMPFolderScanState = 2i32;
pub const wmpfssStopped: WMPFolderScanState = 3i32;
pub const WMPGC_FLAGS_ALLOW_PREROLL: u32 = 1u32;
pub const WMPGC_FLAGS_DISABLE_PLUGINS: u32 = 8u32;
pub const WMPGC_FLAGS_IGNORE_AV_SYNC: u32 = 4u32;
pub const WMPGC_FLAGS_SUPPRESS_DIALOGS: u32 = 2u32;
pub const WMPGC_FLAGS_USE_CUSTOM_GRAPH: u32 = 16u32;
pub const WMPLib: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1811229264, data2: 14666, data3: 4563, data4: [177, 83, 0, 192, 79, 121, 250, 166] };
pub type WMPLibraryType = i32;
pub const wmpltUnknown: WMPLibraryType = 0i32;
pub const wmpltAll: WMPLibraryType = 1i32;
pub const wmpltLocal: WMPLibraryType = 2i32;
pub const wmpltRemote: WMPLibraryType = 3i32;
pub const wmpltDisc: WMPLibraryType = 4i32;
pub const wmpltPortableDevice: WMPLibraryType = 5i32;
pub const WMPOCXEVENT_BASE: u32 = 6500u32;
pub type WMPOpenState = i32;
pub const wmposUndefined: WMPOpenState = 0i32;
pub const wmposPlaylistChanging: WMPOpenState = 1i32;
pub const wmposPlaylistLocating: WMPOpenState = 2i32;
pub const wmposPlaylistConnecting: WMPOpenState = 3i32;
pub const wmposPlaylistLoading: WMPOpenState = 4i32;
pub const wmposPlaylistOpening: WMPOpenState = 5i32;
pub const wmposPlaylistOpenNoMedia: WMPOpenState = 6i32;
pub const wmposPlaylistChanged: WMPOpenState = 7i32;
pub const wmposMediaChanging: WMPOpenState = 8i32;
pub const wmposMediaLocating: WMPOpenState = 9i32;
pub const wmposMediaConnecting: WMPOpenState = 10i32;
pub const wmposMediaLoading: WMPOpenState = 11i32;
pub const wmposMediaOpening: WMPOpenState = 12i32;
pub const wmposMediaOpen: WMPOpenState = 13i32;
pub const wmposBeginCodecAcquisition: WMPOpenState = 14i32;
pub const wmposEndCodecAcquisition: WMPOpenState = 15i32;
pub const wmposBeginLicenseAcquisition: WMPOpenState = 16i32;
pub const wmposEndLicenseAcquisition: WMPOpenState = 17i32;
pub const wmposBeginIndividualization: WMPOpenState = 18i32;
pub const wmposEndIndividualization: WMPOpenState = 19i32;
pub const wmposMediaWaiting: WMPOpenState = 20i32;
pub const wmposOpeningUnknownURL: WMPOpenState = 21i32;
pub type WMPPartnerNotification = i32;
pub const wmpsnBackgroundProcessingBegin: WMPPartnerNotification = 1i32;
pub const wmpsnBackgroundProcessingEnd: WMPPartnerNotification = 2i32;
pub const wmpsnCatalogDownloadFailure: WMPPartnerNotification = 3i32;
pub const wmpsnCatalogDownloadComplete: WMPPartnerNotification = 4i32;
pub type WMPPlayState = i32;
pub const wmppsUndefined: WMPPlayState = 0i32;
pub const wmppsStopped: WMPPlayState = 1i32;
pub const wmppsPaused: WMPPlayState = 2i32;
pub const wmppsPlaying: WMPPlayState = 3i32;
pub const wmppsScanForward: WMPPlayState = 4i32;
pub const wmppsScanReverse: WMPPlayState = 5i32;
pub const wmppsBuffering: WMPPlayState = 6i32;
pub const wmppsWaiting: WMPPlayState = 7i32;
pub const wmppsMediaEnded: WMPPlayState = 8i32;
pub const wmppsTransitioning: WMPPlayState = 9i32;
pub const wmppsReady: WMPPlayState = 10i32;
pub const wmppsReconnecting: WMPPlayState = 11i32;
pub const wmppsLast: WMPPlayState = 12i32;
pub type WMPPlaylistChangeEventType = i32;
pub const wmplcUnknown: WMPPlaylistChangeEventType = 0i32;
pub const wmplcClear: WMPPlaylistChangeEventType = 1i32;
pub const wmplcInfoChange: WMPPlaylistChangeEventType = 2i32;
pub const wmplcMove: WMPPlaylistChangeEventType = 3i32;
pub const wmplcDelete: WMPPlaylistChangeEventType = 4i32;
pub const wmplcInsert: WMPPlaylistChangeEventType = 5i32;
pub const wmplcAppend: WMPPlaylistChangeEventType = 6i32;
pub const wmplcPrivate: WMPPlaylistChangeEventType = 7i32;
pub const wmplcNameChange: WMPPlaylistChangeEventType = 8i32;
pub const wmplcMorph: WMPPlaylistChangeEventType = 9i32;
pub const wmplcSort: WMPPlaylistChangeEventType = 10i32;
pub const wmplcLast: WMPPlaylistChangeEventType = 11i32;
pub type WMPPlugin_Caps = i32;
pub const WMPPlugin_Caps_CannotConvertFormats: WMPPlugin_Caps = 1i32;
pub const WMPRemoteMediaServices: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3744674931, data2: 11511, data3: 19426, data4: [144, 127, 154, 173, 86, 97, 54, 79] };
pub type WMPRipState = i32;
pub const wmprsUnknown: WMPRipState = 0i32;
pub const wmprsRipping: WMPRipState = 1i32;
pub const wmprsStopped: WMPRipState = 2i32;
pub type WMPServices_StreamState = i32;
pub const WMPServices_StreamState_Stop: WMPServices_StreamState = 0i32;
pub const WMPServices_StreamState_Pause: WMPServices_StreamState = 1i32;
pub const WMPServices_StreamState_Play: WMPServices_StreamState = 2i32;
pub type WMPStreamingType = i32;
pub const wmpstUnknown: WMPStreamingType = 0i32;
pub const wmpstMusic: WMPStreamingType = 1i32;
pub const wmpstVideo: WMPStreamingType = 2i32;
pub const wmpstRadio: WMPStreamingType = 3i32;
pub type WMPStringCollectionChangeEventType = i32;
pub const wmpsccetUnknown: WMPStringCollectionChangeEventType = 0i32;
pub const wmpsccetInsert: WMPStringCollectionChangeEventType = 1i32;
pub const wmpsccetChange: WMPStringCollectionChangeEventType = 2i32;
pub const wmpsccetDelete: WMPStringCollectionChangeEventType = 3i32;
pub const wmpsccetClear: WMPStringCollectionChangeEventType = 4i32;
pub const wmpsccetBeginUpdates: WMPStringCollectionChangeEventType = 5i32;
pub const wmpsccetEndUpdates: WMPStringCollectionChangeEventType = 6i32;
pub type WMPSubscriptionDownloadState = i32;
pub const wmpsdlsDownloading: WMPSubscriptionDownloadState = 0i32;
pub const wmpsdlsPaused: WMPSubscriptionDownloadState = 1i32;
pub const wmpsdlsProcessing: WMPSubscriptionDownloadState = 2i32;
pub const wmpsdlsCompleted: WMPSubscriptionDownloadState = 3i32;
pub const wmpsdlsCancelled: WMPSubscriptionDownloadState = 4i32;
pub type WMPSubscriptionServiceEvent = i32;
pub const wmpsseCurrentBegin: WMPSubscriptionServiceEvent = 1i32;
pub const wmpsseCurrentEnd: WMPSubscriptionServiceEvent = 2i32;
pub const wmpsseFullBegin: WMPSubscriptionServiceEvent = 3i32;
pub const wmpsseFullEnd: WMPSubscriptionServiceEvent = 4i32;
pub type WMPSyncState = i32;
pub const wmpssUnknown: WMPSyncState = 0i32;
pub const wmpssSynchronizing: WMPSyncState = 1i32;
pub const wmpssStopped: WMPSyncState = 2i32;
pub const wmpssEstimating: WMPSyncState = 3i32;
pub const wmpssLast: WMPSyncState = 4i32;
pub type WMPTaskType = i32;
pub const wmpttBrowse: WMPTaskType = 1i32;
pub const wmpttSync: WMPTaskType = 2i32;
pub const wmpttBurn: WMPTaskType = 3i32;
pub const wmpttCurrent: WMPTaskType = 4i32;
pub type WMPTemplateSize = i32;
pub const wmptsSmall: WMPTemplateSize = 0i32;
pub const wmptsMedium: WMPTemplateSize = 1i32;
pub const wmptsLarge: WMPTemplateSize = 2i32;
pub type WMPTransactionType = i32;
pub const wmpttNoTransaction: WMPTransactionType = 0i32;
pub const wmpttDownload: WMPTransactionType = 1i32;
pub const wmpttBuy: WMPTransactionType = 2i32;
pub const WMPUE_EC_USER: u32 = 33024u32;
pub const WMP_MDRT_FLAGS_UNREPORTED_ADDED_ITEMS: u32 = 2u32;
pub const WMP_MDRT_FLAGS_UNREPORTED_DELETED_ITEMS: u32 = 1u32;
pub const WMP_PLUGINTYPE_DSP: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1681177322, data2: 18772, data3: 18829, data4: [171, 213, 43, 7, 18, 62, 31, 4] };
pub const WMP_PLUGINTYPE_DSP_OUTOFPROC: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 4012487028,
data2: 49991,
data3: 17612,
data4: [154, 79, 35, 153, 17, 143, 243, 140],
};
pub const WMP_PLUGINTYPE_RENDERING: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2824160577, data2: 4445, data3: 16490, data4: [164, 199, 81, 17, 28, 51, 1, 131] };
#[repr(C, packed(1))]
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))]
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
}
}
pub const WMProfile_V40_100Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2409225688,
data2: 26244,
data3: 17771,
data4: [160, 163, 51, 225, 49, 104, 149, 240],
};
pub const WMProfile_V40_128Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2480782866, data2: 5084, data3: 20018, data4: [163, 94, 64, 55, 142, 52, 39, 154] };
pub const WMProfile_V40_16AMRadio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 256632863,
data2: 54653,
data3: 16865,
data4: [178, 227, 47, 173, 152, 107, 254, 194],
};
pub const WMProfile_V40_1MBVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3024628300,
data2: 52247,
data3: 19207,
data4: [169, 78, 152, 24, 213, 224, 241, 63],
};
pub const WMProfile_V40_250Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1410875843, data2: 37689, data3: 20347, data4: [154, 34, 177, 21, 64, 137, 78, 66] };
pub const WMProfile_V40_2856100MBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1511793158, data2: 56414, data3: 16774, data4: [190, 178, 76, 90, 153, 75, 19, 46] };
pub const WMProfile_V40_288FMRadioMono: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2141552584,
data2: 28324,
data3: 17989,
data4: [138, 191, 182, 229, 168, 248, 20, 161],
};
pub const WMProfile_V40_288FMRadioStereo: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 587002982, data2: 43584, data3: 17183, data4: [162, 137, 6, 208, 234, 26, 30, 64] };
pub const WMProfile_V40_288VideoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2892070701, data2: 27838, data3: 20100, data4: [142, 154, 206, 21, 26, 18, 163, 84] };
pub const WMProfile_V40_288VideoVoice: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3140207220,
data2: 3766,
data3: 19881,
data4: [181, 80, 236, 247, 242, 185, 148, 143],
};
pub const WMProfile_V40_288VideoWebServer: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2884825101,
data2: 54613,
data3: 18453,
data4: [148, 206, 130, 117, 243, 167, 11, 254],
};
pub const WMProfile_V40_3MBVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1429686976,
data2: 12443,
data3: 17302,
data4: [184, 143, 230, 226, 146, 17, 63, 40],
};
pub const WMProfile_V40_512Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1883508333,
data2: 50415,
data3: 20356,
data4: [140, 208, 213, 194, 134, 134, 231, 132],
};
pub const WMProfile_V40_56DialUpStereo: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3892473735, data2: 59653, data3: 17812, data4: [163, 199, 0, 208, 0, 65, 209, 217] };
pub const WMProfile_V40_56DialUpVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3793163195, data2: 25903, data3: 19883, data4: [153, 222, 113, 224, 68, 0, 39, 15] };
pub const WMProfile_V40_56DialUpVideoWebServer: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3075931920,
data2: 21007,
data3: 18249,
data4: [163, 153, 183, 128, 226, 252, 146, 80],
};
pub const WMProfile_V40_64Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1210102775,
data2: 52204,
data3: 16860,
data4: [147, 145, 120, 89, 135, 20, 200, 229],
};
pub const WMProfile_V40_6VoiceAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3574110090,
data2: 4512,
data3: 19733,
data4: [176, 218, 172, 220, 153, 212, 248, 144],
};
pub const WMProfile_V40_96Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 251268835, data2: 40548, data3: 16866, data4: [131, 127, 60, 0, 56, 243, 39, 186] };
pub const WMProfile_V40_DialUpMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4252977137, data2: 29350, data3: 17828, data4: [128, 240, 58, 236, 239, 195, 44, 7] };
pub const WMProfile_V40_IntranetMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2194486049, data2: 43338, data3: 20476, data4: [156, 43, 9, 44, 16, 202, 22, 231] };
pub const WMProfile_V70_100Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3656632626,
data2: 24233,
data3: 19565,
data4: [137, 180, 38, 134, 229, 21, 66, 110],
};
pub const WMProfile_V70_128Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3326932442,
data2: 57157,
data3: 16595,
data4: [128, 39, 222, 105, 141, 104, 220, 102],
};
pub const WMProfile_V70_1500FilmContentVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4138071775, data2: 60991, data3: 17228, data4: [164, 51, 82, 60, 229, 95, 81, 107] };
pub const WMProfile_V70_1500Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 193533514, data2: 21648, data3: 18054, data4: [158, 55, 90, 128, 136, 78, 81, 70] };
pub const WMProfile_V70_150VideoPDA: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 256321895, data2: 58310, data3: 18327, data4: [150, 148, 240, 48, 76, 94, 47, 23] };
pub const WMProfile_V70_2000Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2862088484, data2: 48912, data3: 20047, data4: [154, 253, 67, 41, 167, 57, 92, 255] };
pub const WMProfile_V70_225VideoPDA: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4116620659, data2: 19458, data3: 17077, data4: [144, 38, 168, 38, 12, 67, 138, 159] };
pub const WMProfile_V70_256Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2951125818, data2: 16447, data3: 18971, data4: [128, 7, 14, 33, 207, 179, 223, 132] };
pub const WMProfile_V70_2856100MBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 132086309, data2: 16354, data3: 19035, data4: [139, 30, 52, 139, 7, 33, 202, 112] };
pub const WMProfile_V70_288FMRadioMono: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3222448179,
data2: 41019,
data3: 17573,
data4: [150, 220, 237, 149, 204, 101, 88, 45],
};
pub const WMProfile_V70_288FMRadioStereo: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3916261321, data2: 6713, data3: 19908, data4: [185, 0, 177, 24, 77, 200, 54, 32] };
pub const WMProfile_V70_288VideoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1488691438, data2: 35178, data3: 18760, data4: [153, 83, 133, 183, 54, 248, 57, 71] };
pub const WMProfile_V70_288VideoVoice: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3109221262, data2: 32188, data3: 17715, data4: [169, 202, 176, 11, 28, 110, 152, 0] };
pub const WMProfile_V70_288VideoWebServer: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1889742379, data2: 58079, data3: 20157, data4: [145, 5, 217, 202, 25, 74, 45, 80] };
pub const WMProfile_V70_384Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 4090781627,
data2: 34690,
data3: 17631,
data4: [151, 198, 134, 120, 226, 249, 177, 61],
};
pub const WMProfile_V70_56DialUpStereo: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1733224295, data2: 2377, data3: 20396, data4: [135, 94, 244, 201, 194, 146, 1, 59] };
pub const WMProfile_V70_56VideoWebServer: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3740900928,
data2: 22460,
data3: 19123,
data4: [178, 209, 182, 227, 202, 246, 66, 87],
};
pub const WMProfile_V70_64Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2996633542,
data2: 61745,
data3: 16859,
data4: [181, 232, 153, 216, 176, 185, 69, 244],
};
pub const WMProfile_V70_64AudioISDN: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2447287384, data2: 40288, data3: 16914, data4: [156, 89, 212, 9, 25, 201, 57, 228] };
pub const WMProfile_V70_64VideoISDN: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3266815977, data2: 31630, data3: 18834, data4: [161, 161, 6, 130, 23, 163, 179, 17] };
pub const WMProfile_V70_6VoiceAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3938099135,
data2: 46671,
data3: 18867,
data4: [170, 12, 115, 251, 221, 21, 10, 208],
};
pub const WMProfile_V70_700FilmContentVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2054453536,
data2: 9289,
data3: 19830,
data4: [153, 203, 253, 176, 201, 4, 132, 212],
};
pub const WMProfile_V70_768Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 52882358, data2: 63342, data3: 18788, data4: [176, 219, 231, 41, 151, 141, 53, 238] };
pub const WMProfile_V70_96Audio: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2849290265, data2: 5836, data3: 19033, data4: [159, 55, 105, 61, 187, 3, 2, 214] };
pub const WMProfile_V70_DialUpMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1528227659, data2: 16488, data3: 17845, data4: [184, 14, 123, 248, 200, 13, 44, 47] };
pub const WMProfile_V70_IntranetMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 72909020, data2: 13494, data3: 19625, data4: [163, 38, 115, 85, 126, 209, 67, 243] };
pub const WMProfile_V80_100768VideoMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1541102094,
data2: 38814,
data3: 18387,
data4: [149, 150, 115, 179, 134, 57, 42, 85],
};
pub const WMProfile_V80_100Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2732785844,
data2: 49876,
data3: 20416,
data4: [181, 221, 236, 189, 148, 141, 192, 223],
};
pub const WMProfile_V80_128StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1081840720,
data2: 35804,
data3: 20197,
data4: [136, 184, 111, 82, 123, 217, 65, 242],
};
pub const WMProfile_V80_1400NTSCVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2468158446,
data2: 24954,
data3: 19405,
data4: [153, 5, 204, 208, 120, 102, 131, 238],
};
pub const WMProfile_V80_150VideoPDA: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 2934009338, data2: 11284, data3: 18991, data4: [173, 63, 163, 3, 64, 49, 120, 79] };
pub const WMProfile_V80_255VideoPDA: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 4276993247, data2: 16300, data3: 19603, data4: [172, 13, 71, 148, 30, 199, 44, 11] };
pub const WMProfile_V80_256Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3150402816, data2: 13266, data3: 17510, data4: [184, 107, 18, 43, 32, 28, 201, 174] };
pub const WMProfile_V80_288100VideoMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3631361129, data2: 9241, data3: 19254, data4: [180, 224, 110, 23, 182, 5, 100, 229] };
pub const WMProfile_V80_28856VideoMBR: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3597213892,
data2: 49695,
data3: 20168,
data4: [160, 180, 149, 207, 43, 213, 127, 196],
};
pub const WMProfile_V80_288MonoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2124616301,
data2: 57786,
data3: 18198,
data4: [137, 175, 246, 92, 238, 12, 12, 103],
};
pub const WMProfile_V80_288StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2118953820,
data2: 13788,
data3: 17851,
data4: [167, 192, 25, 178, 128, 112, 208, 204],
};
pub const WMProfile_V80_288Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1039562969,
data2: 4946,
data3: 16774,
data4: [187, 248, 116, 240, 193, 155, 106, 226],
};
pub const WMProfile_V80_288VideoOnly: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2353378503,
data2: 19179,
data3: 20344,
data4: [165, 236, 136, 66, 11, 157, 173, 239],
};
pub const WMProfile_V80_32StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1620082591,
data2: 45906,
data3: 18405,
data4: [178, 16, 14, 241, 244, 126, 159, 157],
};
pub const WMProfile_V80_384PALVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 2452080274,
data2: 44642,
data3: 20338,
data4: [167, 234, 115, 96, 98, 208, 226, 30],
};
pub const WMProfile_V80_384Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 699403307, data2: 2473, data3: 18621, data4: [173, 9, 205, 174, 17, 125, 29, 167] };
pub const WMProfile_V80_48StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1591765989,
data2: 18731,
data3: 18442,
data4: [138, 143, 18, 243, 115, 236, 249, 212],
};
pub const WMProfile_V80_56Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 625904278, data2: 9746, data3: 16476, data4: [128, 57, 240, 191, 114, 92, 237, 125] };
pub const WMProfile_V80_56VideoOnly: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 1848273237,
data2: 33247,
data3: 18755,
data4: [186, 80, 104, 169, 134, 167, 8, 246],
};
pub const WMProfile_V80_64StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 163273668, data2: 12662, data3: 17791, data4: [141, 214, 60, 217, 25, 18, 62, 45] };
pub const WMProfile_V80_700NTSCVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 3368196191,
data2: 58841,
data3: 17720,
data4: [158, 35, 155, 33, 191, 120, 247, 69],
};
pub const WMProfile_V80_700PALVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 3962145097, data2: 25499, data3: 17890, data4: [150, 253, 74, 179, 45, 89, 25, 194] };
pub const WMProfile_V80_768Video: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1959792898, data2: 59162, data3: 18464, data4: [143, 13, 19, 210, 236, 30, 72, 114] };
pub const WMProfile_V80_96StereoAudio: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 533207344, data2: 25074, data3: 17263, data4: [157, 51, 52, 159, 42, 28, 15, 16] };
pub const WMProfile_V80_BESTVBRVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 75774394, data2: 12444, data3: 17422, data4: [156, 180, 61, 204, 163, 117, 100, 35] };
pub const WMProfile_V80_FAIRVBRVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 890284130, data2: 22608, data3: 18566, data4: [131, 95, 215, 142, 198, 166, 64, 66] };
pub const WMProfile_V80_HIGHVBRVideo: ::windows_sys::core::GUID = ::windows_sys::core::GUID {
data1: 252762579,
data2: 15108,
data3: 20400,
data4: [163, 211, 136, 212, 172, 133, 74, 204],
};
pub const WindowsMediaPlayer: ::windows_sys::core::GUID = ::windows_sys::core::GUID { data1: 1811229266, data2: 14666, data3: 4563, data4: [177, 83, 0, 192, 79, 121, 250, 166] };
pub type _WMPOCXEvents = *mut ::core::ffi::c_void;
pub const g_szAllAuthors: &'static str = "AllAuthors";
pub const g_szAllCPAlbumIDs: &'static str = "AllCPAlbumIDs";
pub const g_szAllCPAlbumSubGenreIDs: &'static str = "AllCPAlbumSubGenreIDs";
pub const g_szAllCPArtistIDs: &'static str = "AllCPArtistIDs";
pub const g_szAllCPGenreIDs: &'static str = "AllCPGenreIDs";
pub const g_szAllCPListIDs: &'static str = "AllCPListIDs";
pub const g_szAllCPRadioIDs: &'static str = "AllCPRadioIDs";
pub const g_szAllCPTrackIDs: &'static str = "AllCPTrackIDs";
pub const g_szAllReleaseDateYears: &'static str = "AllReleaseDateYears";
pub const g_szAllUserEffectiveRatingStarss: &'static str = "AllUserEffectiveRatingStarss";
pub const g_szAllWMParentalRatings: &'static str = "AllWMParentalRatings";
pub const g_szAuthor: &'static str = "Author";
pub const g_szCPAlbumID: &'static str = "CPAlbumID";
pub const g_szCPAlbumSubGenreID: &'static str = "CPAlbumSubGenreID";
pub const g_szCPArtistID: &'static str = "CPArtistID";
pub const g_szCPGenreID: &'static str = "CPGenreID";
pub const g_szCPListID: &'static str = "CPListID";
pub const g_szCPRadioID: &'static str = "CPRadioID";
pub const g_szCPTrackID: &'static str = "CPTrackID";
pub const g_szContentPartnerInfo_AccountBalance: &'static str = "AccountBalance";
pub const g_szContentPartnerInfo_AccountType: &'static str = "AccountType";
pub const g_szContentPartnerInfo_HasCachedCredentials: &'static str = "HasCachedCredentials";
pub const g_szContentPartnerInfo_LicenseRefreshAdvanceWarning: &'static str = "LicenseRefreshAdvanceWarning";
pub const g_szContentPartnerInfo_LoginState: &'static str = "LoginState";
pub const g_szContentPartnerInfo_MaximumTrackPurchasePerPurchase: &'static str = "MaximumNumberOfTracksPerPurchase";
pub const g_szContentPartnerInfo_MediaPlayerAccountType: &'static str = "MediaPlayerAccountType";
pub const g_szContentPartnerInfo_PurchasedTrackRequiresReDownload: &'static str = "PurchasedTrackRequiresReDownload";
pub const g_szContentPartnerInfo_UserName: &'static str = "UserName";
pub const g_szContentPrice_CannotBuy: &'static str = "PriceCannotBuy";
pub const g_szContentPrice_Free: &'static str = "PriceFree";
pub const g_szContentPrice_Unknown: &'static str = "PriceUnknown";
pub const g_szFlyoutMenu: &'static str = "FlyoutMenu";
pub const g_szItemInfo_ALTLoginCaption: &'static str = "ALTLoginCaption";
pub const g_szItemInfo_ALTLoginURL: &'static str = "ALTLoginURL";
pub const g_szItemInfo_AlbumArtURL: &'static str = "AlbumArt";
pub const g_szItemInfo_ArtistArtURL: &'static str = "ArtistArt";
pub const g_szItemInfo_AuthenticationSuccessURL: &'static str = "AuthenticationSuccessURL";
pub const g_szItemInfo_CreateAccountURL: &'static str = "CreateAccount";
pub const g_szItemInfo_ErrorDescription: &'static str = "CPErrorDescription";
pub const g_szItemInfo_ErrorURL: &'static str = "CPErrorURL";
pub const g_szItemInfo_ErrorURLLinkText: &'static str = "CPErrorURLLinkText";
pub const g_szItemInfo_ForgetPasswordURL: &'static str = "ForgotPassword";
pub const g_szItemInfo_GenreArtURL: &'static str = "GenreArt";
pub const g_szItemInfo_HTMLViewURL: &'static str = "HTMLViewURL";
pub const g_szItemInfo_ListArtURL: &'static str = "ListArt";
pub const g_szItemInfo_LoginFailureURL: &'static str = "LoginFailureURL";
pub const g_szItemInfo_PopupCaption: &'static str = "PopupCaption";
pub const g_szItemInfo_PopupURL: &'static str = "Popup";
pub const g_szItemInfo_RadioArtURL: &'static str = "RadioArt";
pub const g_szItemInfo_SubGenreArtURL: &'static str = "SubGenreArt";
pub const g_szItemInfo_TreeListIconURL: &'static str = "CPListIDIcon";
pub const g_szMediaPlayerTask_Browse: &'static str = "Browse";
pub const g_szMediaPlayerTask_Burn: &'static str = "Burn";
pub const g_szMediaPlayerTask_Sync: &'static str = "Sync";
pub const g_szOnlineStore: &'static str = "OnlineStore";
pub const g_szRefreshLicenseBurn: &'static str = "RefreshForBurn";
pub const g_szRefreshLicensePlay: &'static str = "RefreshForPlay";
pub const g_szRefreshLicenseSync: &'static str = "RefreshForSync";
pub const g_szReleaseDateYear: &'static str = "ReleaseDateYear";
pub const g_szRootLocation: &'static str = "RootLocation";
pub const g_szStationEvent_Complete: &'static str = "TrackComplete";
pub const g_szStationEvent_Skipped: &'static str = "TrackSkipped";
pub const g_szStationEvent_Started: &'static str = "TrackStarted";
pub const g_szUnknownLocation: &'static str = "UnknownLocation";
pub const g_szUserEffectiveRatingStars: &'static str = "UserEffectiveRatingStars";
pub const g_szUserPlaylist: &'static str = "UserPlaylist";
pub const g_szVerifyPermissionSync: &'static str = "VerifyPermissionSync";
pub const g_szVideoRecent: &'static str = "VideoRecent";
pub const g_szVideoRoot: &'static str = "VideoRoot";
pub const g_szViewMode_Details: &'static str = "ViewModeDetails";
pub const g_szViewMode_Icon: &'static str = "ViewModeIcon";
pub const g_szViewMode_OrderedList: &'static str = "ViewModeOrderedList";
pub const g_szViewMode_Report: &'static str = "ViewModeReport";
pub const g_szViewMode_Tile: &'static str = "ViewModeTile";
pub const g_szWMParentalRating: &'static str = "WMParentalRating";
pub const kfltTimedLevelMaximumFrequency: f32 = 22050f32;
pub const kfltTimedLevelMinimumFrequency: f32 = 20f32;
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::sync::Arc;
use common_config::InnerConfig;
use common_exception::ErrorCode;
use common_exception::Result;
use common_meta_app::schema::DatabaseInfo;
use dashmap::DashMap;
use crate::databases::default::DefaultDatabase;
use crate::databases::share::ShareDatabase;
use crate::databases::Database;
use crate::databases::DatabaseContext;
pub trait DatabaseCreator: Send + Sync {
fn try_create(&self, ctx: DatabaseContext, db_info: DatabaseInfo) -> Result<Box<dyn Database>>;
}
impl<T> DatabaseCreator for T
where
T: Fn(DatabaseContext, DatabaseInfo) -> Result<Box<dyn Database>>,
T: Send + Sync,
{
fn try_create(&self, ctx: DatabaseContext, db_info: DatabaseInfo) -> Result<Box<dyn Database>> {
self(ctx, db_info)
}
}
#[derive(Default)]
pub struct DatabaseFactory {
creators: DashMap<String, Arc<dyn DatabaseCreator>>,
}
impl DatabaseFactory {
pub fn create(_: InnerConfig) -> Self {
let creators: DashMap<String, Arc<dyn DatabaseCreator>> = DashMap::new();
creators.insert(
DefaultDatabase::NAME.to_string(),
Arc::new(DefaultDatabase::try_create),
);
creators.insert(
ShareDatabase::NAME.to_string(),
Arc::new(ShareDatabase::try_create),
);
DatabaseFactory { creators }
}
pub fn get_database(
&self,
ctx: DatabaseContext,
db_info: &DatabaseInfo,
) -> Result<Arc<dyn Database>> {
let db_engine = &db_info.engine();
let engine = if db_engine.is_empty() {
"DEFAULT".to_string()
} else {
db_engine.to_uppercase()
};
let factory = self.creators.get(&engine).ok_or_else(|| {
ErrorCode::UnknownDatabaseEngine(format!("Unknown database engine {}", engine))
})?;
let db: Arc<dyn Database> = factory.try_create(ctx, db_info.clone())?.into();
Ok(db)
}
}
|
#[test]
fn mem_transmute() {
fn inc_fn(x: u32) -> u32 {
x + 1
};
let fn_ptr = inc_fn as *const u32;
let func: fn(i32) -> i32 = unsafe { std::mem::transmute(fn_ptr) };
assert_eq!(11, func(10));
}
#[test]
fn mem_maybe_uninitialized() {
let mut s: String = unsafe { std::mem::uninitialized() };
unsafe {
std::ptr::write(&mut s, "ABCD".to_string());
}
assert_eq!("ABCD", s.as_str());
std::mem::forget(s);
}
|
use rand::Rng;
use crate::cell::Cell;
use crate::grid::Grid;
use crate::row::Row;
use crate::automaton::Automaton;
use crate::renderer::Renderer;
pub struct Seeds {
grid: Grid,
}
impl Seeds {
pub fn new(n_rows: usize, n_cols: usize) -> Seeds {
let mut rows = vec![
Row {
cells: vec![Cell { value: 0 }; n_cols]
};
n_rows
];
// Blinker
// rows[4].cells[4].value = 1;
// rows[4].cells[5].value = 1;
// rows[4].cells[6].value = 1;
// Glider
// rows[4].cells[4].value = 1;
// rows[4].cells[5].value = 1;
// rows[4].cells[6].value = 1;
// rows[3].cells[6].value = 1;
// rows[2].cells[5].value = 1;
// Random
// let mut rng = rand::thread_rng();
// for row in rows.iter_mut() {
// for col in row.cells.iter_mut() {
// col.value = rng.gen();
// }
// }
rows[n_rows / 2].cells[n_cols / 2 - 1].value = 1;
rows[n_rows / 2].cells[n_cols / 2].value = 1;
rows[n_rows / 2].cells[n_cols / 2 + 1].value = 1;
rows[n_rows / 2 - 1].cells[n_cols / 2 - 1].value = 1;
rows[n_rows / 2 - 1].cells[n_cols / 2].value = 1;
rows[n_rows / 2 - 1].cells[n_cols / 2 + 1].value = 1;
rows[n_rows / 2 - 2].cells[n_cols / 2 - 1].value = 1;
rows[n_rows / 2 - 2].cells[n_cols / 2].value = 1;
rows[n_rows / 2 - 2].cells[n_cols / 2 + 1].value = 1;
rows[n_rows / 2 - 3].cells[n_cols / 2 - 1].value = 1;
rows[n_rows / 2 - 3].cells[n_cols / 2].value = 1;
rows[n_rows / 2 - 3].cells[n_cols / 2 + 1].value = 1;
Seeds {
grid: Grid { rows },
}
}
fn next_iteration(grid: &Grid) -> Grid {
let mut new_rows = Vec::new();
for row in grid.rows.iter().enumerate() {
let mut new_row = Row { cells: Vec::new() };
for col in row.1.cells.iter().enumerate() {
// A cell turns on if it was off and has exactly two neighbors
// All other cells turn off.
let mut living_neighbours = 0;
for dir in 0..=7 {
let (x, y) = grid.neib(col.0, row.0, dir).unwrap();
if grid.rows[y].cells[x].value == 1 {
living_neighbours += 1;
}
}
let is_alive = col.1.value;
match living_neighbours {
0..=1 => new_row.cells.push(Cell { value: 0 }),
2 => new_row.cells.push(Cell { value: (is_alive + 1) % 2 }),
3..=8 => new_row.cells.push(Cell { value: 0 }),
_ => {}
}
}
new_rows.push(new_row);
}
Grid { rows: new_rows }
}
}
impl Automaton for Seeds {
fn next(&mut self) {
self.grid = Seeds::next_iteration(&self.grid);
}
fn render(&self, renderer: &mut dyn Renderer) {
renderer.render_grid(&self.grid);
}
}
|
use layout::{Entry, StreamVec, FlexMeasure, Item};
use output::{Output};
use num::Zero;
//use layout::style::{Style};
use units::Length;
use std::fmt::{self, Debug};
#[derive(Copy, Clone, Debug, Default)]
struct LineBreak {
prev: usize, // index to previous line-break
path: u64, // one bit for each branch taken (1) or not (0)
factor: f32,
score: f32,
height: f32,
}
#[derive(Copy, Clone, Debug, Default)]
struct ColumnBreak {
prev: usize, // index to previous column-break
score: f32,
}
#[derive(Copy, Clone, Debug, Default)]
struct Break {
line: LineBreak,
column: Option<ColumnBreak>
}
pub struct ParagraphLayout<'o, O: Output + 'o> {
items: &'o [Entry<O>],
nodes: Vec<Option<LineBreak>>,
width: Length,
last: usize
}
pub struct ColumnLayout<'o, O: Output + 'o> {
para: ParagraphLayout<'o, O>,
nodes_col: Vec<Option<ColumnBreak>>,
height: Length
}
impl<'o, O: Output + 'o> Debug for ColumnLayout<'o, O> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ColumnLayout")
}
}
impl<'o, O: Output + 'o> Debug for ParagraphLayout<'o, O> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "ParagraphLayout")
}
}
struct Context {
measure: FlexMeasure,
path: u64, // one bit for each branch on this line
begin: usize, // begin of line or branch
pos: usize, // calculation starts here
score: f32, // score at pos
branches: u8, // number of branches so far (<= 64)
punctuaton: FlexMeasure
}
impl Context {
fn new(start: usize, score: f32) -> Context {
Context {
measure: FlexMeasure::zero(),
path: 0,
begin: start,
pos: start,
branches: 0,
score: score,
punctuaton: FlexMeasure::zero()
}
}
fn add_word(&mut self, measure: FlexMeasure) {
self.measure += self.punctuaton + measure;
self.punctuaton = FlexMeasure::zero();
}
fn add_punctuation(&mut self, measure: FlexMeasure) {
self.punctuaton = measure;
}
fn line(&self) -> FlexMeasure {
self.measure + self.punctuaton * 0.5
}
fn fill(&mut self, width: Length) {
self.measure = self.line();
self.measure.extend(width);
self.punctuaton = FlexMeasure::zero();
}
}
impl<'o, O: Output+Debug> ParagraphLayout<'o, O> {
pub fn new(items: &'o [Entry<O>], width: Length) -> ParagraphLayout<'o, O> {
let limit = items.len();
let mut nodes = vec![None; limit+1];
nodes[0] = Some(LineBreak::default());
let mut layout = ParagraphLayout {
nodes,
items,
width,
last: 0
};
layout.run();
layout
}
fn run(&mut self) {
let mut last = 0;
for start in 0 .. self.items.len() {
match self.nodes[start] {
Some(b) => {
last = self.complete_line(
start,
Context::new(start, b.score)
);
},
None => {}
}
}
if self.nodes[last].is_none() {
for i in 0 .. last {
println!("{:3} {:?}", i, self.items[i]);
if let Some(b) = self.nodes[i] {
println!(" {:?}", b);
}
}
}
self.last = last;
}
fn complete_line(&mut self, start: usize, mut c: Context) -> usize {
let mut last = c.begin;
while c.pos < self.items.len() {
let n = c.pos;
match self.items[n] {
Entry::Word(ref w) => c.add_word(O::measure_word(w, self.width)),
Entry::Punctuation(ref w) => c.add_punctuation(O::measure_word(w, self.width)),
Entry::Space(breaking, s) => {
if breaking {
// breaking case:
// width is not added yet!
if self.maybe_update(&c, n+1) {
last = n+1;
}
}
// add width now.
c.measure += s;
}
Entry::Linebreak(fill) => {
if fill {
c.fill(self.width);
}
if self.maybe_update(&c, n+1) {
last = n+1;
}
break;
},
Entry::BranchEntry(len) => {
// b
let b_last = self.complete_line(
start,
Context {
pos: n + 1,
path: c.path | (1 << c.branches),
branches: c.branches + 1,
.. c
}
);
if b_last > last {
last = b_last;
}
// a follows here
c.pos += len;
c.branches += 1;
},
Entry::BranchExit(skip) => {
c.pos += skip;
}
_ => {}
}
if c.measure.shrink > self.width {
break; // too full
}
c.pos += 1;
}
last
}
fn maybe_update(&mut self, c: &Context, n: usize) -> bool {
if let Some(factor) = c.line().factor(self.width) {
let break_score = c.score - factor * factor;
let break_point = LineBreak {
prev: c.begin,
path: c.path,
factor: factor,
score: break_score,
height: c.measure.height
};
self.nodes[n] = Some(match self.nodes[n] {
Some(line) if break_score <= line.score => line,
_ => break_point
});
true
} else {
false
}
}
pub fn lines<'l>(&'l self) -> Column<'l, 'o, O> {
Column::new(0, self.last, self)
}
}
impl<'a, O: Output+Debug> ColumnLayout<'a, O> {
pub fn new(items: &'a StreamVec<O>, width: Length, height: Length) -> ColumnLayout<'a, O> {
let limit = items.len();
let mut nodes = vec![None; limit+1];
let mut nodes_col = vec![None; limit+1];
nodes[0] = Some(LineBreak::default());
nodes_col[0] = Some(ColumnBreak::default());
let mut layout = ColumnLayout {
para: ParagraphLayout {
nodes,
items,
width,
last: 0
},
nodes_col,
height,
};
layout.run();
layout
}
pub fn columns<'l>(&'l self) -> Columns<'l, 'a, O> {
Columns::new(self)
}
fn run(&mut self) {
let mut last = 0;
for start in 0 .. self.para.items.len() {
match self.para.nodes[start] {
Some(b) => {
last = self.para.complete_line(
start,
Context::new(start, b.score)
);
self.compute_column(start, false);
},
None => {}
}
}
self.compute_column(last, true);
if self.nodes_col[last].is_none() {
for i in 0 .. last {
println!("{:3} {:?}", i, self.para.items[i]);
if let Some(b) = self.para.nodes[i] {
println!(" {:?}", b);
}
if let Some(l) = self.nodes_col[i] {
println!(" {:?}", l);
}
}
}
self.para.last = last;
}
fn num_lines_penalty(&self, n: usize) -> f32 {
match n {
1 => -20.0,
2 => -2.0,
_ => 0.0
}
}
fn fill_penalty(&self, fill: Length) -> f32 {
-10.0 * (self.height - fill) / self.height
}
fn compute_column(&mut self, n: usize, is_last: bool) -> bool {
// measure:
let mut num_lines_before_end = 0; // - lines before the break; reset between paragraphs
let mut num_lines_at_last_break = 0; // - lines after the previous break; count until the last paragraph starts
let mut is_last_paragraph = true;
let mut height = 0.0;
let mut last = n;
let mut found = false;
loop {
let last_node = self.para.nodes[last].unwrap();
if last > 0 {
match self.para.items[last-1] {
Entry::Linebreak(_) => {
is_last_paragraph = false;
num_lines_before_end = 0;
},
Entry::Space { .. } => {
num_lines_before_end += 1;
if is_last_paragraph {
num_lines_at_last_break += 1;
}
}
ref e => panic!("found: {:?}", e)
}
height += last_node.height;
if height > self.height {
break;
}
}
if let Some(column) = self.nodes_col[last] {
let mut score = column.score
+ self.num_lines_penalty(num_lines_at_last_break)
+ self.num_lines_penalty(num_lines_before_end);
if !is_last {
score += self.fill_penalty(height);
}
match self.nodes_col[n] {
Some(column) if column.score > score => {},
_ => {
self.nodes_col[n] = Some(ColumnBreak {
prev: last,
score: score
});
found = true;
}
}
}
if last == 0 {
break;
}
last = last_node.prev;
}
found
}
}
#[derive(Debug)]
pub struct Columns<'l, 'o: 'l, O: Output + 'o> {
layout: &'l ColumnLayout<'o, O>,
columns: Vec<usize>
}
impl<'l, 'o: 'l, O: Output + 'o> Columns<'l, 'o, O> {
fn new(layout: &'l ColumnLayout<'o, O>) -> Self {
let mut columns = Vec::new();
let mut last = layout.para.last;
while last > 0 {
columns.push(last);
last = layout.nodes_col[last].unwrap().prev;
}
Columns {
layout: layout,
columns: columns
}
}
}
impl<'l, 'o: 'l, O: Output + 'o> Iterator for Columns<'l, 'o, O> {
type Item = Column<'l, 'o, O>;
fn next(&mut self) -> Option<Self::Item> {
self.columns.pop().map(|last| Column::new(
self.layout.nodes_col[last].unwrap().prev,
last,
&self.layout.para
))
}
}
#[derive(Debug)]
pub struct Column<'l, 'o: 'l, O: Output + 'o> {
lines: Vec<usize>, // points to the end of each line
layout: &'l ParagraphLayout<'o, O>,
y: Length
}
impl<'l, 'o: 'l, O: Output + 'o> Column<'l, 'o, O> {
fn new(first: usize, mut last: usize, layout: &'l ParagraphLayout<'o, O>) -> Self {
let mut lines = Vec::new();
while last > first {
lines.push(last);
last = layout.nodes[last].unwrap().prev;
}
Column {
lines: lines,
layout: layout,
y: 0.0
}
}
}
impl<'l, 'o: 'l, O: Output + 'o> Iterator for Column<'l, 'o, O> {
type Item = (Length, Line<'l, 'o, O>);
fn next(&mut self) -> Option<Self::Item> {
self.lines.pop().map(|last| {
let b = self.layout.nodes[last].unwrap();
self.y += b.height;
(self.y, Line {
layout: self.layout,
pos: b.prev,
branches: 0,
measure: FlexMeasure::zero(),
line: b,
end: last-1
})
})
}
}
#[derive(Debug)]
pub struct Line<'l, 'o: 'l, O: Output + 'o> {
layout: &'l ParagraphLayout<'o, O>,
pos: usize,
end: usize,
branches: usize,
measure: FlexMeasure,
line: LineBreak
}
impl<'l, 'o: 'l, O: Output + 'o> Iterator for Line<'l, 'o, O> {
type Item = (f32, Item<'o, O>);
fn next(&mut self) -> Option<Self::Item> {
while self.pos < self.end {
let pos = self.pos;
self.pos += 1;
match self.layout.items[pos] {
Entry::Word(ref w) | Entry::Punctuation(ref w) => {
let x = self.measure.at(self.line.factor);
self.measure += O::measure_word(w, self.layout.width);
return Some((x, Item::Word(w)));
},
Entry::Space(_, s) => {
self.measure += s;
},
Entry::BranchEntry(len) => {
if self.line.path & (1<<self.branches) == 0 {
// not taken
self.pos += len;
}
self.branches += 1;
},
Entry::BranchExit(skip) => self.pos += skip,
Entry::Linebreak(_) => unreachable!(),
Entry::Anchor(ref data) => return Some((
self.measure.at(self.line.factor),
Item::Anchor(&*data)
)),
_ => {}
}
}
None
}
}
|
use gdal::errors::Result;
use gdal::spatial_ref::{CoordTransform, SpatialRef};
use gdal::vector::*;
use gdal::{Dataset, Driver};
use std::fs;
use std::path::Path;
fn run() -> Result<()> {
let dataset_a = Dataset::open(Path::new("fixtures/roads.geojson"))?;
let mut layer_a = dataset_a.layer(0)?;
let fields_defn = layer_a
.defn()
.fields()
.map(|field| (field.name(), field.field_type(), field.width()))
.collect::<Vec<_>>();
// Create a new dataset:
let path = std::env::temp_dir().join("abcde.shp");
let _ = fs::remove_file(&path);
let drv = Driver::get("ESRI Shapefile")?;
let mut ds = drv.create_vector_only(path.to_str().unwrap())?;
let lyr = ds.create_layer(Default::default())?;
// Copy the origin layer shema to the destination layer:
for fd in &fields_defn {
let field_defn = FieldDefn::new(&fd.0, fd.1)?;
field_defn.set_width(fd.2);
field_defn.add_to_layer(&lyr)?;
}
// Prepare the origin and destination spatial references objects:
let spatial_ref_src = SpatialRef::from_epsg(4326)?;
let spatial_ref_dst = SpatialRef::from_epsg(3025)?;
// And the feature used to actually transform the geometries:
let htransform = CoordTransform::new(&spatial_ref_src, &spatial_ref_dst)?;
// Get the definition to use on each feature:
let defn = Defn::from_layer(&lyr);
for feature_a in layer_a.features() {
// Get the original geometry:
let geom = feature_a.geometry();
// Get a new transformed geometry:
let new_geom = geom.transform(&htransform)?;
// Create the new feature, set its geometry:
let mut ft = Feature::new(&defn)?;
ft.set_geometry(new_geom)?;
// copy each field value of the feature:
for fd in &fields_defn {
if let Some(value) = feature_a.field(&fd.0)? {
ft.set_field(&fd.0, &value)?;
}
}
// Add the feature to the layer:
ft.create(&lyr)?;
}
Ok(())
}
fn main() {
run().unwrap();
}
|
extern crate reqwest;
use log::{info, warn};
use serde::{Deserialize, Serialize};
use serde_json::json;
use std::fmt;
type Result<T> = std::result::Result<T, Box<dyn std::error::Error + Send + Sync>>;
#[derive(Debug)]
struct ClientError(String);
impl fmt::Display for ClientError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "There is an error: {}", self.0)
}
}
impl std::error::Error for ClientError {}
pub struct Client {
host: String,
port: String,
token: Option<String>,
}
impl Client {
pub fn new(host: String, port: String) -> Client {
Client {
host,
port,
token: None,
}
}
pub async fn game_info(&self) -> Result<GameInfoResp> {
info!("Getting game info...");
let res = reqwest::get(&format!("http://{}:{}/game", self.host, self.port)).await?;
let game_info = res.json::<GameInfoResp>().await?;
info!("Got game info: {:?}", game_info);
Ok(game_info)
}
pub async fn connect(&mut self, name: String) -> Result<String> {
info!("Connecting to the game server...");
let res = reqwest::Client::new()
.post(&format!(
"http://{}:{}/game?team_name={}",
self.host, self.port, name
))
.send()
.await
.unwrap();
if res.status().is_success() {
let data_payload = res.json::<ConnectResp>().await.unwrap();
let data = data_payload.data;
self.token = Some(data.token);
info!(
"Connected to a server and got assigned color: {}",
data.color
);
Ok(data.color)
} else {
let err = res.text().await.unwrap().to_owned();
warn!("Error while connecting to the server: '{}'", err);
// Err(Box::new(ClientError(err)))
Err(err)?
}
}
pub async fn make_move(&self, moves: Vec<u32>) -> Result<()> {
info!("Making moves...");
let res = reqwest::Client::new()
.post(&format!("http://{}:{}/move", self.host, self.port))
.header(
"Authorization",
format!("Token {}", self.token.as_ref().unwrap()),
)
.json(&json!({ "move": &moves }))
.send()
.await
.unwrap();
if res.status().is_success() {
info!("Made moves: {:?}", moves);
Ok(())
} else {
let err = res.text().await.unwrap().to_owned();
warn!("Error while making moves: '{}'", err);
// Err(Box::new(ClientError(err)))
Err(err)?
}
}
}
#[derive(Debug, Serialize, Deserialize)]
struct ConnectResp {
status: String,
data: ConnectRespData,
}
#[derive(Debug, Serialize, Deserialize)]
struct ConnectRespData {
token: String,
color: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GameInfoResp {
status: String,
pub data: GameInfoData,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct GameInfoData {
pub status: String,
pub whose_turn: String,
pub winner: Option<String>,
pub board: Vec<Cell>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Cell {
pub color: String,
pub row: u32,
pub column: u32,
pub king: bool,
pub position: u32,
}
|
extern crate walkdir;
use clap::OsValues;
use regex::Regex;
use std::ffi::OsStr;
use std::fmt::{Error, Formatter};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::{fmt, io};
use walkdir::WalkDir;
type SearchResultProcessor = dyn Fn(&SearchResult, bool);
/// The holder of state for the search operation, which contains all of the needed parameters.
pub struct Context<'a> {
debug: bool,
re: Regex,
search_result_processor: &'a SearchResultProcessor,
}
impl Context<'_> {
/// Allow the creation of the holder of search parameters without making them public fields.
pub fn new(re: Regex, search_result_processor: &SearchResultProcessor, debug: bool) -> Context {
Context {
debug,
re,
search_result_processor,
}
}
}
// can't #[derive] because the SearchResultProcessor function reference doesn't implement Debug
impl fmt::Debug for Context<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("Context")
.field("debug", &self.debug)
.field("re", &self.re)
.field(
"search_result_processor",
&format_args!("{:p}", self.search_result_processor),
)
.finish()
}
}
impl fmt::Display for Context<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(
f,
"( debug: {}, re: {} search_result_processor: {:p} )",
self.debug, self.re, self.search_result_processor
)
}
}
type LineNumber = u64;
/// The structure used to return search results for processing.
#[derive(Clone, Debug)]
pub struct SearchResult<'a> {
pub path: &'a OsStr,
pub line_number: LineNumber,
pub text: &'a str,
pub new_file: bool,
_private: (), // to make creation only be possible within this crate, but allow pub fields
}
impl fmt::Display for SearchResult<'_> {
fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> {
write!(
f,
"({}, {}, {}, \"{}\")",
self.path.to_string_lossy(),
self.line_number,
self.new_file,
self.text
)
}
}
/// The main function to perform a search.
pub fn find_all_lines<'a>(paths: Option<OsValues<'a>>, context: &Context) -> io::Result<()> {
walk_all_paths(paths, context)
}
fn do_search(the_path: &PathBuf, _context: &Context) -> io::Result<()> {
let search_result_processor: &SearchResultProcessor = _context.search_result_processor;
// I always hate using a "first" sentinel, but sometimes it is needed
let mut new_file = true;
let re = &_context.re;
if _context.debug {
eprintln!("About to open file {:?}", the_path)
}
let f = File::open(the_path)?;
let f = BufReader::new(f);
for (_index, line) in f.lines().enumerate() {
if _context.debug {
eprintln!("About to look for {:?} in {:?}", re, line);
}
match line {
Ok(l) => {
if re.is_match(l.as_str()) {
let search_result: SearchResult = SearchResult {
path: the_path.as_os_str(),
line_number: (_index + 1) as LineNumber,
text: l.as_str(),
new_file,
_private: (),
};
if new_file {
new_file = false
}
search_result_processor(&search_result, _context.debug);
}
}
Err(e) => {
if _context.debug {
eprintln!("Error reading file {:?}: {:?}", the_path, e)
}
}
}
}
Ok(())
}
fn walk_a_dir<'a>(the_dir: &'a OsStr, context: &Context) -> io::Result<()> {
for entry in WalkDir::new(the_dir)
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
{
let path: PathBuf = entry.into_path();
let path_ref: &PathBuf = &path;
do_search(path_ref, context)?;
}
Ok(())
}
fn walk_all_paths<'a>(paths: Option<OsValues<'a>>, context: &Context) -> io::Result<()> {
let dot_as_os_str = OsStr::new(".");
let the_iterators: OsValues<'a> = match paths {
Some(path_values) => path_values,
None => OsValues::default(),
};
if the_iterators.clone().count() == 0 {
walk_a_dir(dot_as_os_str, context)?;
} else {
for the_iterator in the_iterators {
walk_a_dir(the_iterator, context)?;
}
}
Ok(())
}
|
use std::alloc::{Alloc, Layout, GlobalAlloc, AllocErr};
use std::ptr::NonNull;
use super::super::{Mutex, MutexGuard};
use super::Dlmalloc;
pub struct GlobalDlmalloc;
unsafe impl GlobalAlloc for GlobalDlmalloc {
#[inline]
unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
<Dlmalloc>::malloc(&mut get(), layout.size(), layout.align()) as *mut u8
}
#[inline]
unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
<Dlmalloc>::free(&mut get(), ptr as *mut u8, layout.size(), layout.align())
}
#[inline]
unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {
<Dlmalloc>::calloc(&mut get(), layout.size(), layout.align()) as *mut u8
}
#[inline]
unsafe fn realloc(
&self,
ptr: *mut u8,
layout: Layout,
new_size: usize
) -> *mut u8 {
<Dlmalloc>::realloc(
&mut get(),
ptr as *mut u8,
layout.size(),
layout.align(),
new_size,
) as *mut u8
}
}
unsafe impl Alloc for GlobalDlmalloc {
#[inline]
unsafe fn alloc(
&mut self,
layout: Layout
) -> Result<NonNull<u8>, AllocErr> {
get().alloc(layout)
}
#[inline]
unsafe fn dealloc(&mut self, ptr: NonNull<u8>, layout: Layout) {
get().dealloc(ptr, layout)
}
#[inline]
unsafe fn realloc(
&mut self,
ptr: NonNull<u8>,
layout: Layout,
new_size: usize
) -> Result<NonNull<u8>, AllocErr> {
Alloc::realloc(&mut *get(), ptr, layout, new_size)
}
#[inline]
unsafe fn alloc_zeroed(
&mut self,
layout: Layout
) -> Result<NonNull<u8>, AllocErr> {
get().alloc_zeroed(layout)
}
}
static DLMALLOC: Mutex<Dlmalloc> = Mutex::new(Dlmalloc(super::dlmalloc::DLMALLOC_INIT));
fn get() -> MutexGuard<'static, Dlmalloc> {
DLMALLOC.lock()
}
|
use crate::types::CustomRetrieveValue;
use aws_sdk_dynamodb::{
error::GetItemError, model::AttributeValue, output::GetItemOutput, types::SdkError,
};
use log::{self, debug};
use aws_sdk_dynamodb::Client;
pub async fn retrieve_database_item(
table_name: &str,
retrieve_value: &CustomRetrieveValue,
client: &Client,
) -> Result<GetItemOutput, SdkError<GetItemError>> {
debug!("About to get from DynamoDB {:?}", &retrieve_value.key);
client
.get_item()
.table_name(table_name)
.key("PK", AttributeValue::S(retrieve_value.key.to_string()))
.send()
.await
}
|
use crate::types::*;
use serde::{Serialize, Deserialize};
/*
Messages sent by the Clients to the servers.
*/
#[derive(Debug, Serialize, Deserialize)]
pub enum ClientMessage {
LimitOrderMsg(LimitOrderMsg),
}
#[derive(Debug, Serialize, Deserialize)]
pub struct LimitOrderMsg {
pub user: UserId,
pub order_id: OrderId,
pub symbol: String,
pub qty: Qty,
pub side: Side,
pub price: Price,
}
|
use utilities::prelude::*;
use crate::impl_vk_handle;
use crate::prelude::*;
use std::sync::Arc;
#[derive(Debug)]
pub struct Semaphore {
device: Arc<Device>,
semaphore: VkSemaphore,
}
impl Semaphore {
pub fn new(device: Arc<Device>) -> VerboseResult<Arc<Semaphore>> {
let semaphore_ci = VkSemaphoreCreateInfo::new(VK_SEMAPHORE_CREATE_NULL_BIT);
let semaphore = device.create_semaphore(&semaphore_ci)?;
Ok(Arc::new(Semaphore { device, semaphore }))
}
}
impl VulkanDevice for Semaphore {
fn device(&self) -> &Arc<Device> {
&self.device
}
}
impl_vk_handle!(Semaphore, VkSemaphore, semaphore);
impl Drop for Semaphore {
fn drop(&mut self) {
self.device.destroy_semaphore(self.semaphore);
}
}
use crate::{ffi::*, handle_ffi_result};
#[no_mangle]
pub extern "C" fn create_semaphore(device: *const Device) -> *const Semaphore {
let device = unsafe { Arc::from_raw(device) };
handle_ffi_result!(Semaphore::new(device))
}
#[no_mangle]
pub extern "C" fn destroy_semaphore(semaphore: *const Semaphore) {
let _semaphore = unsafe { Arc::from_raw(semaphore) };
}
|
extern crate minifb;
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};
use self::minifb::{Key, WindowOptions, MouseMode};
use std::thread::sleep;
use std::fmt;
use memory;
use window;
pub struct DebugScreen {
pub window: minifb::Window,
pub scroll: u16,
pub offset: u16,
pub width: usize,
pub buffer: Vec<u32>,
pub memory: Arc<RwLock<memory::Memory>>,
}
impl window::Drawable for DebugScreen {
fn update(&mut self) {
if self.window.is_open() {
self.window.get_scroll_wheel().map(|scroll| {
let amount = self.width.wrapping_mul(scroll.1 as usize);
self.scroll = self.scroll.wrapping_add(amount as u16);
});
self.window.get_mouse_pos(MouseMode::Clamp).map(|mouse| {
let x = mouse.0 as u16;
let y = mouse.1 as u16;
self.offset = y.wrapping_mul(self.width as u16).wrapping_add(x);
});
}
}
fn draw(&mut self) {
let offset = self.scroll.wrapping_sub(self.offset);
let byte = { self.memory.read().unwrap()[offset] };
let s = format!("0x{:0>4X}: {:0>4X}: {:0>2X}",
self.scroll,
offset,
byte);
self.window.set_title(&s);
let mut count = self.scroll;
let memory = { self.memory.read().unwrap() };
for i in &mut self.buffer {
let gray = memory[count] as u32;
*i = gray << 16 | gray << 8 | gray;
count = count.wrapping_sub(1);
}
let _ = self.window.update_with_buffer(&self.buffer);
}
fn pause(&mut self) {
let frame_duration = Duration::from_millis(16);
let ms = Duration::from_millis(1);
let mut previous_draw = Instant::now();
while self.window.is_open() && !self.window.is_key_down(Key::Escape) {
self.update();
let now = Instant::now();
if now - previous_draw > frame_duration {
self.draw();
previous_draw = now;
};
sleep(ms);
}
}
}
impl fmt::Display for DebugScreen {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(writeln!(f, "offset: {offset:0>4X}", offset=self.offset));
Ok(())
}
}
impl DebugScreen {
pub fn new(width: usize, height: usize, memory: Arc<RwLock<memory::Memory>>) -> DebugScreen {
DebugScreen {
buffer: vec![0; width * height],
memory: memory,
scroll: 0xFFFF,
offset: 0x0000,
width: width,
window: minifb::Window::new("rustboy debug",
width,
height,
WindowOptions {
borderless: true,
scale: minifb::Scale::X4,
..Default::default()
})
.unwrap(),
}
}
fn run(&mut self) {
self.width = self.window.get_size().0 / 4;
}
}
|
// Copyright 2012 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.
use std::path::Path;
use super::graph::NodeIndex;
use super::timestamp::TimeStamp;
use super::state::State;
/// As build commands run they can output extra dependency information
/// (e.g. header dependencies for C source) dynamically. DepsLog collects
/// that information at build time and uses it for subsequent builds.
///
/// The on-disk format is based on two primary design constraints:
/// - it must be written to as a stream (during the build, which may be
/// interrupted);
/// - it can be read all at once on startup. (Alternative designs, where
/// it contains indexing information, were considered and discarded as
/// too complicated to implement; if the file is small than reading it
/// fully on startup is acceptable.)
/// Here are some stats from the Windows Chrome dependency files, to
/// help guide the design space. The total text in the files sums to
/// 90mb so some compression is warranted to keep load-time fast.
/// There's about 10k files worth of dependencies that reference about
/// 40k total paths totalling 2mb of unique strings.
///
/// Based on these stats, here's the current design.
/// The file is structured as version header followed by a sequence of records.
/// Each record is either a path string or a dependency list.
/// Numbering the path strings in file order gives them dense integer ids.
/// A dependency list maps an output id to a list of input ids.
///
/// Concretely, a record is:
/// four bytes record length, high bit indicates record type
/// (but max record sizes are capped at 512kB)
/// path records contain the string name of the path, followed by up to 3
/// padding bytes to align on 4 byte boundaries, followed by the
/// one's complement of the expected index of the record (to detect
/// concurrent writes of multiple ninja processes to the log).
/// dependency records are an array of 4-byte integers
/// [output path id, output path mtime, input path id, input path id...]
/// (The mtime is compared against the on-disk output path mtime
/// to verify the stored data is up-to-date.)
/// If two records reference the same output the latter one in the file
/// wins, allowing updates to just be appended to the file. A separate
/// repacking step can run occasionally to remove dead records.
pub struct DepsLog {}
impl DepsLog {
pub fn new() -> Self {
DepsLog {}
}
pub fn load(&mut self, path: &Path, state: &mut State) -> Result<Option<String>, String> {
return Ok(None);
unimplemented!{}
}
pub fn open_for_write(&self, path: &Path) -> Result<(), String> {
return Ok(());
unimplemented!()
}
pub fn record_deps(
&self,
state: &State,
node_idx: NodeIndex,
mtime: TimeStamp,
nodes: &[NodeIndex],
) -> Result<(), ()> {
return Ok(());
unimplemented!()
}
pub fn recompact(&self, path: &Path) -> Result<(), String> {
unimplemented!()
}
}
/*
// Copyright 2012 Google Inc. 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.
#ifndef NINJA_DEPS_LOG_H_
#define NINJA_DEPS_LOG_H_
#include <string>
#include <vector>
using namespace std;
#include <stdio.h>
#include "timestamp.h"
struct Node;
struct State;
struct DepsLog {
DepsLog() : needs_recompaction_(false), file_(NULL) {}
~DepsLog();
// Writing (build-time) interface.
bool OpenForWrite(const string& path, string* err);
bool RecordDeps(Node* node, TimeStamp mtime, const vector<Node*>& nodes);
bool RecordDeps(Node* node, TimeStamp mtime, int node_count, Node** nodes);
void Close();
// Reading (startup-time) interface.
struct Deps {
Deps(int mtime, int node_count)
: mtime(mtime), node_count(node_count), nodes(new Node*[node_count]) {}
~Deps() { delete [] nodes; }
int mtime;
int node_count;
Node** nodes;
};
bool Load(const string& path, State* state, string* err);
Deps* GetDeps(Node* node);
/// Rewrite the known log entries, throwing away old data.
bool Recompact(const string& path, string* err);
/// Returns if the deps entry for a node is still reachable from the manifest.
///
/// The deps log can contain deps entries for files that were built in the
/// past but are no longer part of the manifest. This function returns if
/// this is the case for a given node. This function is slow, don't call
/// it from code that runs on every build.
bool IsDepsEntryLiveFor(Node* node);
/// Used for tests.
const vector<Node*>& nodes() const { return nodes_; }
const vector<Deps*>& deps() const { return deps_; }
private:
// Updates the in-memory representation. Takes ownership of |deps|.
// Returns true if a prior deps record was deleted.
bool UpdateDeps(int out_id, Deps* deps);
// Write a node name record, assigning it an id.
bool RecordId(Node* node);
bool needs_recompaction_;
FILE* file_;
/// Maps id -> Node.
vector<Node*> nodes_;
/// Maps id -> deps of that id.
vector<Deps*> deps_;
friend struct DepsLogTest;
};
#endif // NINJA_DEPS_LOG_H_
*/
|
/*
Copyright 2020 Timo Saarinen
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 super::*;
// -------------------------------------------------------------------------------------------------
/// Type 12: Addressed Safety-Related Message
#[derive(Default, Clone, Debug, PartialEq)]
pub struct AddressedSafetyRelatedMessage {
/// True if the data is about own vessel, false if about other.
pub own_vessel: bool,
/// AIS station type.
pub station: Station,
/// Source MMSI (30 bits)
pub source_mmsi: u32,
/// Sequence number (2 bits)
pub sequence_number: u8,
/// Destination MMSI (30 bits)
pub destination_mmsi: u32,
/// Retransmit flag (1 bit)
pub retransmit_flag: bool,
/// Text (936 bits; 1-156 chars)
pub text: String,
}
// -------------------------------------------------------------------------------------------------
/// AIS VDM/VDO type 12: Addressed Safety-Related Message
pub(crate) fn handle(
bv: &BitVec,
station: Station,
own_vessel: bool,
) -> Result<ParsedMessage, ParseError> {
Ok(ParsedMessage::AddressedSafetyRelatedMessage(
AddressedSafetyRelatedMessage {
own_vessel: { own_vessel },
station: { station },
source_mmsi: { pick_u64(&bv, 8, 30) as u32 },
sequence_number: { pick_u64(&bv, 38, 2) as u8 },
destination_mmsi: { pick_u64(&bv, 40, 30) as u32 },
retransmit_flag: { pick_u64(&bv, 70, 1) != 0 },
text: { pick_string(&bv, 72, 156) },
},
))
}
// -------------------------------------------------------------------------------------------------
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_parse_vdm_type12() {
// First message
let mut p = NmeaParser::new();
match p.parse_sentence(
"!AIVDM,1,1,,A,<02:oP0kKcv0@<51C5PB5@?BDPD?P:?2?EB7PDB16693P381>>5<PikP,0*37",
) {
Ok(ps) => {
match ps {
// The expected result
ParsedMessage::AddressedSafetyRelatedMessage(asrm) => {
assert_eq!(asrm.source_mmsi, 2275200);
assert_eq!(asrm.sequence_number, 0);
assert_eq!(asrm.destination_mmsi, 215724000);
assert_eq!(asrm.retransmit_flag, false);
assert_eq!(asrm.text, "PLEASE REPORT TO JOBOURG TRAFFIC CHANNEL 13");
}
ParsedMessage::Incomplete => {
assert!(false);
}
_ => {
assert!(false);
}
}
}
Err(e) => {
assert_eq!(e.to_string(), "OK");
}
}
// Second message
match p.parse_sentence(
"!AIVDM,1,1,,A,<CR3B@<0TO3j5@PmkiP31BCPphPDB13;CPihkP=?D?PmP3B5GPpn,0*3A",
) {
Ok(ps) => {
match ps {
// The expected result
ParsedMessage::AddressedSafetyRelatedMessage(asrm) => {
assert_eq!(asrm.source_mmsi, 237032000);
assert_eq!(asrm.sequence_number, 3);
assert_eq!(asrm.destination_mmsi, 2391100);
assert_eq!(asrm.retransmit_flag, true);
assert_eq!(asrm.text, "EP 531 CARS 80 TRACKS 103 MOTO 5 CREW 86");
}
ParsedMessage::Incomplete => {
assert!(false);
}
_ => {
assert!(false);
}
}
}
Err(e) => {
assert_eq!(e.to_string(), "OK");
}
}
}
}
|
use flame::Span;
use std::cmp::Ordering;
use std::collections::{hash_map, HashMap};
pub struct Profiler {
occurances: HashMap<String, (usize, f64)>,
}
impl Default for Profiler {
fn default() -> Self {
Self {
occurances: Default::default(),
}
}
}
impl Profiler {
pub fn record(&mut self, span: &Span) {
let opcode = span.name.to_string();
match self.occurances.entry(opcode) {
hash_map::Entry::Occupied(mut entry) => {
let (occ, avg) = *entry.get();
let (nocc, navg) = (
occ + 1,
((avg * (occ as f64)) + (span.delta as f64)) / ((occ + 1) as f64),
);
entry.insert((nocc, navg));
}
hash_map::Entry::Vacant(entry) => {
entry.insert((1, span.delta as f64));
}
}
}
pub fn print_stats(&self) {
println!("--- Profiler Stats ---");
let mut occs: Vec<_> = self.occurances.iter().collect();
occs.sort_by(|&(_k1, v1), &(_k2, v2)| match v1.1.partial_cmp(&v2.1) {
Some(val) => val,
None => Ordering::Equal,
});
occs.reverse();
for occ in occs {
println!("{}: {:.0} ns ({} times)", occ.0, (occ.1).1, (occ.1).0);
}
println!("--- End Profiler Stats ---");
}
}
|
#[doc = "Reader of register SCAR_PRG"]
pub type R = crate::R<u32, super::SCAR_PRG>;
#[doc = "Writer for register SCAR_PRG"]
pub type W = crate::W<u32, super::SCAR_PRG>;
#[doc = "Register SCAR_PRG `reset()`'s with value 0"]
impl crate::ResetValue for super::SCAR_PRG {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `SEC_AREA_START`"]
pub type SEC_AREA_START_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `SEC_AREA_START`"]
pub struct SEC_AREA_START_W<'a> {
w: &'a mut W,
}
impl<'a> SEC_AREA_START_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !0x0fff) | ((value as u32) & 0x0fff);
self.w
}
}
#[doc = "Reader of field `SEC_AREA_END`"]
pub type SEC_AREA_END_R = crate::R<u16, u16>;
#[doc = "Write proxy for field `SEC_AREA_END`"]
pub struct SEC_AREA_END_W<'a> {
w: &'a mut W,
}
impl<'a> SEC_AREA_END_W<'a> {
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub unsafe fn bits(self, value: u16) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x0fff << 16)) | (((value as u32) & 0x0fff) << 16);
self.w
}
}
#[doc = "Reader of field `DMES`"]
pub type DMES_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMES`"]
pub struct DMES_W<'a> {
w: &'a mut W,
}
impl<'a> DMES_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31);
self.w
}
}
impl R {
#[doc = "Bits 0:11 - Bank 1 lowest secure protected address configuration"]
#[inline(always)]
pub fn sec_area_start(&self) -> SEC_AREA_START_R {
SEC_AREA_START_R::new((self.bits & 0x0fff) as u16)
}
#[doc = "Bits 16:27 - Bank 1 highest secure protected address configuration"]
#[inline(always)]
pub fn sec_area_end(&self) -> SEC_AREA_END_R {
SEC_AREA_END_R::new(((self.bits >> 16) & 0x0fff) as u16)
}
#[doc = "Bit 31 - Bank 1 secure protected erase enable option configuration bit"]
#[inline(always)]
pub fn dmes(&self) -> DMES_R {
DMES_R::new(((self.bits >> 31) & 0x01) != 0)
}
}
impl W {
#[doc = "Bits 0:11 - Bank 1 lowest secure protected address configuration"]
#[inline(always)]
pub fn sec_area_start(&mut self) -> SEC_AREA_START_W {
SEC_AREA_START_W { w: self }
}
#[doc = "Bits 16:27 - Bank 1 highest secure protected address configuration"]
#[inline(always)]
pub fn sec_area_end(&mut self) -> SEC_AREA_END_W {
SEC_AREA_END_W { w: self }
}
#[doc = "Bit 31 - Bank 1 secure protected erase enable option configuration bit"]
#[inline(always)]
pub fn dmes(&mut self) -> DMES_W {
DMES_W { w: self }
}
}
|
pub mod sema;
mod transforms;
mod translate;
pub use self::sema::*;
pub use self::transforms::*;
pub use self::translate::*;
|
use std::collections::HashMap;
use std::fmt;
pub type Item = i32;
#[derive(Debug)]
pub struct Pair(usize, usize);
impl fmt::Display for Pair {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} {}", self.0, self.1)
}
}
#[aoc_generator(day10)]
pub fn input_generator(input: &str) -> Vec<Item> {
let mut xs = input
.lines()
.filter_map(|s| s.trim().parse().ok())
.collect::<Vec<Item>>();
xs.sort();
xs
}
#[aoc(day10, part1)]
pub fn solve_part1(input: &[Item]) -> usize {
let pair = calculate(input);
pair.0 * pair.1
}
fn calculate(input: &[i32]) -> Pair {
let mut joltage = 0;
let mut ones = 0;
let mut threes = 0;
for i in input {
match i - joltage {
1 => ones += 1,
3 => threes += 1,
_ => continue,
}
joltage = *i;
}
threes += 1; // built-in
println!("{} + {} = {}", ones, threes, ones + threes);
Pair(ones, threes)
}
fn count(input: &[Item]) -> usize {
let mut acc: HashMap<i32, i64> = HashMap::new();
acc.insert(0, 1);
for n in input {
for prev in 1..=3 {
if let Some(val) = acc.get(&(*n - prev)).copied() {
let entry = acc.entry(*n).or_insert(0);
*entry += val;
}
}
}
*acc.get(&(*input.iter().max().unwrap())).unwrap() as usize
}
#[aoc(day10, part2)]
pub fn solve_part2(input: &[Item]) -> usize {
count(input)
}
#[cfg(test)]
mod tests {
#![allow(unused)]
use super::*;
#[test]
fn test_smaller() {
let pair = calculate(&input_generator(SMALL));
assert_eq!(7, pair.0);
assert_eq!(5, pair.1);
}
#[test]
fn test_larger() {
let pair = calculate(&input_generator(LARGER));
assert_eq!(22, pair.0);
assert_eq!(10, pair.1);
}
#[test]
fn test_count_smaller() {
assert_eq!(8, count(&input_generator(SMALL)));
}
#[test]
fn test_count_larger() {
assert_eq!(19208, count(&input_generator(LARGER)))
}
const SMALL: &str = r##"16
10
15
5
1
11
7
19
6
12
4"##;
const LARGER: &str = r##"28
33
18
42
31
14
46
20
48
47
24
23
49
45
19
38
39
11
1
32
25
35
8
17
7
9
4
2
34
10
3"##;
}
|
use crate::matrices::Matrix44::*;
use crate::vectors::{Vector2::*, Vector3::*, Vector4::*};
use crate::defs::*;
use pancurses::Window;
pub struct FrameBuffer {
width: i32,
height: i32
}
impl FrameBuffer {
fn new(w: i32, h:i32) -> FrameBuffer {
FrameBuffer {
width: w,
height: h
}
}
}
pub struct Rasterizer<'a> {
fb: FrameBuffer,
window: &'a Window
}
// impl Default for Rasterizer< 'static> {
// fn default() -> Rasterizer<'static>{
// Rasterizer::new(500, 500)
// }
// }
impl Rasterizer<'_> {
pub fn new<'a>(width: i32, height: i32, window: &'a Window) -> Rasterizer<'a> {
Rasterizer {
fb: FrameBuffer::new(width, height),
window: window
}
}
fn getFrameBuffer(&self) -> &FrameBuffer {
&self.fb
}
pub fn rasterizeTriangle(&self, v1: &Vector2, v2: &Vector2, v3: &Vector2) {
let minX: i32;
let maxX: i32;
let minY: i32;
let maxY: i32;
minX = 0.max(v1.x.min(v2.x.min(v3.x)) as i32);
minY = 0.max(v1.y.min(v2.y.min(v3.y)) as i32);
maxX = self.fb.width.min(v1.x.max(v2.x.max(v3.x)) as i32 + 1);
maxY = self.fb.height.min(v1.y.max(v2.y.max(v3.y)) as i32 + 1);
for j in minY..maxY {
for i in minX..maxX {
if Rasterizer::isPointInTriangle(i, j, &v1, &v2, &v3) {
self.window.mvprintw(j, i, "#");
} else {
self.window.mvprintw(j, i, ".");
}
}
}
}
pub fn isPointInTriangle(ptX: i32, ptY: i32, v1: &Vector2, v2: &Vector2, v3: &Vector2) -> bool {
let wv1: f64 = ((v2.y - v3.y) * (ptX as f64 - v3.x) +
(v3.x - v2.x) * (ptY as f64 - v3.y)) /
((v2.y - v3.y) * (v1.x - v3.x) +
(v3.x - v2.x) * (v1.y - v3.y));
let wv2: f64 = ((v3.y - v1.y) * (ptX as f64 - v3.x) +
(v1.x - v3.x) * (ptY as f64 - v3.y)) /
((v2.y - v3.y) * (v1.x - v3.x) +
(v3.x - v2.x) * (v1.y - v3.y));
let wv3: f64 = 1f64 - wv1 -wv2;
let one: bool = wv1 < -0.001;
let two: bool = wv2 < -0.001;
let three: bool = wv3 < -0.001;
(one == two) && (two == three)
}
} |
fn main() {
let x = 13;
match x {
1 => println!("satu"),
2 | 3 | 5 | 7 | 11 => println!("bil prima"),
13..=19 => println!("Anak muda"),
_ => println!("Tidak ada yg spesial"),
}
let boolean = true;
let binary = match boolean {
false => 0,
true => 1,
};
println!("{} -> {}", boolean, binary);
} |
fn main() {
panic!("This should show a backtrace. Please ?");
}
|
// Copyright (c) 2016 The Rouille 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. All files in the project carrying such
// notice may not be copied, modified, or distributed except
// according to those terms.
//! Parsing data sent with `multipart/form-data`.
//!
//! > **Note**: You are encouraged to look at [the `post` module](../post/index.html) instead in
//! > order to parse data from HTML forms.
use std::error;
use std::fmt;
use Request;
use RequestBody;
use multipart::server::Multipart as InnerMultipart;
// TODO: provide wrappers around these
pub use multipart::server::MultipartData;
pub use multipart::server::MultipartField;
/// Error that can happen when decoding multipart data.
#[derive(Clone, Debug)]
pub enum MultipartError {
/// The `Content-Type` header of the request indicates that it doesn't contain multipart data
/// or is invalid.
WrongContentType,
/// Can't parse the body of the request because it was already extracted.
BodyAlreadyExtracted,
}
impl error::Error for MultipartError {}
impl fmt::Display for MultipartError {
#[inline]
fn fmt(&self, fmt: &mut fmt::Formatter) -> Result<(), fmt::Error> {
let description = match *self {
MultipartError::WrongContentType => {
"the `Content-Type` header of the request indicates that it doesn't contain \
multipart data or is invalid"
}
MultipartError::BodyAlreadyExtracted => {
"can't parse the body of the request because it was already extracted"
}
};
write!(fmt, "{}", description)
}
}
/// Attempts to decode the content of the request as `multipart/form-data` data.
pub fn get_multipart_input(request: &Request) -> Result<Multipart, MultipartError> {
let boundary = match multipart_boundary(request) {
Some(b) => b,
None => return Err(MultipartError::WrongContentType),
};
let request_body = if let Some(body) = request.data() {
body
} else {
return Err(MultipartError::BodyAlreadyExtracted);
};
Ok(Multipart {
inner: InnerMultipart::with_body(request_body, boundary),
})
}
/// Allows you to inspect the content of the multipart input of a request.
pub struct Multipart<'a> {
inner: InnerMultipart<RequestBody<'a>>,
}
impl<'a> Multipart<'a> {
#[allow(clippy::should_implement_trait)]
pub fn next(&mut self) -> Option<MultipartField<&mut InnerMultipart<RequestBody<'a>>>> {
self.inner.read_entry().unwrap_or(None)
}
}
fn multipart_boundary(request: &Request) -> Option<String> {
const BOUNDARY: &str = "boundary=";
let content_type = match request.header("Content-Type") {
None => return None,
Some(c) => c,
};
let start = match content_type.find(BOUNDARY) {
Some(pos) => pos + BOUNDARY.len(),
None => return None,
};
let end = content_type[start..]
.find(';')
.map_or(content_type.len(), |end| start + end);
Some(content_type[start..end].to_owned())
}
|
extern crate rand;
extern crate sdl2;
use std::process;
use std::env::args;
use std::time::{Instant, Duration};
mod cpu;
mod bus;
mod rom;
use cpu::Cpu;
use bus::Bus;
use rom::Rom;
use sdl2::rect::{Rect};
use sdl2::event::{Event};
use sdl2::keyboard::Keycode;
use sdl2::audio::{AudioCallback, AudioDevice, AudioSpecDesired};
use sdl2::Sdl;
pub struct SquareWave {
phase_inc: f32,
phase: f32,
volume: f32,
}
impl AudioCallback for SquareWave {
type Channel = f32;
fn callback(&mut self, out: &mut [f32]) {
for x in out.iter_mut() {
*x = match self.phase {
0.0...0.5 => self.volume,
_ => -self.volume
};
self.phase = (self.phase + self.phase_inc) % 1.0;
}
}
}
pub struct Beeper {
pub device: AudioDevice<SquareWave>,
duration: Duration,
start: Instant,
}
impl Beeper {
pub fn new(context: &Sdl, duration: Duration) -> Self {
let desired_spec = AudioSpecDesired {
freq: Some(24100),
channels: Some(1),
samples: None,
};
let sub = context.audio().unwrap();
let device = sub.open_playback(None, &desired_spec, |spec| {
SquareWave {
phase_inc: 440.0 / spec.freq as f32,
phase: 0.0,
volume: 0.25
}
}).unwrap();
Beeper {
device: device,
duration: duration,
start: Instant::now(),
}
}
pub fn set_beep(&mut self, enable: bool) {
if enable {
self.start = Instant::now();
self.device.resume();
} else {
if self.duration <= Instant::now().duration_since(self.start) {
self.device.pause();
}
}
}
}
fn main() {
let rom_file = args().nth(1).unwrap();
let rom = Rom::new(&rom_file).unwrap();
let bus = Bus::new(rom);
let mut cpu = Cpu::new(bus);
let mut now = Instant::now();
let mut last_instruction = now.clone();
let mut last_screen = now.clone();
let sdl_context = sdl2::init().unwrap();
let video_subsystem = sdl_context.video().unwrap();
let window = video_subsystem.window("CHIP-8 Emulator by Vitaly Shvetsov", 640, 320)
.position_centered()
.opengl()
.build()
.unwrap();
let mut renderer = window.into_canvas()
.index(find_sdl_gl_driver().unwrap())
.build()
.unwrap();
let mut rect = Rect::new(10, 10, 10, 10);
let black = sdl2::pixels::Color::RGB(0, 0, 0);
let white = sdl2::pixels::Color::RGB(255, 255, 255);
let mut events = sdl_context.event_pump().unwrap();
let mut beeper = Beeper::new(&sdl_context, Duration::from_millis(120));
loop {
now = Instant::now();
if now - last_instruction > Duration::from_millis(2) {
cpu.run_next_instruction();
last_instruction = now.clone();
cpu.decrease_timers(now.clone());
if now - last_screen > Duration::from_millis(10) {
let _ = renderer.set_draw_color(black);
let _ = renderer.clear();
for x in 0..64 {
for y in 0..32 {
if is_paint(x, y, &cpu.video) {
let x_pos = (x * 10) as i32;
let y_pos = (y * 10) as i32;
rect.set_y(y_pos);
rect.set_x(x_pos);
let _ = renderer.fill_rect(rect);
let _ = renderer.set_draw_color(white);
}
}
}
let _ = renderer.present();
last_screen = now.clone();
beeper.set_beep(cpu.make_sound);
}
for event in events.poll_iter() {
match event {
Event::Quit {..} | Event::KeyDown {keycode: Some(Keycode::Escape), ..} => {
process::exit(1);
},
Event::KeyDown { keycode: Some(Keycode::X), ..} => {
cpu.read_keys(0x0, true);
},
Event::KeyDown { keycode: Some(Keycode::Num1), ..} => {
cpu.read_keys(0x1, true);
},
Event::KeyDown { keycode: Some(Keycode::Num2), ..} => {
cpu.read_keys(0x2, true);
},
Event::KeyDown { keycode: Some(Keycode::Num3), ..} => {
cpu.read_keys(0x3, true);
},
Event::KeyDown { keycode: Some(Keycode::Q), ..} => {
cpu.read_keys(0x4, true);
},
Event::KeyDown { keycode: Some(Keycode::W), ..} => {
cpu.read_keys(0x5, true);
},
Event::KeyDown { keycode: Some(Keycode::E), ..} => {
cpu.read_keys(0x6, true);
},
Event::KeyDown { keycode: Some(Keycode::A), ..} => {
cpu.read_keys(0x7, true);
},
Event::KeyDown { keycode: Some(Keycode::S), ..} => {
cpu.read_keys(0x8, true);
},
Event::KeyDown { keycode: Some(Keycode::D), ..} => {
cpu.read_keys(0x9, true);
},
Event::KeyDown { keycode: Some(Keycode::Z), ..} => {
cpu.read_keys(0xa, true);
},
Event::KeyDown { keycode: Some(Keycode::C), ..} => {
cpu.read_keys(0xb, true);
},
Event::KeyDown { keycode: Some(Keycode::Num4), ..} => {
cpu.read_keys(0xc, true);
},
Event::KeyDown { keycode: Some(Keycode::R), ..} => {
cpu.read_keys(0xd, true);
},
Event::KeyDown { keycode: Some(Keycode::F), ..} => {
cpu.read_keys(0xe, true);
},
Event::KeyDown { keycode: Some(Keycode::V), ..} => {
cpu.read_keys(0xf, true);
},
Event::KeyUp { keycode: Some(Keycode::X), ..} => {
cpu.read_keys(0x0, false);
},
Event::KeyUp { keycode: Some(Keycode::Num1), ..} => {
cpu.read_keys(0x1, false);
},
Event::KeyUp { keycode: Some(Keycode::Num2), ..} => {
cpu.read_keys(0x2, false);
},
Event::KeyUp { keycode: Some(Keycode::Num3), ..} => {
cpu.read_keys(0x3, false);
},
Event::KeyUp { keycode: Some(Keycode::Q), ..} => {
cpu.read_keys(0x4, false);
},
Event::KeyUp { keycode: Some(Keycode::W), ..} => {
cpu.read_keys(0x5, false);
},
Event::KeyUp { keycode: Some(Keycode::E), ..} => {
cpu.read_keys(0x6, false);
},
Event::KeyUp { keycode: Some(Keycode::A), ..} => {
cpu.read_keys(0x7, false);
},
Event::KeyUp { keycode: Some(Keycode::S), ..} => {
cpu.read_keys(0x8, false);
},
Event::KeyUp { keycode: Some(Keycode::D), ..} => {
cpu.read_keys(0x9, false);
},
Event::KeyUp { keycode: Some(Keycode::Z), ..} => {
cpu.read_keys(0xa, false);
},
Event::KeyUp { keycode: Some(Keycode::C), ..} => {
cpu.read_keys(0xb, false);
},
Event::KeyUp { keycode: Some(Keycode::Num4), ..} => {
cpu.read_keys(0xc, false);
},
Event::KeyUp { keycode: Some(Keycode::R), ..} => {
cpu.read_keys(0xd, false);
},
Event::KeyUp { keycode: Some(Keycode::F), ..} => {
cpu.read_keys(0xe, false);
},
Event::KeyUp { keycode: Some(Keycode::V), ..} => {
cpu.read_keys(0xf, false);
},
_ => {}
}
}
}
}
}
fn is_paint(x: usize, y: usize, vid_buffer: &[[u8; 64]; 32]) -> bool {
vid_buffer[y][x] == 1
}
fn find_sdl_gl_driver() -> Option<u32> {
for (index, item) in sdl2::render::drivers().enumerate() {
if item.name == "opengl" {
return Some(index as u32);
}
}
None
}
|
use super::{LzfError, LzfResult};
/// Decompress the given data, if possible.
/// An error will be returned if decompression fails.
///
/// The length of the output buffer can be specified.
/// If the output buffer is not large enough to hold the decompressed data,
/// BufferTooSmall is returned.
/// Otherwise the number of decompressed bytes
/// (i.e. the original length of the data) is returned.
///
/// If an error in the compressed data is detected, DataCorrupted is returned.
///
/// Example:
///
/// ```rust,no_run
/// let data = "[your-compressed-data]";
/// let decompressed = lzf::decompress(data.as_bytes(), 10);
/// ```
pub fn decompress(data: &[u8], out_len_should: usize) -> LzfResult<Vec<u8>> {
let mut current_offset = 0;
let in_len = data.len();
if in_len == 0 {
return Err(LzfError::DataCorrupted);
}
// We have sanity checks to not exceed this capacity.
let mut output = vec![0; out_len_should];
let mut out_len: usize = 0;
while current_offset < in_len {
let mut ctrl = data[current_offset] as usize;
current_offset += 1;
if ctrl < (1 << 5) {
ctrl += 1;
if out_len + ctrl > out_len_should {
return Err(LzfError::BufferTooSmall);
}
if current_offset + ctrl > in_len {
return Err(LzfError::DataCorrupted);
}
// We can simply memcpy everything from the input to the output
output[out_len..(out_len + ctrl)]
.copy_from_slice(&data[current_offset..(current_offset + ctrl)]);
current_offset += ctrl;
out_len += ctrl;
} else {
let mut len = ctrl >> 5;
let mut ref_offset = (((ctrl & 0x1f) << 8) + 1) as i32;
if current_offset >= in_len {
return Err(LzfError::DataCorrupted);
}
if len == 7 {
len += data[current_offset] as usize;
current_offset += 1;
if current_offset >= in_len {
return Err(LzfError::DataCorrupted);
}
}
ref_offset += data[current_offset] as i32;
current_offset += 1;
if out_len + len + 2 > out_len_should {
return Err(LzfError::BufferTooSmall);
}
let mut ref_pos = (out_len as i32) - ref_offset;
if ref_pos < 0 {
return Err(LzfError::DataCorrupted);
}
let c = output[ref_pos as usize];
output[out_len] = c;
out_len += 1;
ref_pos += 1;
let c = output[ref_pos as usize];
output[out_len] = c;
out_len += 1;
ref_pos += 1;
while len > 0 {
let c = output[ref_pos as usize];
output[out_len] = c;
out_len += 1;
ref_pos += 1;
len -= 1;
}
}
}
// Set the real length now, user might have passed a bigger buffer in the first place.
unsafe { output.set_len(out_len) };
Ok(output)
}
#[test]
fn test_decompress_lorem() {
use super::compress;
let lorem = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod \
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At \
vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, \
no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit \
amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut \
labore et dolore magna aliquyam erat, sed diam voluptua.";
let compressed = compress(lorem.as_bytes()).unwrap();
let decompressed = decompress(&compressed[..], lorem.len()).unwrap();
assert_eq!(lorem.as_bytes(), &decompressed[..]);
let decompressed = decompress(&compressed[..], 1000).unwrap();
assert_eq!(lorem.len(), decompressed.len());
}
#[test]
fn test_decompress_fails_with_short_buffer() {
use super::compress;
let lorem = "Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod \
tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At \
vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, \
no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit \
amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut \
labore et dolore magna aliquyam erat, sed diam voluptua.";
let compressed = match compress(lorem.as_bytes()) {
Ok(c) => c,
Err(err) => panic!("Compression failed with error {:?}", err),
};
match decompress(&compressed, 10) {
Ok(_) => panic!("Decompression worked. That should not happen"),
Err(err) => assert_eq!(LzfError::BufferTooSmall, err),
}
}
#[test]
fn test_decompress_fails_for_corrupted_data() {
let lorem = "Lorem ipsum dolor sit amet";
match decompress(lorem.as_bytes(), lorem.len()) {
Ok(_) => panic!("Decompression worked. That should not happen"),
Err(err) => assert_eq!(LzfError::DataCorrupted, err),
}
}
#[test]
fn test_alice_wonderland() {
use super::compress;
let alice = "\r\n\r\n\r\n\r\n ALICE'S ADVENTURES IN WONDERLAND\r\n";
let compressed = match compress(alice.as_bytes()) {
Ok(c) => c,
Err(err) => panic!("Compression failed with error {:?}", err),
};
match decompress(&compressed, alice.len()) {
Ok(decompressed) => {
assert_eq!(alice.len(), decompressed.len());
assert_eq!(alice.as_bytes(), &decompressed[..]);
}
Err(err) => panic!("Decompression failed with error {:?}", err),
}
}
#[test]
fn easily_compressible() {
// RDB regression
let data = vec![1, 97, 97, 224, 187, 0, 1, 97, 97];
let real_length = 200;
let text = decompress(&data, real_length).unwrap();
assert_eq!(200, text.len());
assert_eq!(97, text[0]);
assert_eq!(97, text[199]);
}
#[test]
fn test_empty() {
assert_eq!(LzfError::DataCorrupted, decompress(&[], 10).unwrap_err());
}
|
use juniper::{
graphql_interface, graphql_object,
EmptySubscription, FieldResult, FieldError,
GraphQLObject, GraphQLInputObject,
ID, RootNode, http::GraphQLRequest
};
use tide::{Body, Request, Response, StatusCode};
use uuid::Uuid;
use bson::{Bson, doc};
use mongodb::{Client, options::ClientOptions, Collection};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
type StoreResult<T> = Result<T, Box<dyn std::error::Error>>;
#[derive(Clone)]
struct Store(Collection);
impl juniper::Context for Store {}
impl Store {
async fn save(&self, event: &StoredEvent) -> StoreResult<()> {
let doc = bson::to_bson(event)?;
if let Bson::Document(d) = doc {
println!("to_bson: {:?}", d);
self.0.insert_one(d, None).await?;
Ok(())
} else {
Err("invalid type".into())
}
}
async fn load(&self, id: ID) -> StoreResult<Option<StoredEvent>> {
let query = doc! {"_id": id.to_string()};
let r = self.0
.find_one(query, None)
.await?;
if let Some(d) = r {
let s = bson::from_document::<StoredEvent>(d)?;
Ok(Some(s))
} else {
Ok(None)
}
}
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(tag = "type")]
enum StoredEvent {
CreatedEvent(Created),
DeletedEvent(Deleted),
}
impl StoredEvent {
fn to_event(&self) -> EventValue {
match self {
Self::CreatedEvent(e) => e.clone().into(),
Self::DeletedEvent(e) => e.clone().into(),
}
}
}
#[derive(Debug, Clone, GraphQLInputObject)]
struct CreateInput {
target: ID,
value: i32,
}
#[derive(Debug, Clone, GraphQLInputObject)]
struct DeleteInput {
target: ID,
reason: Option<String>,
}
#[graphql_interface(for = [Created, Deleted])]
trait Event {
fn id(&self) -> ID;
fn target(&self) -> ID;
}
#[derive(Debug, Clone, GraphQLObject, Deserialize, Serialize)]
#[graphql(impl = EventValue)]
struct Created {
#[serde(rename = "_id")]
id: ID,
target: ID,
value: i32,
}
#[graphql_interface]
impl Event for Created {
fn id(&self) -> ID {
self.id.clone()
}
fn target(&self) -> ID {
self.target.clone()
}
}
#[derive(Debug, Clone, GraphQLObject, Deserialize, Serialize)]
#[graphql(impl = EventValue)]
struct Deleted {
#[serde(rename = "_id")]
id: ID,
target: ID,
reason: Option<String>,
}
#[graphql_interface]
impl Event for Deleted {
fn id(&self) -> ID {
self.id.clone()
}
fn target(&self) -> ID {
self.target.clone()
}
}
#[derive(Debug)]
struct Query;
#[graphql_object(Context = Store)]
impl Query {
async fn find(ctx: &Store, id: ID) -> FieldResult<Option<EventValue>> {
let r = ctx.load(id)
.await
.map_err(|e|
error(format!("{:?}", e).as_str())
)?;
Ok(r.map(|s| s.to_event()))
}
}
#[derive(Debug)]
struct Mutation;
#[graphql_object(Context = Store)]
impl Mutation {
async fn create(ctx: &Store, input: CreateInput) -> FieldResult<EventValue> {
let event = Created {
id: format!("event-{}", Uuid::new_v4()).into(),
target: input.target,
value: input.value,
};
ctx.save(&StoredEvent::CreatedEvent(event.clone()))
.await
.map(|_| event.into())
.map_err(|e|
error(format!("{:?}", e).as_str())
)
}
async fn delete(ctx: &Store, input: DeleteInput) -> FieldResult<EventValue> {
let event = Deleted {
id: format!("event-{}", Uuid::new_v4()).into(),
target: input.target,
reason: input.reason,
};
ctx.save(&StoredEvent::DeletedEvent(event.clone()))
.await
.map(|_| event.into())
.map_err(|e|
error(format!("{:?}", e).as_str())
)
}
}
type Schema = RootNode<'static, Query, Mutation, EmptySubscription<Store>>;
type State = (Store, Arc<Schema>);
#[async_std::main]
async fn main() -> tide::Result<()> {
let opt = ClientOptions::parse("mongodb://localhost").await?;
let mongo = Client::with_options(opt)?;
let state = (
Store(mongo.database("events").collection("data")),
Arc::new(Schema::new(Query, Mutation, EmptySubscription::new())),
);
let mut app = tide::with_state(state);
app.at("/graphql").post(handle_graphql);
app.listen("127.0.0.1:8080").await?;
Ok(())
}
fn error(msg: &str) -> FieldError {
FieldError::new(msg, juniper::Value::Null)
}
async fn handle_graphql(mut req: Request<State>) -> tide::Result {
let query: GraphQLRequest = req.body_json().await?;
let state = req.state();
println!("{:?}", query);
let res = query.execute(&state.1, &state.0).await;
let status = if res.is_ok() {
StatusCode::Ok
} else {
StatusCode::BadRequest
};
Body::from_json(&res)
.map(|b|
Response::builder(status)
.body(b)
.build()
)
} |
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#![feature(async_await, await_macro, futures_api)]
#![deny(warnings)]
use failure::{Error, ResultExt};
use fidl::endpoints::ServiceMarker;
use fidl_fuchsia_amber::ControlMarker as AmberMarker;
use fidl_fuchsia_pkg::{PackageCacheMarker, PackageResolverMarker};
use fuchsia_app::client::connect_to_service;
use fuchsia_app::server::ServicesServer;
use fuchsia_async as fasync;
use fuchsia_syslog::{self, fx_log_err, fx_log_info};
use futures::TryFutureExt;
mod resolver_service;
const SERVER_THREADS: usize = 2;
fn main() -> Result<(), Error> {
fuchsia_syslog::init_with_tags(&["pkg_resolver"]).expect("can't init logger");
fx_log_info!("starting package resolver");
let mut executor = fasync::Executor::new().context("error creating executor")?;
let amber = connect_to_service::<AmberMarker>().context("error connecting to amber")?;
let cache =
connect_to_service::<PackageCacheMarker>().context("error connecting to package cache")?;
let server = ServicesServer::new()
.add_service((PackageResolverMarker::NAME, move |chan| {
fx_log_info!("spawning resolver service");
fasync::spawn(
resolver_service::run_resolver_service(amber.clone(), cache.clone(), chan)
.unwrap_or_else(|e| fx_log_err!("failed to spawn {:?}", e)),
)
}))
.start()
.context("error starting package resolver server")?;
executor
.run(server, SERVER_THREADS)
.context("failed to execute package resolver future")?;
Ok(())
}
|
extern crate regex;
use std::io;
use std::fs;
use std::io::BufRead;
use std::path::Path;
use std::collections::HashSet;
use regex::Regex;
fn main() {
let input = parse_input();
let program = input.program;
println!("{}", program.find_loop());
println!("Looking for termination...");
for i in 0..program.instructions.len() {
let new_program = program.copy_with_mutation_at_index(i);
match new_program.find_terminate() {
Some(acc) => {
println!("Found result {} by changing index {}", acc, i);
break;
}
None => {}
}
}
}
struct InputData {
program: Program,
}
#[derive(Clone, Copy)]
enum OpCode {
Acc,
Jmp,
Nop,
}
struct Instruction {
op_code: OpCode,
offset: i32,
}
struct Program {
instructions: Vec<Instruction>
}
impl Program {
fn find_loop(&self) -> i32 {
let mut acc_value = 0;
let mut instruction_pointer: usize = 0;
let mut visited_indexes = HashSet::new();
while !visited_indexes.contains(&instruction_pointer) {
visited_indexes.insert(instruction_pointer);
let instruction = &self.instructions[instruction_pointer];
match instruction.op_code {
OpCode::Acc => {
acc_value += instruction.offset;
instruction_pointer += 1;
}
OpCode::Jmp => {
if instruction.offset > 0 {
instruction_pointer = instruction_pointer + (instruction.offset as usize);
} else {
let abs: i32 = -instruction.offset;
instruction_pointer = instruction_pointer - (abs as usize);
}
}
OpCode::Nop => {
instruction_pointer += 1;
}
}
}
acc_value
}
fn find_terminate(&self) -> Option<i32> {
let mut acc_value = 0;
let mut instruction_pointer: usize = 0;
let mut visited_indexes = HashSet::new();
loop {
// Looped
if visited_indexes.contains(&instruction_pointer) {
return None;
}
visited_indexes.insert(instruction_pointer);
if instruction_pointer >= self.instructions.len() {
return Some(acc_value);
}
let instruction = &self.instructions[instruction_pointer];
match instruction.op_code {
OpCode::Acc => {
acc_value += instruction.offset;
instruction_pointer += 1;
}
OpCode::Jmp => {
if instruction.offset > 0 {
instruction_pointer = instruction_pointer + (instruction.offset as usize);
} else {
let abs: i32 = -instruction.offset;
instruction_pointer = instruction_pointer - (abs as usize);
}
}
OpCode::Nop => {
instruction_pointer += 1;
}
}
}
}
fn copy_with_mutation_at_index(&self, mutation_index: usize) -> Program {
Program {
instructions: self.instructions.iter().enumerate().map(|(index, instruction)| {
if index == mutation_index {
Instruction {
op_code: match instruction.op_code {
OpCode::Acc => OpCode::Acc,
OpCode::Jmp => OpCode::Nop,
OpCode::Nop => OpCode::Jmp,
},
offset: instruction.offset,
}
} else {
Instruction {
op_code: instruction.op_code,
offset: instruction.offset,
}
}
}).collect(),
}
}
}
fn parse_input() -> InputData {
let io_result = lines_in_file("input/day8.txt");
let instruction_regex = Regex::new(r"^(?P<op>acc|jmp|nop) (?P<num>(\+|-)\d+)$").unwrap();
match io_result {
Ok(lines) => {
let instructions = lines.map(|line| {
match line {
Ok(stuff) => {
let captures = instruction_regex.captures(&stuff).unwrap();
let op_code_str = captures.name("op").unwrap().as_str();
let op_code = match op_code_str {
"acc" => OpCode::Acc,
"jmp" => OpCode::Jmp,
"nop" => OpCode::Nop,
_ => panic!("Unknown op code {}", op_code_str),
};
let offset = captures.name("num").unwrap().as_str().parse().unwrap();
Instruction {
op_code: op_code,
offset: offset,
}
}
Err(_) => panic!("Error reading line"),
}
}).collect();
InputData {
program: Program { instructions: instructions },
}
},
Err(_) => panic!("Error reading file"),
}
}
fn lines_in_file<P>(file_path: P) -> io::Result<io::Lines<io::BufReader<fs::File>>> where P: AsRef<Path> {
let file = fs::File::open(file_path)?;
Ok(io::BufReader::new(file).lines())
}
|
use super::VarResult;
use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType};
use crate::helper::{pine_ref_to_f64, pine_ref_to_i64};
use crate::runtime::context::{downcast_ctx, Ctx};
use crate::types::{Callable, Float, Int, PineFrom, PineRef, RuntimeErr, Series, NA};
use std::mem;
use std::rc::Rc;
fn int_abs<'a>(xval: Option<PineRef<'a>>) -> Int {
match pine_ref_to_i64(xval) {
None => None,
Some(v) => Some(v.abs()),
}
}
fn float_abs<'a>(xval: Option<PineRef<'a>>) -> Float {
match pine_ref_to_f64(xval) {
None => None,
Some(v) => Some(v.abs()),
}
}
fn abs_func<'a>(
_context: &mut dyn Ctx<'a>,
mut param: Vec<Option<PineRef<'a>>>,
func_type: FunctionType<'a>,
) -> Result<PineRef<'a>, RuntimeErr> {
let xval = mem::replace(&mut param[0], None);
match ((func_type.signature.0)[0]).1 {
SyntaxType::Simple(SimpleSyntaxType::Int) => {
let res = int_abs(xval);
Ok(PineRef::new_box(res))
}
SyntaxType::Series(SimpleSyntaxType::Int) => {
let res = int_abs(xval);
Ok(PineRef::new_rc(Series::from(res)))
}
SyntaxType::Simple(SimpleSyntaxType::Float) => {
let res = float_abs(xval);
Ok(PineRef::new_box(res))
}
SyntaxType::Series(SimpleSyntaxType::Float) => {
let res = float_abs(xval);
Ok(PineRef::new_rc(Series::from(res)))
}
_ => unreachable!(),
}
}
pub const VAR_NAME: &'static str = "abs";
pub fn declare_var<'a>() -> VarResult<'a> {
let value = PineRef::new(Callable::new(Some(abs_func), None));
let func_type = FunctionTypes(vec![
FunctionType::new((vec![("x", SyntaxType::int())], SyntaxType::int())),
FunctionType::new((
vec![("x", SyntaxType::int_series())],
SyntaxType::int_series(),
)),
FunctionType::new((vec![("x", SyntaxType::float())], SyntaxType::float())),
FunctionType::new((
vec![("x", SyntaxType::float_series())],
SyntaxType::float_series(),
)),
]);
let syntax_type = SyntaxType::Function(Rc::new(func_type));
VarResult::new(value, syntax_type, VAR_NAME)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ast::stat_expr_types::VarIndex;
use crate::ast::syntax_type::SimpleSyntaxType;
use crate::runtime::{AnySeries, NoneCallback, VarOperate};
use crate::{LibInfo, PineParser, PineRunner};
#[test]
fn abs_test() {
let lib_info = LibInfo::new(
vec![declare_var()],
vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))],
);
let src = "m1 = abs(-123)\nm2 = abs(int(close))\nm3 = abs(-123.23)\nm4 = abs(close)";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner
.run(
&vec![("close", AnySeries::from_float_vec(vec![Some(-2f64)]))],
None,
)
.unwrap();
assert_eq!(
runner.get_context().move_var(VarIndex::new(0, 0)),
Some(PineRef::new(Some(123i64)))
);
assert_eq!(
runner.get_context().move_var(VarIndex::new(1, 0)),
Some(PineRef::new_rc(Series::from_vec(vec![Some(2i64)])))
);
assert_eq!(
runner.get_context().move_var(VarIndex::new(2, 0)),
Some(PineRef::new(Some(123.23f64)))
);
assert_eq!(
runner.get_context().move_var(VarIndex::new(3, 0)),
Some(PineRef::new_rc(Series::from_vec(vec![Some(2f64)])))
);
}
#[test]
fn abs_const_test() {
use crate::libs::plot;
use crate::runtime::{downcast_ctx, OutputData};
let lib_info = LibInfo::new(vec![declare_var(), plot::declare_var()], vec![]);
let src = "plot(abs(-1))";
let blk = PineParser::new(src, &lib_info).parse_blk().unwrap();
let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback());
runner.runl(&vec![], 2, None).unwrap();
assert_eq!(
downcast_ctx(runner.get_context()).move_output_data(),
vec![Some(OutputData::new(vec![vec![Some(1f64), Some(1f64)]]))]
);
}
}
|
#[allow(dead_code)]
#[allow(deprecated)]
fn read_line_from_stdin() -> String {
let mut buffer = String::new();
std::io::stdin().read_line(&mut buffer).unwrap();
buffer.trim_right().to_owned()
}
fn main() {
println!(
"{}",
read_line_from_stdin().chars().filter(|c| *c == '1').count()
);
}
|
use front::stdlib::object::{PROTOTYPE, INSTANCE_PROTOTYPE, ObjectData, Property};
use serialize::json::from_str;
use front::stdlib::function::Function;
use std::collections::btree_map::BTreeMap;
use std::cmp::Ordering;
use std::ops::*;
use serialize::json::Json::*;
use std::string::String;
use serialize::json::{ToJson, Json, Object};
use std::fmt;
use std::ops::{Add, Sub, Mul, Div, Rem, BitAnd, BitOr, BitXor};
use std::f64;
use front::stdlib::value::ValueData::*;
use std::gc::{Gc, GC};
use std::ffi::CString;
use std::cell::RefCell;
use std::iter::FromIterator;
use std::cmp::PartialOrd;
use front::stdlib::*;
use std::ops::Deref;
use serde_json::value::{Number};
#[must_use]
/// The result of a Javascript expression is represented like this so it can succeed (`Ok`) or fail (`Err`)
pub type ResultValue = Result<Value, Value>;
#[derive(Clone)]
/// A Garbage-collected Javascript value as represented in the interpreter
pub struct Value {
/// The garbage-collected pointer
pub ptr: Gc<ValueData>
}
impl Deref for Value {
#[inline]
fn deref<'a>(&'a self) -> &'a ValueData {
&**self
}
}
#[derive(Clone)]
/// A Javascript value
pub enum ValueData {
/// `null` - A null value, for when a value doesn't exist
VNull,
/// `undefined` - An undefined value, for when a field or index doesn't exist
VUndefined,
/// `boolean` - A `true` / `false` value, for if a certain criteria is met
VBoolean(bool),
/// `String` - A UTF-8 string, such as `"Hello, world"`
VString(String),
/// `Number` - A 64-bit floating point number, such as `3.1415`
VNumber(f64),
/// `Number` - A 32-bit integer, such as `42`
VInteger(i32),
/// `Object` - An object, such as `Math`, represented by a binary tree of string keys to Javascript values
VObject(RefCell<ObjectData>),
/// `Function` - A runnable block of code, such as `Math.sqrt`, which can take some variables and return a useful value or act upon an object
VFunction(RefCell<Function>)
}
impl Value {
#[inline]
/// Move some value data into a new value
pub fn new(data: ValueData) -> Value {
Value {
ptr: box(GC)
}
}
/// Create a new global object
pub fn new_global() -> Value {
let global = Value::new_obj(None);
array::init(global);
boolean::init(global);
console::init(global);
error::init(global);
function::init(global);
json::init(global);
math::init(global);
number::init(global);
object::init(global);
string::init(global);
uri::init(global);
global
}
/// Returns a new empty object
pub fn new_obj(global: Option<Value>) -> Value {
let mut obj : ObjectData = BTreeMap::new();
if global.is_some() {
let obj_proto = global.unwrap().get_field("Object").get_field(PROTOTYPE);
obj.insert(INSTANCE_PROTOTYPE.into_string(), Property::new(obj_proto));
}
Value::new(VObject(RefCell::new(obj)))
}
/// Returns true if the value is an object
pub fn is_object(&self) -> bool {
match **self {
VObject(_) => true,
_ => false
}
}
/// Returns true if the value is undefined
pub fn is_undefined(&self) -> bool {
match **self {
VUndefined => true,
_ => false
}
}
/// Returns true if the value is null
pub fn is_null(&self) -> bool {
match **self {
VNull => true,
_ => false
}
}
/// Returns true if the value is null or undefined
pub fn is_null_or_undefined(&self) -> bool {
match **self {
VNull | VUndefined => true,
_ => false
}
}
/// Returns true if the value is a 64-bit floating-point number
pub fn is_double(&self) -> bool {
match **self {
VNumber(_) => true,
_ => false
}
}
/// Returns true if the value is a string
pub fn is_string(&self) -> bool {
match **self {
VString(_) => true,
_ => false
}
}
/// Returns true if the value is true
pub fn is_true(&self) -> bool {
match **self {
VObject(_) => true,
VString(ref s) if s.as_slice() == "1" => true,
VNumber(n) if n >= 1.0 && n % 1.0 == 0.0 => true,
VInteger(n) if n > 1 => true,
VBoolean(v) => v,
_ => false
}
}
/// Converts the value into a 64-bit floating point number
pub fn to_num(&self) -> f64 {
match **self {
VObject(_) | VUndefined | VFunction(_) => f64::NAN,
VString(ref str) => match from_str(str.as_slice()) {
Some(num) => num,
None => f64::NAN
},
VNumber(num) => num,
VBoolean(true) => 1.0,
VBoolean(false) | VNull => 0.0,
VInteger(num) => num as f64
}
}
/// Converts the value into a 32-bit integer
pub fn to_int(&self) -> i32 {
match **self {
VObject(_) | VUndefined | VNull | VBoolean(false) | VFunction(_) => 0,
VString(ref str) => match from_str(str.as_slice()) {
Some(num) => num,
None => 0
},
VNumber(num) => num as i32,
VBoolean(true) => 1,
VInteger(num) => num
}
}
/// Resolve the property in the object
pub fn get_prop<'a>(&self, field:&'a str) -> Option<Property> {
let obj : ObjectData = match **self {
VObject(ref obj) => obj.borrow().clone(),
VFunction(ref func) =>func.borrow().object.clone(),
_ => return None
};
match obj.find(&field.into_string()) {
Some(val) => Some(*val),
None => match obj.find(&PROTOTYPE.into_string()) {
Some(prop) =>
prop.value.get_prop(field),
None => None
}
}
}
/// Resolve the property in the object and get its value, or undefined if this is not an object or the field doesn't exist
pub fn get_field<'a>(&self, field:&'a str) -> Value {
match self.get_prop(field) {
Some(prop) => prop.value,
None => Value::new(VUndefined)
}
}
/// Set the field in the value
pub fn set_field<'a>(&self, field:&'a str, val:Value) -> Value {
match **self {
VObject(ref obj) => {
obj.borrow_mut().insert(field.into_string(), Property::new(val));
},
VFunction(ref func) => {
func.borrow_mut().object.insert(field.into_string(), Property::new(val));
},
_ => ()
}
val
}
/// Set the property in the value
pub fn set_prop<'a>(&self, field:&'a str, prop:Property) -> Property {
match **self {
VObject(ref obj) => {
obj.borrow_mut().insert(field.into_string(), prop);
},
VFunction(ref func) => {
func.borrow_mut().object.insert(field.into_string(), prop);
},
_ => ()
}
prop
}
/// Convert from a JSON value to a JS value
pub fn from_json(json:Json) -> ValueData {
match json {
Number::from_f64(v) => VNumber(v),
String(v) => VString(v),
Boolean(v) => VBoolean(v),
Array(vs) => {
let mut i = 0;
let mut data : ObjectData = FromIterator::from_iter(vs.iter().map(|json| {
i += 1;
((i - 1).to_string(), Property::new(to_value(json.clone())))
}));
data.insert("length".into_string(), Property::new(to_value(vs.len() as i32)));
VObject(RefCell::new(data))
},
Object(obj) => {
let data : ObjectData = FromIterator::from_iter(obj.iter().map(|(key, json)| {
(key.clone(), Property::new(to_value(json.clone())))
}));
VObject(RefCell::new(data))
},
Null => VNull
}
}
/// Get the type of the value
pub fn get_type(&self) -> &'static str {
match **self {
VNumber(_) | VInteger(_) => "number",
VString(_) => "string",
VBoolean(_) => "boolean",
VNull => "null",
VUndefined => "undefined",
_ => "object"
}
}
/// Get the value for undefined
pub fn undefined() -> Value {
Value::new(VUndefined)
}
}
impl fmt::Display for Value {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match **self {
VNull => write!(f, "null"),
VUndefined => write!(f, "undefined"),
VBoolean(v) => write!(f, "{}", v),
VString(ref v) => write!(f, "{}", v),
VNumber(v) => write!(f, "{}", match v {
_ if v.is_nan() => "NaN".into_string(),
f64::INFINITY => "Infinity".into_string(),
f64::NEG_INFINITY => "-Infinity".into_string(),
_ => f64::to_str_digits(v, 15)
}),
VObject(ref v) => {
try!(write!(f, "{}", "{"));
match v.borrow().iter().last() {
Some((last_key, _)) => {
for (key, val) in v.borrow().iter() {
try!(write!(f, "{}: {}", key, val.value));
if key != last_key {
try!(write!(f, "{}", ", "));
}
}
},
None => ()
}
write!(f, "{}", "}")
},
VInteger(v) => write!(f, "{}", v),
VFunction(ref v) => {
let args = v.borrow().args.connect(", ");
write!(f, "function({}){{...}}", args)
}
}
}
}
impl PartialEq for Value {
fn eq(&self, other:&Value) -> bool {
match ((**self).clone(), (*other.ptr).clone()) {
_ if self.is_null_or_undefined() && other.is_null_or_undefined() => true,
(VString(_), _) | (_, VString(_)) => self.to_string() == other.to_string(),
(VBoolean(a), VBoolean(b)) if a == b => true,
(VNumber(a), VNumber(b)) if a == b && !a.is_nan() && !b.is_nan() => true,
(VNumber(a), _) if a == other.to_num() => true,
(_, VNumber(a)) if a == self.to_num() => true,
(VInteger(a), VInteger(b)) if a == b => true,
_ => false
}
}
}
impl ToJson for Value {
fn to_json( &self ) -> Json {
match **self {
VNull | VUndefined => Null,
VBoolean(b) => Boolean(b),
VObject(ref obj) => {
let mut nobj = BTreeMap::new();
for (k, v) in obj.borrow().iter() {
if k.as_slice() != INSTANCE_PROTOTYPE.as_slice() {
nobj.insert(k.clone(), v.value.to_json());
}
}
Object(nobj)
},
VString(ref str) => String(str.clone()),
//TODO remove comments (original code) if compilation succeeds
//VNumber(num) => Number(num),
VNumber(num) => Number::as_i64(num),
//VInteger(val) => Number(val as f64),
VInteger(val) => Number::as_f64(val),
VFunction(_) => Null
}
}
}
impl Add for Value {
fn add(&self, other:&Value) -> Value {
if self.is_string() || other.is_string() {
let text = self.to_string().append(other.to_string().as_slice());
to_value(text)
} else {
to_value(self.to_num() + other.to_num())
}
}
}
impl Sub for Value {
fn sub(&self, other:&Value) -> Value {
to_value(self.to_num() - other.to_num())
}
}
impl Mul for Value {
fn mul(&self, other:&Value) -> Value {
to_value(self.to_num() * other.to_num())
}
}
impl Div for Value {
fn div(&self, other:&Value) -> Value {
to_value(self.to_num() / other.to_num())
}
}
impl Rem for Value {
fn rem(&self, other:&Value) -> Value {
to_value(self.to_num() % other.to_num())
}
}
impl BitAnd for Value {
fn bitand(&self, other:&Value) -> Value {
to_value(self.to_int() & other.to_int())
}
}
impl BitOr for Value {
fn bitor(&self, other:&Value) -> Value {
to_value(self.to_int() | other.to_int())
}
}
impl BitXor for Value {
fn bitxor(&self, other:&Value) -> Value {
to_value(self.to_int() ^ other.to_int())
}
}
impl Shl for Value {
fn shl(&self, other:&Value) -> Value {
to_value(self.to_int() << other.to_int() as u64)
}
}
impl Shr for Value {
fn shr(&self, other:&Value) -> Value {
to_value(self.to_int() >> other.to_int() as u64)
}
}
impl Not for Value {
fn not(&self) -> Value {
to_value(!self.is_true())
}
}
impl Neg for Value {
fn neg(&self) -> Value {
to_value(-self.to_num())
}
}
impl PartialOrd for Value {
fn partial_cmp(&self, other: &Value) -> Option<Ordering> {
self.to_num().partial_cmp(&other.to_num())
}
}
/// Conversion to Javascript values from Rust values
pub trait ToValue {
/// Convert this value to a Rust value
fn to_value(&self) -> Value;
}
/// Conversion to Rust values from Javascript values
pub trait FromValue {
/// Convert this value to a Javascript value
fn from_value(value:Value) -> Result<Self, &'static str>;
}
impl ToValue for Value {
#[inline(always)]
fn to_value(&self) -> Value {
*self
}
}
impl FromValue for Value {
#[inline(always)]
fn from_value(v:Value) -> Result<Value, &'static str> {
Ok(v)
}
}
impl ToValue for String {
#[inline(always)]
fn to_value(&self) -> Value {
Value::new(VString(self.clone()))
}
}
impl FromValue for String {
fn from_value(v:Value) -> Result<String, &'static str> {
Ok(v.to_string())
}
}
impl<'s> ToValue for &'s str {
fn to_value(&self) -> Value {
Value::new(VString(String::from_str(*self)))
}
}
impl ToValue for *const i8 {
fn to_value(&self) -> Value {
unsafe {
let cstr = CString::new(*self, false);
to_value(cstr.as_str().unwrap())
}
}
}
impl ToValue for char {
fn to_value(&self) -> Value {
Value::new(VString(String::from_char(1, *self)))
}
}
impl FromValue for char {
fn from_value(v:Value) -> Result<char, &'static str> {
Ok(v.to_string().as_slice().char_at(0))
}
}
impl ToValue for f64 {
fn to_value(&self) -> Value {
Value::new(VNumber(*self))
}
}
impl FromValue for f64 {
fn from_value(v:Value) -> Result<f64, &'static str> {
Ok(v.to_num())
}
}
impl ToValue for i32 {
fn to_value(&self) -> Value {
Value::new(VInteger(*self))
}
}
impl FromValue for i32 {
fn from_value(v:Value) -> Result<i32, &'static str> {
Ok(v.to_int())
}
}
impl ToValue for bool {
fn to_value(&self) -> Value {
Value::new(VBoolean(*self))
}
}
impl FromValue for bool {
fn from_value(v:Value) -> Result<bool, &'static str> {
Ok(v.is_true())
}
}
impl<'s, T:ToValue> ToValue for &'s [T] {
fn to_value(&self) -> Value {
to_value::<ObjectData>(self.iter().enumerate().map(|(i, elem)| {
(i.to_string(), Property::new(elem.to_value()))
}).collect())
}
}
impl<T:ToValue> ToValue for Vec<T> {
fn to_value(&self) -> Value {
to_value::<ObjectData>(self.iter().enumerate().map(|(i, elem)| {
(i.to_string(), Property::new(elem.to_value()))
}).collect())
}
}
impl<T:FromValue> FromValue for Vec<T> {
fn from_value(v:Value) -> Result<Vec<T>, &'static str> {
let len = v.get_field("length").to_int();
let mut vec = Vec::with_capacity(len as u64);
for i in 0..len {
vec.push(try!(from_value(v.get_field(i.to_string().as_slice()))))
}
Ok(vec)
}
}
impl ToValue for ObjectData {
fn to_value(&self) -> Value {
Value::new(VObject(RefCell::new(self.clone())))
}
}
impl FromValue for ObjectData {
fn from_value(v:Value) -> Result<ObjectData, &'static str> {
match *v.ptr {
VObject(ref obj) => Ok(obj.borrow().deref().clone()),
VFunction(ref func) => Ok(func.borrow().object.clone()),
_ => Err("Value is not a valid object")
}
}
}
impl ToValue for Json {
fn to_value(&self) -> Value {
Value::new(Value::from_json(self.clone()))
}
}
impl FromValue for Json {
fn from_value(v:Value) -> Result<Json, &'static str> {
Ok(v.to_json())
}
}
impl ToValue for () {
fn to_value(&self) -> Value {
Value::new(VNull)
}
}
impl FromValue for () {
fn from_value(_:Value) -> Result<(), &'static str> {
Ok(())
}
}
impl<T:ToValue> ToValue for Option<T> {
fn to_value(&self) -> Value {
match *self {
Some(ref v) => v.to_value(),
None => Value::new(VNull)
}
}
}
impl<T:FromValue> FromValue for Option<T> {
fn from_value(value:Value) -> Result<Option<T>, &'static str> {
Ok(if value.is_null_or_undefined() {
None
} else {
Some(try!(FromValue::from_value(value)))
})
}
}
/// A utility function that just calls FromValue::from_value
pub fn from_value<A: FromValue>(v: Value) -> Result<A, &'static str> {
FromValue::from_value(v)
}
/// A utility function that just calls ToValue::to_value
pub fn to_value<A: ToValue>(v: A) -> Value {
v.to_value()
}
|
#[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::RIS {
#[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 PWM_RIS_INTPWM0R {
bits: bool,
}
impl PWM_RIS_INTPWM0R {
#[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 _PWM_RIS_INTPWM0W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_RIS_INTPWM0W<'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 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_RIS_INTPWM1R {
bits: bool,
}
impl PWM_RIS_INTPWM1R {
#[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 _PWM_RIS_INTPWM1W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_RIS_INTPWM1W<'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 PWM_RIS_INTPWM2R {
bits: bool,
}
impl PWM_RIS_INTPWM2R {
#[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 _PWM_RIS_INTPWM2W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_RIS_INTPWM2W<'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 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_RIS_INTPWM3R {
bits: bool,
}
impl PWM_RIS_INTPWM3R {
#[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 _PWM_RIS_INTPWM3W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_RIS_INTPWM3W<'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 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_RIS_INTFAULT0R {
bits: bool,
}
impl PWM_RIS_INTFAULT0R {
#[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 _PWM_RIS_INTFAULT0W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_RIS_INTFAULT0W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 16);
self.w.bits |= ((value as u32) & 1) << 16;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_RIS_INTFAULT1R {
bits: bool,
}
impl PWM_RIS_INTFAULT1R {
#[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 _PWM_RIS_INTFAULT1W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_RIS_INTFAULT1W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits &= !(1 << 17);
self.w.bits |= ((value as u32) & 1) << 17;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_RIS_INTFAULT2R {
bits: bool,
}
impl PWM_RIS_INTFAULT2R {
#[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 _PWM_RIS_INTFAULT2W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_RIS_INTFAULT2W<'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 << 18);
self.w.bits |= ((value as u32) & 1) << 18;
self.w
}
}
#[doc = r"Value of the field"]
pub struct PWM_RIS_INTFAULT3R {
bits: bool,
}
impl PWM_RIS_INTFAULT3R {
#[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 _PWM_RIS_INTFAULT3W<'a> {
w: &'a mut W,
}
impl<'a> _PWM_RIS_INTFAULT3W<'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 << 19);
self.w.bits |= ((value as u32) & 1) << 19;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - PWM0 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_ris_intpwm0(&self) -> PWM_RIS_INTPWM0R {
let bits = ((self.bits >> 0) & 1) != 0;
PWM_RIS_INTPWM0R { bits }
}
#[doc = "Bit 1 - PWM1 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_ris_intpwm1(&self) -> PWM_RIS_INTPWM1R {
let bits = ((self.bits >> 1) & 1) != 0;
PWM_RIS_INTPWM1R { bits }
}
#[doc = "Bit 2 - PWM2 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_ris_intpwm2(&self) -> PWM_RIS_INTPWM2R {
let bits = ((self.bits >> 2) & 1) != 0;
PWM_RIS_INTPWM2R { bits }
}
#[doc = "Bit 3 - PWM3 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_ris_intpwm3(&self) -> PWM_RIS_INTPWM3R {
let bits = ((self.bits >> 3) & 1) != 0;
PWM_RIS_INTPWM3R { bits }
}
#[doc = "Bit 16 - Interrupt Fault PWM 0"]
#[inline(always)]
pub fn pwm_ris_intfault0(&self) -> PWM_RIS_INTFAULT0R {
let bits = ((self.bits >> 16) & 1) != 0;
PWM_RIS_INTFAULT0R { bits }
}
#[doc = "Bit 17 - Interrupt Fault PWM 1"]
#[inline(always)]
pub fn pwm_ris_intfault1(&self) -> PWM_RIS_INTFAULT1R {
let bits = ((self.bits >> 17) & 1) != 0;
PWM_RIS_INTFAULT1R { bits }
}
#[doc = "Bit 18 - Interrupt Fault PWM 2"]
#[inline(always)]
pub fn pwm_ris_intfault2(&self) -> PWM_RIS_INTFAULT2R {
let bits = ((self.bits >> 18) & 1) != 0;
PWM_RIS_INTFAULT2R { bits }
}
#[doc = "Bit 19 - Interrupt Fault PWM 3"]
#[inline(always)]
pub fn pwm_ris_intfault3(&self) -> PWM_RIS_INTFAULT3R {
let bits = ((self.bits >> 19) & 1) != 0;
PWM_RIS_INTFAULT3R { 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 0 - PWM0 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_ris_intpwm0(&mut self) -> _PWM_RIS_INTPWM0W {
_PWM_RIS_INTPWM0W { w: self }
}
#[doc = "Bit 1 - PWM1 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_ris_intpwm1(&mut self) -> _PWM_RIS_INTPWM1W {
_PWM_RIS_INTPWM1W { w: self }
}
#[doc = "Bit 2 - PWM2 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_ris_intpwm2(&mut self) -> _PWM_RIS_INTPWM2W {
_PWM_RIS_INTPWM2W { w: self }
}
#[doc = "Bit 3 - PWM3 Interrupt Asserted"]
#[inline(always)]
pub fn pwm_ris_intpwm3(&mut self) -> _PWM_RIS_INTPWM3W {
_PWM_RIS_INTPWM3W { w: self }
}
#[doc = "Bit 16 - Interrupt Fault PWM 0"]
#[inline(always)]
pub fn pwm_ris_intfault0(&mut self) -> _PWM_RIS_INTFAULT0W {
_PWM_RIS_INTFAULT0W { w: self }
}
#[doc = "Bit 17 - Interrupt Fault PWM 1"]
#[inline(always)]
pub fn pwm_ris_intfault1(&mut self) -> _PWM_RIS_INTFAULT1W {
_PWM_RIS_INTFAULT1W { w: self }
}
#[doc = "Bit 18 - Interrupt Fault PWM 2"]
#[inline(always)]
pub fn pwm_ris_intfault2(&mut self) -> _PWM_RIS_INTFAULT2W {
_PWM_RIS_INTFAULT2W { w: self }
}
#[doc = "Bit 19 - Interrupt Fault PWM 3"]
#[inline(always)]
pub fn pwm_ris_intfault3(&mut self) -> _PWM_RIS_INTFAULT3W {
_PWM_RIS_INTFAULT3W { w: self }
}
}
|
import libc::{c_char, c_int, c_long, size_t, time_t};
import io::{reader, reader_util};
import result::{result, ok, err, methods};
import std::time;
export
timespec,
get_time,
tm,
empty_tm,
now,
at,
now_utc,
at_utc,
strptime;
#[abi = "cdecl"]
#[nolink]
native mod libtime {
// FIXME: The i64 values can be passed by-val when #2064 is fixed.
fn tzset();
fn gmtime_r(&&sec: time_t, &&result: tm) -> *tm;
fn localtime_r(&&sec: time_t, &&result: tm) -> *tm;
fn timegm(&&tm: tm) -> time_t;
fn mktime(&&tm: tm) -> time_t;
}
#[doc = "A record specifying a time value in seconds and microseconds."]
type timespec = {sec: i64, nsec: i32};
#[doc = "
Returns the current time as a `timespec` containing the seconds and
microseconds since 1970-01-01T00:00:00Z.
"]
fn get_time() -> timespec {
let {sec, usec} = time::get_time();
{sec: sec as i64, nsec: usec as i32 * 1000_i32}
}
type tm = {
tm_sec: c_int, // seconds after the minute [0-60]
tm_min: c_int, // minutes after the hour [0-59]
tm_hour: c_int, // hours after midnight [0-23]
tm_mday: c_int, // days of the month [1-31]
tm_mon: c_int, // months since January [0-11]
tm_year: c_int, // years since 1900
tm_wday: c_int, // days since Sunday [0-6]
tm_yday: c_int, // days since January 1 [0-365]
tm_isdst: c_int, // Daylight Savings Time flag
tm_gmtoff: c_long, // offset from UTC in seconds
tm_zone: *c_char, // timezone abbreviation
tm_nsec: i32,
};
fn empty_tm() -> tm {
{
tm_sec: 0 as c_int,
tm_min: 0 as c_int,
tm_hour: 0 as c_int,
tm_mday: 0 as c_int,
tm_mon: 0 as c_int,
tm_year: 0 as c_int,
tm_wday: 0 as c_int,
tm_yday: 0 as c_int,
tm_isdst: 0 as c_int,
tm_gmtoff: 0 as c_long,
tm_zone: ptr::null(),
tm_nsec: 0_i32,
}
}
#[doc = "Returns the specified time in UTC"]
fn at_utc(clock: timespec) -> tm {
let mut sec = clock.sec as time_t;
let mut tm = empty_tm();
libtime::tzset();
libtime::gmtime_r(sec, tm);
{ tm_nsec: clock.nsec with tm }
}
#[doc = "Returns the current time in UTC"]
fn now_utc() -> tm {
at_utc(get_time())
}
#[doc = "Returns the specified time in the local timezone"]
fn at(clock: timespec) -> tm {
let mut sec = clock.sec as time_t;
let mut tm = empty_tm();
libtime::tzset();
libtime::localtime_r(sec, tm);
{ tm_nsec: clock.nsec with tm }
}
#[doc = "Returns the current time in the local timezone"]
fn now() -> tm {
at(get_time())
}
#[doc = "Parses the time from the string according to the format string."]
fn strptime(s: str, format: str) -> result<tm, str> {
type tm_mut = {
mut tm_sec: c_int,
mut tm_min: c_int,
mut tm_hour: c_int,
mut tm_mday: c_int,
mut tm_mon: c_int,
mut tm_year: c_int,
mut tm_wday: c_int,
mut tm_yday: c_int,
mut tm_isdst: c_int,
mut tm_gmtoff: c_long,
mut tm_zone: *c_char,
mut tm_nsec: i32,
};
fn match_str(s: str, pos: uint, needle: str) -> bool {
let mut i = pos;
for str::each(needle) {|ch|
if s[i] != ch {
ret false;
}
i += 1u;
}
ret true;
}
fn match_strs(s: str, pos: uint, strs: [(str, i32)])
-> option<(i32, uint)> {
let mut i = 0u;
let len = vec::len(strs);
while i < len {
let (needle, value) = strs[i];
if match_str(s, pos, needle) {
ret some((value, pos + str::len(needle)));
}
i += 1u;
}
none
}
fn match_digits(s: str, pos: uint, digits: uint, ws: bool)
-> option<(i32, uint)> {
let mut pos = pos;
let mut value = 0 as c_int;
let mut i = 0u;
while i < digits {
let {ch, next} = str::char_range_at(s, pos);
pos = next;
alt ch {
'0' to '9' {
value = value * 10 as c_int + (ch as i32 - '0' as i32);
}
' ' if ws { }
_ { ret none; }
}
i += 1u;
}
some((value, pos))
}
fn parse_char(s: str, pos: uint, c: char) -> result<uint, str> {
let {ch, next} = str::char_range_at(s, pos);
if c == ch {
ok(next)
} else {
err(#fmt("Expected %?, found %?",
str::from_char(c),
str::from_char(ch)))
}
}
fn parse_type(s: str, pos: uint, ch: char, tm: tm_mut)
-> result<uint, str> {
alt ch {
'A' {
alt match_strs(s, pos, [
("Sunday", 0 as c_int),
("Monday", 1 as c_int),
("Tuesday", 2 as c_int),
("Wednesday", 3 as c_int),
("Thursday", 4 as c_int),
("Friday", 5 as c_int),
("Saturday", 6 as c_int)
]) {
some(item) { let (v, pos) = item; tm.tm_wday = v; ok(pos) }
none { err("Invalid day") }
}
}
'a' {
alt match_strs(s, pos, [
("Sun", 0 as c_int),
("Mon", 1 as c_int),
("Tue", 2 as c_int),
("Wed", 3 as c_int),
("Thu", 4 as c_int),
("Fri", 5 as c_int),
("Sat", 6 as c_int)
]) {
some(item) { let (v, pos) = item; tm.tm_wday = v; ok(pos) }
none { err("Invalid day") }
}
}
'B' {
alt match_strs(s, pos, [
("January", 0 as c_int),
("February", 1 as c_int),
("March", 2 as c_int),
("April", 3 as c_int),
("May", 4 as c_int),
("June", 5 as c_int),
("July", 6 as c_int),
("August", 7 as c_int),
("September", 8 as c_int),
("October", 9 as c_int),
("November", 10 as c_int),
("December", 11 as c_int)
]) {
some(item) { let (v, pos) = item; tm.tm_mon = v; ok(pos) }
none { err("Invalid month") }
}
}
'b' | 'h' {
alt match_strs(s, pos, [
("Jan", 0 as c_int),
("Feb", 1 as c_int),
("Mar", 2 as c_int),
("Apr", 3 as c_int),
("May", 4 as c_int),
("Jun", 5 as c_int),
("Jul", 6 as c_int),
("Aug", 7 as c_int),
("Sep", 8 as c_int),
("Oct", 9 as c_int),
("Nov", 10 as c_int),
("Dec", 11 as c_int)
]) {
some(item) { let (v, pos) = item; tm.tm_mon = v; ok(pos) }
none { err("Invalid month") }
}
}
'C' {
alt match_digits(s, pos, 2u, false) {
some(item) {
let (v, pos) = item;
tm.tm_year += (v * 100 as c_int) - 1900 as c_int;
ok(pos)
}
none { err("Invalid year") }
}
}
'c' {
parse_type(s, pos, 'a', tm)
.chain { |pos| parse_char(s, pos, ' ') }
.chain { |pos| parse_type(s, pos, 'b', tm) }
.chain { |pos| parse_char(s, pos, ' ') }
.chain { |pos| parse_type(s, pos, 'e', tm) }
.chain { |pos| parse_char(s, pos, ' ') }
.chain { |pos| parse_type(s, pos, 'T', tm) }
.chain { |pos| parse_char(s, pos, ' ') }
.chain { |pos| parse_type(s, pos, 'Y', tm) }
}
'D' | 'x' {
parse_type(s, pos, 'm', tm)
.chain { |pos| parse_char(s, pos, '/') }
.chain { |pos| parse_type(s, pos, 'd', tm) }
.chain { |pos| parse_char(s, pos, '/') }
.chain { |pos| parse_type(s, pos, 'y', tm) }
}
'd' {
alt match_digits(s, pos, 2u, false) {
some(item) { let (v, pos) = item; tm.tm_mday = v; ok(pos) }
none { err("Invalid day of the month") }
}
}
'e' {
alt match_digits(s, pos, 2u, true) {
some(item) { let (v, pos) = item; tm.tm_mday = v; ok(pos) }
none { err("Invalid day of the month") }
}
}
'F' {
parse_type(s, pos, 'Y', tm)
.chain { |pos| parse_char(s, pos, '-') }
.chain { |pos| parse_type(s, pos, 'm', tm) }
.chain { |pos| parse_char(s, pos, '-') }
.chain { |pos| parse_type(s, pos, 'd', tm) }
}
'H' {
// FIXME: range check.
alt match_digits(s, pos, 2u, false) {
some(item) { let (v, pos) = item; tm.tm_hour = v; ok(pos) }
none { err("Invalid hour") }
}
}
'I' {
// FIXME: range check.
alt match_digits(s, pos, 2u, false) {
some(item) {
let (v, pos) = item;
tm.tm_hour = if v == 12 as c_int { 0 as c_int } else { v };
ok(pos)
}
none { err("Invalid hour") }
}
}
'j' {
// FIXME: range check.
alt match_digits(s, pos, 3u, false) {
some(item) {
let (v, pos) = item;
tm.tm_yday = v - 1 as c_int;
ok(pos)
}
none { err("Invalid year") }
}
}
'k' {
// FIXME: range check.
alt match_digits(s, pos, 2u, true) {
some(item) { let (v, pos) = item; tm.tm_hour = v; ok(pos) }
none { err("Invalid hour") }
}
}
'l' {
// FIXME: range check.
alt match_digits(s, pos, 2u, true) {
some(item) {
let (v, pos) = item;
tm.tm_hour = if v == 12 as c_int { 0 as c_int } else { v };
ok(pos)
}
none { err("Invalid hour") }
}
}
'M' {
// FIXME: range check.
alt match_digits(s, pos, 2u, false) {
some(item) { let (v, pos) = item; tm.tm_min = v; ok(pos) }
none { err("Invalid minute") }
}
}
'm' {
// FIXME: range check.
alt match_digits(s, pos, 2u, false) {
some(item) {
let (v, pos) = item;
tm.tm_mon = v - 1 as c_int;
ok(pos)
}
none { err("Invalid month") }
}
}
'n' { parse_char(s, pos, '\n') }
'P' {
alt match_strs(s, pos, [("am", 0 as c_int), ("pm", 12 as c_int)]) {
some(item) { let (v, pos) = item; tm.tm_hour += v; ok(pos) }
none { err("Invalid hour") }
}
}
'p' {
alt match_strs(s, pos, [("AM", 0 as c_int), ("PM", 12 as c_int)]) {
some(item) { let (v, pos) = item; tm.tm_hour += v; ok(pos) }
none { err("Invalid hour") }
}
}
'R' {
parse_type(s, pos, 'H', tm)
.chain { |pos| parse_char(s, pos, ':') }
.chain { |pos| parse_type(s, pos, 'M', tm) }
}
'r' {
parse_type(s, pos, 'I', tm)
.chain { |pos| parse_char(s, pos, ':') }
.chain { |pos| parse_type(s, pos, 'M', tm) }
.chain { |pos| parse_char(s, pos, ':') }
.chain { |pos| parse_type(s, pos, 'S', tm) }
.chain { |pos| parse_char(s, pos, ' ') }
.chain { |pos| parse_type(s, pos, 'p', tm) }
}
'S' {
// FIXME: range check.
alt match_digits(s, pos, 2u, false) {
some(item) {
let (v, pos) = item;
tm.tm_sec = v;
ok(pos)
}
none { err("Invalid second") }
}
}
//'s' {}
'T' | 'X' {
parse_type(s, pos, 'H', tm)
.chain { |pos| parse_char(s, pos, ':') }
.chain { |pos| parse_type(s, pos, 'M', tm) }
.chain { |pos| parse_char(s, pos, ':') }
.chain { |pos| parse_type(s, pos, 'S', tm) }
}
't' { parse_char(s, pos, '\t') }
'u' {
// FIXME: range check.
alt match_digits(s, pos, 1u, false) {
some(item) {
let (v, pos) = item;
tm.tm_wday = v;
ok(pos)
}
none { err("Invalid weekday") }
}
}
'v' {
parse_type(s, pos, 'e', tm)
.chain { |pos| parse_char(s, pos, '-') }
.chain { |pos| parse_type(s, pos, 'b', tm) }
.chain { |pos| parse_char(s, pos, '-') }
.chain { |pos| parse_type(s, pos, 'Y', tm) }
}
//'W' {}
'w' {
// FIXME: range check.
alt match_digits(s, pos, 1u, false) {
some(item) { let (v, pos) = item; tm.tm_wday = v; ok(pos) }
none { err("Invalid weekday") }
}
}
//'X' {}
//'x' {}
'Y' {
// FIXME: range check.
alt match_digits(s, pos, 4u, false) {
some(item) {
let (v, pos) = item;
tm.tm_year = v - 1900 as c_int;
ok(pos)
}
none { err("Invalid weekday") }
}
}
'y' {
// FIXME: range check.
alt match_digits(s, pos, 2u, false) {
some(item) {
let (v, pos) = item;
tm.tm_year = v - 1900 as c_int;
ok(pos)
}
none { err("Invalid weekday") }
}
}
'Z' {
if match_str(s, pos, "UTC") || match_str(s, pos, "GMT") {
tm.tm_gmtoff = 0 as c_long;
// FIXME: this should be "UTC"
tm.tm_zone = ptr::null();
ok(pos + 3u)
} else {
// It's odd, but to maintain compatibility with c's
// strptime we ignore the timezone.
let mut pos = pos;
let len = str::len(s);
while pos < len {
let {ch, next} = str::char_range_at(s, pos);
pos = next;
if ch == ' ' { break; }
}
ok(pos)
}
}
'z' {
let {ch, next} = str::char_range_at(s, pos);
if ch == '+' || ch == '-' {
alt match_digits(s, next, 4u, false) {
some(item) {
let (v, pos) = item;
if v == 0 as c_int {
tm.tm_gmtoff = 0 as c_long;
// FIXME: this should be UTC
tm.tm_zone = ptr::null();
}
ok(pos)
}
none { err("Invalid zone offset") }
}
} else {
err("Invalid zone offset")
}
}
'%' { parse_char(s, pos, '%') }
ch {
err(#fmt("unknown formatting type: %?", str::from_char(ch)))
}
}
}
io::with_str_reader(format) { |rdr|
let tm = {
mut tm_sec: 0 as c_int,
mut tm_min: 0 as c_int,
mut tm_hour: 0 as c_int,
mut tm_mday: 0 as c_int,
mut tm_mon: 0 as c_int,
mut tm_year: 0 as c_int,
mut tm_wday: 0 as c_int,
mut tm_yday: 0 as c_int,
mut tm_isdst: 0 as c_int,
mut tm_gmtoff: 0 as c_long,
mut tm_zone: ptr::null(),
mut tm_nsec: 0i32,
};
let mut pos = 0u;
let len = str::len(s);
let mut result = err("Invalid time");
while !rdr.eof() && pos < len {
let {ch, next} = str::char_range_at(s, pos);
alt rdr.read_char() {
'%' {
alt parse_type(s, pos, rdr.read_char(), tm) {
ok(next) { pos = next; }
err(e) { result = err(e); break; }
}
}
c {
if c != ch { break }
pos = next;
}
}
}
if pos == len && rdr.eof() {
ok({
tm_sec: tm.tm_sec,
tm_min: tm.tm_min,
tm_hour: tm.tm_hour,
tm_mday: tm.tm_mday,
tm_mon: tm.tm_mon,
tm_year: tm.tm_year,
tm_wday: tm.tm_wday,
tm_yday: tm.tm_yday,
tm_isdst: tm.tm_isdst,
tm_gmtoff: tm.tm_gmtoff,
tm_zone: tm.tm_zone,
tm_nsec: tm.tm_nsec,
})
} else { result }
}
}
fn strftime(format: str, tm: tm) -> str {
fn parse_type(ch: char, tm: tm) -> str {
//FIXME: Implement missing types.
alt check ch {
'A' {
alt check tm.tm_wday as int {
0 { "Sunday" }
1 { "Monday" }
2 { "Tuesday" }
3 { "Wednesday" }
4 { "Thursday" }
5 { "Friday" }
6 { "Saturday" }
}
}
'a' {
alt check tm.tm_wday as int {
0 { "Sun" }
1 { "Mon" }
2 { "Tue" }
3 { "Wed" }
4 { "Thu" }
5 { "Fri" }
6 { "Sat" }
}
}
'B' {
alt check tm.tm_mon as int {
0 { "January" }
1 { "February" }
2 { "March" }
3 { "April" }
4 { "May" }
5 { "June" }
6 { "July" }
7 { "August" }
8 { "September" }
9 { "October" }
10 { "November" }
11 { "December" }
}
}
'b' | 'h' {
alt check tm.tm_mon as int {
0 { "Jan" }
1 { "Feb" }
2 { "Mar" }
3 { "Apr" }
4 { "May" }
5 { "Jun" }
6 { "Jul" }
7 { "Aug" }
8 { "Sep" }
9 { "Oct" }
10 { "Nov" }
11 { "Dec" }
}
}
'C' { #fmt("%02d", (tm.tm_year as int + 1900) / 100) }
'c' {
#fmt("%s %s %s %s %s",
parse_type('a', tm),
parse_type('b', tm),
parse_type('e', tm),
parse_type('T', tm),
parse_type('Y', tm))
}
'D' | 'x' {
#fmt("%s/%s/%s",
parse_type('m', tm),
parse_type('d', tm),
parse_type('y', tm))
}
'd' { #fmt("%02d", tm.tm_mday as int) }
'e' { #fmt("%2d", tm.tm_mday as int) }
'F' {
#fmt("%s-%s-%s",
parse_type('Y', tm),
parse_type('m', tm),
parse_type('d', tm))
}
//'G' {}
//'g' {}
'H' { #fmt("%02d", tm.tm_hour as int) }
'I' {
let mut h = tm.tm_hour as int;
if h == 0 { h = 12 }
if h > 12 { h -= 12 }
#fmt("%02d", h)
}
'j' { #fmt("%03d", tm.tm_yday as int + 1) }
'k' { #fmt("%2d", tm.tm_hour as int) }
'l' {
let mut h = tm.tm_hour as int;
if h == 0 { h = 12 }
if h > 12 { h -= 12 }
#fmt("%2d", h)
}
'M' { #fmt("%02d", tm.tm_min as int) }
'm' { #fmt("%02d", tm.tm_mon as int + 1) }
'n' { "\n" }
'P' { if tm.tm_hour as int < 12 { "am" } else { "pm" } }
'p' { if tm.tm_hour as int < 12 { "AM" } else { "PM" } }
'R' {
#fmt("%s:%s",
parse_type('H', tm),
parse_type('M', tm))
}
'r' {
#fmt("%s:%s:%s %s",
parse_type('I', tm),
parse_type('M', tm),
parse_type('S', tm),
parse_type('p', tm))
}
'S' { #fmt("%02d", tm.tm_sec as int) }
's' { #fmt("%d", tm.to_timespec().sec as int) }
'T' | 'X' {
#fmt("%s:%s:%s",
parse_type('H', tm),
parse_type('M', tm),
parse_type('S', tm))
}
't' { "\t" }
//'U' {}
'u' {
let i = tm.tm_wday as int;
int::str(if i == 0 { 7 } else { i })
}
//'V' {}
'v' {
#fmt("%s-%s-%s",
parse_type('e', tm),
parse_type('b', tm),
parse_type('Y', tm))
}
//'W' {}
'w' { int::str(tm.tm_wday as int) }
//'X' {}
//'x' {}
'Y' { int::str(tm.tm_year as int + 1900) }
'y' { #fmt("%02d", (tm.tm_year as int + 1900) % 100) }
'Z' {
if tm.tm_zone == ptr::null() {
""
} else {
unsafe { str::unsafe::from_c_str(tm.tm_zone) }
}
}
'z' {
let gmtoff = tm.tm_gmtoff as i32;
let sign = if gmtoff > 0_i32 { '+' } else { '-' };
let mut m = i32::abs(gmtoff) / 60_i32;
let h = m / 60_i32;
m -= h * 60_i32;
#fmt("%c%02d%02d", sign, h as int, m as int)
}
//'+' {}
'%' { "%" }
}
}
let mut buf = "";
io::with_str_reader(format) { |rdr|
while !rdr.eof() {
alt rdr.read_char() {
'%' { buf += parse_type(rdr.read_char(), tm); }
ch { str::push_char(buf, ch); }
}
}
}
buf
}
impl tm for tm {
#[doc = "Convert time to the seconds from January 1, 1970"]
fn to_timespec() -> timespec {
let sec = if self.tm_gmtoff == 0 as c_long {
libtime::timegm(self) as i64
} else {
libtime::mktime(self) as i64
};
{ sec: sec, nsec: self.tm_nsec }
}
#[doc = "Convert time to the local timezone"]
fn to_local() -> tm {
at(self.to_timespec())
}
#[doc = "Convert time to the UTC"]
fn to_utc() -> tm {
at_utc(self.to_timespec())
}
#[doc = "
Return a string of the current time in the form
\"Thu Jan 1 00:00:00 1970\".
"]
fn ctime() -> str { self.strftime("%c") }
#[doc = "Formats the time according to the format string."]
fn strftime(format: str) -> str { strftime(format, self) }
#[doc = "
Returns a time string formatted according to RFC 822.
local: \"Thu, 22 Mar 2012 07:53:18 PST\"
utc: \"Thu, 22 Mar 2012 14:53:18 UTC\"
"]
fn rfc822() -> str {
if self.tm_gmtoff == 0 as c_long {
self.strftime("%a, %d %b %Y %T GMT")
} else {
self.strftime("%a, %d %b %Y %T %Z")
}
}
#[doc = "
Returns a time string formatted according to RFC 822 with Zulu time.
local: \"Thu, 22 Mar 2012 07:53:18 -0700\"
utc: \"Thu, 22 Mar 2012 14:53:18 -0000\"
"]
fn rfc822z() -> str {
self.strftime("%a, %d %b %Y %T %z")
}
#[doc = "
Returns a time string formatted according to ISO 8601.
local: \"2012-02-22T07:53:18-07:00\"
utc: \"2012-02-22T14:53:18Z\"
"]
fn rfc3339() -> str {
if self.tm_gmtoff == 0 as c_long{
self.strftime("%Y-%m-%dT%H:%M:%SZ")
} else {
let s = self.strftime("%Y-%m-%dT%H:%M:%S");
let gmtoff = self.tm_gmtoff as i32;
let sign = if gmtoff > 0_i32 { '+' } else { '-' };
let mut m = i32::abs(gmtoff) / 60_i32;
let h = m / 60_i32;
m -= h * 60_i32;
s + #fmt("%c%02d:%02d", sign, h as int, m as int)
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn test_at_utc() {
os::setenv("TZ", "America/Los_Angeles");
let time = { sec: 1234567890_i64, nsec: 54321_i32 };
let utc = at_utc(time);
assert utc.tm_sec == 30 as c_int;
assert utc.tm_min == 31 as c_int;
assert utc.tm_hour == 23 as c_int;
assert utc.tm_mday == 13 as c_int;
assert utc.tm_mon == 1 as c_int;
assert utc.tm_year == 109 as c_int;
assert utc.tm_wday == 5 as c_int;
assert utc.tm_yday == 43 as c_int;
assert utc.tm_isdst == 0 as c_int;
assert utc.tm_gmtoff == 0 as c_long;
assert utc.tm_zone != ptr::null();
assert unsafe { str::unsafe::from_c_str(utc.tm_zone) } == "UTC";
assert utc.tm_nsec == 54321_i32;
}
#[test]
fn test_at() {
os::setenv("TZ", "America/Los_Angeles");
let time = { sec: 1234567890_i64, nsec: 54321_i32 };
let local = at(time);
assert local.tm_sec == 30 as c_int;
assert local.tm_min == 31 as c_int;
assert local.tm_hour == 15 as c_int;
assert local.tm_mday == 13 as c_int;
assert local.tm_mon == 1 as c_int;
assert local.tm_year == 109 as c_int;
assert local.tm_wday == 5 as c_int;
assert local.tm_yday == 43 as c_int;
assert local.tm_isdst == 0 as c_int;
assert local.tm_gmtoff == -28800 as c_long;
assert local.tm_zone != ptr::null();
assert unsafe { str::unsafe::from_c_str(local.tm_zone) } == "PST";
assert local.tm_nsec == 54321_i32;
}
#[test]
fn test_to_timespec() {
os::setenv("TZ", "America/Los_Angeles");
let time = { sec: 1234567890_i64, nsec: 54321_i32 };
let utc = at_utc(time);
assert utc.to_timespec() == time;
assert utc.to_local().to_timespec() == time;
}
#[test]
fn test_conversions() {
os::setenv("TZ", "America/Los_Angeles");
let time = { sec: 1234567890_i64, nsec: 54321_i32 };
let utc = at_utc(time);
let local = at(time);
assert local.to_local() == local;
assert local.to_utc() == utc;
assert local.to_utc().to_local() == local;
assert utc.to_utc() == utc;
assert utc.to_local() == local;
assert utc.to_local().to_utc() == utc;
}
#[test]
fn test_strptime() {
os::setenv("TZ", "America/Los_Angeles");
alt strptime("", "") {
ok(tm) {
assert tm.tm_sec == 0 as c_int;
assert tm.tm_min == 0 as c_int;
assert tm.tm_hour == 0 as c_int;
assert tm.tm_mday == 0 as c_int;
assert tm.tm_mon == 0 as c_int;
assert tm.tm_year == 0 as c_int;
assert tm.tm_wday == 0 as c_int;
assert tm.tm_isdst== 0 as c_int;
assert tm.tm_gmtoff == 0 as c_long;
assert tm.tm_zone == ptr::null();
assert tm.tm_nsec == 0_i32;
}
err(_) {}
}
let format = "%a %b %e %T %Y";
assert strptime("", format) == err("Invalid time");
assert strptime("Fri Feb 13 15:31:30", format) == err("Invalid time");
alt strptime("Fri Feb 13 15:31:30 2009", format) {
err(e) { fail e }
ok(tm) {
assert tm.tm_sec == 30 as c_int;
assert tm.tm_min == 31 as c_int;
assert tm.tm_hour == 15 as c_int;
assert tm.tm_mday == 13 as c_int;
assert tm.tm_mon == 1 as c_int;
assert tm.tm_year == 109 as c_int;
assert tm.tm_wday == 5 as c_int;
assert tm.tm_yday == 0 as c_int;
assert tm.tm_isdst == 0 as c_int;
assert tm.tm_gmtoff == 0 as c_long;
assert tm.tm_zone == ptr::null();
assert tm.tm_nsec == 0_i32;
}
}
fn test(s: str, format: str) -> bool {
alt strptime(s, format) {
ok(tm) { tm.strftime(format) == s }
err(e) { fail e }
}
}
vec::iter([
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
]) { |day| assert test(day, "%A"); }
vec::iter([
"Sun",
"Mon",
"Tue",
"Wed",
"Thu",
"Fri",
"Sat"
]) { |day| assert test(day, "%a"); }
vec::iter([
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
]) { |day| assert test(day, "%B"); }
vec::iter([
"Jan",
"Feb",
"Mar",
"Apr",
"May",
"Jun",
"Jul",
"Aug",
"Sep",
"Oct",
"Nov",
"Dec"
]) { |day| assert test(day, "%b"); }
assert test("19", "%C");
assert test("Fri Feb 13 23:31:30 2009", "%c");
assert test("02/13/09", "%D");
assert test("03", "%d");
assert test("13", "%d");
assert test(" 3", "%e");
assert test("13", "%e");
assert test("2009-02-13", "%F");
assert test("03", "%H");
assert test("13", "%H");
assert test("03", "%I"); // FIXME: flesh out
assert test("11", "%I"); // FIXME: flesh out
assert test("044", "%j");
assert test(" 3", "%k");
assert test("13", "%k");
assert test(" 1", "%l");
assert test("11", "%l");
assert test("03", "%M");
assert test("13", "%M");
assert test("\n", "%n");
assert test("am", "%P");
assert test("pm", "%P");
assert test("AM", "%p");
assert test("PM", "%p");
assert test("23:31", "%R");
assert test("11:31:30 AM", "%r");
assert test("11:31:30 PM", "%r");
assert test("03", "%S");
assert test("13", "%S");
assert test("15:31:30", "%T");
assert test("\t", "%t");
assert test("1", "%u");
assert test("7", "%u");
assert test("13-Feb-2009", "%v");
assert test("0", "%w");
assert test("6", "%w");
assert test("2009", "%Y");
assert test("09", "%y");
//FIXME
assert result::get(strptime("UTC", "%Z")).tm_zone == ptr::null();
assert result::get(strptime("PST", "%Z")).tm_zone == ptr::null();
assert result::get(strptime("-0000", "%z")).tm_gmtoff == 0 as c_long;
assert result::get(strptime("-0800", "%z")).tm_gmtoff == 0 as c_long;
assert test("%", "%%");
}
#[test]
fn test_ctime() {
os::setenv("TZ", "America/Los_Angeles");
let time = { sec: 1234567890_i64, nsec: 54321_i32 };
let utc = at_utc(time);
let local = at(time);
assert utc.ctime() == "Fri Feb 13 23:31:30 2009";
assert local.ctime() == "Fri Feb 13 15:31:30 2009";
}
#[test]
fn test_strftime() {
os::setenv("TZ", "America/Los_Angeles");
let time = { sec: 1234567890_i64, nsec: 54321_i32 };
let utc = at_utc(time);
let local = at(time);
assert local.strftime("") == "";
assert local.strftime("%A") == "Friday";
assert local.strftime("%a") == "Fri";
assert local.strftime("%B") == "February";
assert local.strftime("%b") == "Feb";
assert local.strftime("%C") == "20";
assert local.strftime("%c") == "Fri Feb 13 15:31:30 2009";
assert local.strftime("%D") == "02/13/09";
assert local.strftime("%d") == "13";
assert local.strftime("%e") == "13";
assert local.strftime("%F") == "2009-02-13";
// assert local.strftime("%G") == "2009";
// assert local.strftime("%g") == "09";
assert local.strftime("%H") == "15";
assert local.strftime("%I") == "03";
assert local.strftime("%j") == "044";
assert local.strftime("%k") == "15";
assert local.strftime("%l") == " 3";
assert local.strftime("%M") == "31";
assert local.strftime("%m") == "02";
assert local.strftime("%n") == "\n";
assert local.strftime("%P") == "pm";
assert local.strftime("%p") == "PM";
assert local.strftime("%R") == "15:31";
assert local.strftime("%r") == "03:31:30 PM";
assert local.strftime("%S") == "30";
assert local.strftime("%s") == "1234567890";
assert local.strftime("%T") == "15:31:30";
assert local.strftime("%t") == "\t";
// assert local.strftime("%U") == "06";
assert local.strftime("%u") == "5";
// assert local.strftime("%V") == "07";
assert local.strftime("%v") == "13-Feb-2009";
// assert local.strftime("%W") == "06";
assert local.strftime("%w") == "5";
// handle "%X"
// handle "%x"
assert local.strftime("%Y") == "2009";
assert local.strftime("%y") == "09";
// FIXME: We should probably standardize on the timezone
// abbreviation.
let zone = local.strftime("%Z");
assert zone == "PST" || zone == "Pacific Standard Time";
assert local.strftime("%z") == "-0800";
assert local.strftime("%%") == "%";
// FIXME: We should probably standardize on the timezone
// abbreviation.
let rfc822 = local.rfc822();
let prefix = "Fri, 13 Feb 2009 15:31:30 ";
assert rfc822 == prefix + "PST" ||
rfc822 == prefix + "Pacific Standard Time";
assert local.ctime() == "Fri Feb 13 15:31:30 2009";
assert local.rfc822z() == "Fri, 13 Feb 2009 15:31:30 -0800";
assert local.rfc3339() == "2009-02-13T15:31:30-08:00";
assert utc.ctime() == "Fri Feb 13 23:31:30 2009";
assert utc.rfc822() == "Fri, 13 Feb 2009 23:31:30 GMT";
assert utc.rfc822z() == "Fri, 13 Feb 2009 23:31:30 -0000";
assert utc.rfc3339() == "2009-02-13T23:31:30Z";
}
}
|
// Copyright 2021 Datafuse Labs.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use std::hash::Hash;
use std::hash::Hasher;
use num_traits::FromPrimitive;
use roaring::RoaringBitmap;
use crate::optimizer::rule::RuleID;
/// Set of `Rule`
#[derive(Debug, Clone, PartialEq, Default)]
pub struct RuleSet {
rules: RoaringBitmap,
}
impl RuleSet {
pub fn create() -> Self {
RuleSet {
rules: RoaringBitmap::new(),
}
}
pub fn create_with_ids(ids: Vec<RuleID>) -> Self {
let mut rule_set = Self::create();
for id in ids {
rule_set.rules.insert(id as u32);
}
rule_set
}
pub fn insert(&mut self, id: RuleID) {
self.rules.insert(id as u32);
}
pub fn contains(&self, id: &RuleID) -> bool {
self.rules.contains(*id as u32)
}
pub fn remove(&mut self, id: &RuleID) {
self.rules.remove(*id as u32);
}
pub fn intersect(&self, other: &RuleSet) -> RuleSet {
let mut rule_set = Self::create();
rule_set.rules = self.rules.clone() & other.rules.clone();
rule_set
}
pub fn iter(&self) -> impl Iterator<Item = RuleID> + '_ {
self.rules.iter().map(|v| RuleID::from_u32(v).unwrap())
}
}
/// A bitmap to store information about applied rules
#[derive(Debug, Clone, PartialEq, Default)]
pub struct AppliedRules {
rules: RuleSet,
}
impl AppliedRules {
pub fn set(&mut self, id: &RuleID, v: bool) {
if v {
self.rules.insert(*id);
} else {
self.rules.remove(id);
}
}
pub fn get(&self, id: &RuleID) -> bool {
self.rules.contains(id)
}
}
impl Hash for AppliedRules {
fn hash<H: Hasher>(&self, state: &mut H) {
self.rules.iter().for_each(|id| id.hash(state))
}
}
|
#[doc = "Reader of register APB4LPENR"]
pub type R = crate::R<u32, super::APB4LPENR>;
#[doc = "Writer for register APB4LPENR"]
pub type W = crate::W<u32, super::APB4LPENR>;
#[doc = "Register APB4LPENR `reset()`'s with value 0"]
impl crate::ResetValue for super::APB4LPENR {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "SYSCFG peripheral clock enable during CSleep mode\n\nValue on reset: 0"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum SYSCFGLPEN_A {
#[doc = "0: The selected clock is disabled during csleep mode"]
DISABLED = 0,
#[doc = "1: The selected clock is enabled during csleep mode"]
ENABLED = 1,
}
impl From<SYSCFGLPEN_A> for bool {
#[inline(always)]
fn from(variant: SYSCFGLPEN_A) -> Self {
variant as u8 != 0
}
}
#[doc = "Reader of field `SYSCFGLPEN`"]
pub type SYSCFGLPEN_R = crate::R<bool, SYSCFGLPEN_A>;
impl SYSCFGLPEN_R {
#[doc = r"Get enumerated values variant"]
#[inline(always)]
pub fn variant(&self) -> SYSCFGLPEN_A {
match self.bits {
false => SYSCFGLPEN_A::DISABLED,
true => SYSCFGLPEN_A::ENABLED,
}
}
#[doc = "Checks if the value of the field is `DISABLED`"]
#[inline(always)]
pub fn is_disabled(&self) -> bool {
*self == SYSCFGLPEN_A::DISABLED
}
#[doc = "Checks if the value of the field is `ENABLED`"]
#[inline(always)]
pub fn is_enabled(&self) -> bool {
*self == SYSCFGLPEN_A::ENABLED
}
}
#[doc = "Write proxy for field `SYSCFGLPEN`"]
pub struct SYSCFGLPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SYSCFGLPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SYSCFGLPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 1)) | (((value as u32) & 0x01) << 1);
self.w
}
}
#[doc = "LPUART1 Peripheral Clocks Enable During CSleep Mode"]
pub type LPUART1LPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `LPUART1LPEN`"]
pub type LPUART1LPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `LPUART1LPEN`"]
pub struct LPUART1LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> LPUART1LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPUART1LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 3)) | (((value as u32) & 0x01) << 3);
self.w
}
}
#[doc = "SPI6 Peripheral Clocks Enable During CSleep Mode"]
pub type SPI6LPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `SPI6LPEN`"]
pub type SPI6LPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `SPI6LPEN`"]
pub struct SPI6LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SPI6LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SPI6LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 5)) | (((value as u32) & 0x01) << 5);
self.w
}
}
#[doc = "I2C4 Peripheral Clocks Enable During CSleep Mode"]
pub type I2C4LPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `I2C4LPEN`"]
pub type I2C4LPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `I2C4LPEN`"]
pub struct I2C4LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> I2C4LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: I2C4LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "LPTIM2 Peripheral Clocks Enable During CSleep Mode"]
pub type LPTIM2LPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `LPTIM2LPEN`"]
pub type LPTIM2LPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `LPTIM2LPEN`"]
pub struct LPTIM2LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM2LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM2LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "LPTIM3 Peripheral Clocks Enable During CSleep Mode"]
pub type LPTIM3LPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `LPTIM3LPEN`"]
pub type LPTIM3LPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `LPTIM3LPEN`"]
pub struct LPTIM3LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM3LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM3LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "LPTIM4 Peripheral Clocks Enable During CSleep Mode"]
pub type LPTIM4LPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `LPTIM4LPEN`"]
pub type LPTIM4LPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `LPTIM4LPEN`"]
pub struct LPTIM4LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM4LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM4LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "LPTIM5 Peripheral Clocks Enable During CSleep Mode"]
pub type LPTIM5LPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `LPTIM5LPEN`"]
pub type LPTIM5LPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `LPTIM5LPEN`"]
pub struct LPTIM5LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> LPTIM5LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: LPTIM5LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "COMP1/2 peripheral clock enable during CSleep mode"]
pub type COMP12LPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `COMP12LPEN`"]
pub type COMP12LPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `COMP12LPEN`"]
pub struct COMP12LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> COMP12LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: COMP12LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "VREF peripheral clock enable during CSleep mode"]
pub type VREFLPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `VREFLPEN`"]
pub type VREFLPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `VREFLPEN`"]
pub struct VREFLPEN_W<'a> {
w: &'a mut W,
}
impl<'a> VREFLPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: VREFLPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "RTC APB Clock Enable During CSleep Mode"]
pub type RTCAPBLPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `RTCAPBLPEN`"]
pub type RTCAPBLPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `RTCAPBLPEN`"]
pub struct RTCAPBLPEN_W<'a> {
w: &'a mut W,
}
impl<'a> RTCAPBLPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: RTCAPBLPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "SAI4 Peripheral Clocks Enable During CSleep Mode"]
pub type SAI4LPEN_A = SYSCFGLPEN_A;
#[doc = "Reader of field `SAI4LPEN`"]
pub type SAI4LPEN_R = crate::R<bool, SYSCFGLPEN_A>;
#[doc = "Write proxy for field `SAI4LPEN`"]
pub struct SAI4LPEN_W<'a> {
w: &'a mut W,
}
impl<'a> SAI4LPEN_W<'a> {
#[doc = r"Writes `variant` to the field"]
#[inline(always)]
pub fn variant(self, variant: SAI4LPEN_A) -> &'a mut W {
{
self.bit(variant.into())
}
}
#[doc = "The selected clock is disabled during csleep mode"]
#[inline(always)]
pub fn disabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::DISABLED)
}
#[doc = "The selected clock is enabled during csleep mode"]
#[inline(always)]
pub fn enabled(self) -> &'a mut W {
self.variant(SYSCFGLPEN_A::ENABLED)
}
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
impl R {
#[doc = "Bit 1 - SYSCFG peripheral clock enable during CSleep mode"]
#[inline(always)]
pub fn syscfglpen(&self) -> SYSCFGLPEN_R {
SYSCFGLPEN_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 3 - LPUART1 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lpuart1lpen(&self) -> LPUART1LPEN_R {
LPUART1LPEN_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 5 - SPI6 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn spi6lpen(&self) -> SPI6LPEN_R {
SPI6LPEN_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 7 - I2C4 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn i2c4lpen(&self) -> I2C4LPEN_R {
I2C4LPEN_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 9 - LPTIM2 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lptim2lpen(&self) -> LPTIM2LPEN_R {
LPTIM2LPEN_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - LPTIM3 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lptim3lpen(&self) -> LPTIM3LPEN_R {
LPTIM3LPEN_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - LPTIM4 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lptim4lpen(&self) -> LPTIM4LPEN_R {
LPTIM4LPEN_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - LPTIM5 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lptim5lpen(&self) -> LPTIM5LPEN_R {
LPTIM5LPEN_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 14 - COMP1/2 peripheral clock enable during CSleep mode"]
#[inline(always)]
pub fn comp12lpen(&self) -> COMP12LPEN_R {
COMP12LPEN_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - VREF peripheral clock enable during CSleep mode"]
#[inline(always)]
pub fn vreflpen(&self) -> VREFLPEN_R {
VREFLPEN_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - RTC APB Clock Enable During CSleep Mode"]
#[inline(always)]
pub fn rtcapblpen(&self) -> RTCAPBLPEN_R {
RTCAPBLPEN_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 21 - SAI4 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn sai4lpen(&self) -> SAI4LPEN_R {
SAI4LPEN_R::new(((self.bits >> 21) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 1 - SYSCFG peripheral clock enable during CSleep mode"]
#[inline(always)]
pub fn syscfglpen(&mut self) -> SYSCFGLPEN_W {
SYSCFGLPEN_W { w: self }
}
#[doc = "Bit 3 - LPUART1 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lpuart1lpen(&mut self) -> LPUART1LPEN_W {
LPUART1LPEN_W { w: self }
}
#[doc = "Bit 5 - SPI6 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn spi6lpen(&mut self) -> SPI6LPEN_W {
SPI6LPEN_W { w: self }
}
#[doc = "Bit 7 - I2C4 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn i2c4lpen(&mut self) -> I2C4LPEN_W {
I2C4LPEN_W { w: self }
}
#[doc = "Bit 9 - LPTIM2 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lptim2lpen(&mut self) -> LPTIM2LPEN_W {
LPTIM2LPEN_W { w: self }
}
#[doc = "Bit 10 - LPTIM3 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lptim3lpen(&mut self) -> LPTIM3LPEN_W {
LPTIM3LPEN_W { w: self }
}
#[doc = "Bit 11 - LPTIM4 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lptim4lpen(&mut self) -> LPTIM4LPEN_W {
LPTIM4LPEN_W { w: self }
}
#[doc = "Bit 12 - LPTIM5 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn lptim5lpen(&mut self) -> LPTIM5LPEN_W {
LPTIM5LPEN_W { w: self }
}
#[doc = "Bit 14 - COMP1/2 peripheral clock enable during CSleep mode"]
#[inline(always)]
pub fn comp12lpen(&mut self) -> COMP12LPEN_W {
COMP12LPEN_W { w: self }
}
#[doc = "Bit 15 - VREF peripheral clock enable during CSleep mode"]
#[inline(always)]
pub fn vreflpen(&mut self) -> VREFLPEN_W {
VREFLPEN_W { w: self }
}
#[doc = "Bit 16 - RTC APB Clock Enable During CSleep Mode"]
#[inline(always)]
pub fn rtcapblpen(&mut self) -> RTCAPBLPEN_W {
RTCAPBLPEN_W { w: self }
}
#[doc = "Bit 21 - SAI4 Peripheral Clocks Enable During CSleep Mode"]
#[inline(always)]
pub fn sai4lpen(&mut self) -> SAI4LPEN_W {
SAI4LPEN_W { w: self }
}
}
|
//! Metric instrumentation for a [`NamespaceCache`] implementation.
use std::sync::Arc;
use async_trait::async_trait;
use data_types::{NamespaceName, NamespaceSchema};
use iox_time::{SystemProvider, TimeProvider};
use metric::{DurationHistogram, Metric, U64Gauge};
use super::{ChangeStats, NamespaceCache};
/// An [`InstrumentedCache`] decorates a [`NamespaceCache`] with cache read
/// hit/miss and cache put insert/update metrics.
#[derive(Debug)]
pub struct InstrumentedCache<T, P = SystemProvider> {
inner: T,
time_provider: P,
/// Metrics derived from the [`NamespaceSchema`] held within the cache.
table_count: U64Gauge,
column_count: U64Gauge,
/// A cache read hit
get_hit: DurationHistogram,
/// A cache read miss
get_miss: DurationHistogram,
/// A cache put for a namespace that did not previously exist in the cache
put_insert: DurationHistogram,
/// A cache put for a namespace that previously had a cache entry
put_update: DurationHistogram,
}
impl<T> InstrumentedCache<T> {
/// Instrument `T`, recording cache operations to `registry`.
pub fn new(inner: T, registry: &metric::Registry) -> Self {
let get_counter: Metric<DurationHistogram> =
registry.register_metric("namespace_cache_get_duration", "cache read call duration");
let get_hit = get_counter.recorder(&[("result", "hit")]);
let get_miss = get_counter.recorder(&[("result", "miss")]);
let put_counter: Metric<DurationHistogram> =
registry.register_metric("namespace_cache_put_duration", "cache put call duration");
let put_insert = put_counter.recorder(&[("op", "insert")]);
let put_update = put_counter.recorder(&[("op", "update")]);
let table_count = registry
.register_metric::<U64Gauge>(
"namespace_cache_table_count",
"number of tables in the cache across all namespaces",
)
.recorder([]);
let column_count = registry
.register_metric::<U64Gauge>(
"namespace_cache_column_count",
"number of columns in the cache across all tables and namespaces",
)
.recorder([]);
Self {
inner,
time_provider: Default::default(),
table_count,
column_count,
get_hit,
get_miss,
put_insert,
put_update,
}
}
}
#[async_trait]
impl<T, P> NamespaceCache for Arc<InstrumentedCache<T, P>>
where
T: NamespaceCache,
P: TimeProvider,
{
type ReadError = T::ReadError;
async fn get_schema(
&self,
namespace: &NamespaceName<'static>,
) -> Result<Arc<NamespaceSchema>, Self::ReadError> {
let t = self.time_provider.now();
let res = self.inner.get_schema(namespace).await;
// Avoid exploding if time goes backwards - simply drop the measurement
// if it happens.
if let Some(delta) = self.time_provider.now().checked_duration_since(t) {
match &res {
Ok(_) => self.get_hit.record(delta),
Err(_) => self.get_miss.record(delta),
};
}
res
}
fn put_schema(
&self,
namespace: NamespaceName<'static>,
schema: NamespaceSchema,
) -> (Arc<NamespaceSchema>, ChangeStats) {
let t = self.time_provider.now();
let (result, change_stats) = self.inner.put_schema(namespace, schema);
if let Some(delta) = self.time_provider.now().checked_duration_since(t) {
if change_stats.did_update {
self.put_update.record(delta);
} else {
self.put_insert.record(delta)
};
}
// Adjust the metrics to reflect the change in table and column counts
self.table_count.inc(change_stats.new_tables.len() as u64);
self.column_count.inc(change_stats.num_new_columns as u64);
(result, change_stats)
}
}
#[cfg(test)]
mod tests {
use assert_matches::assert_matches;
use data_types::{
Column, ColumnId, ColumnType, ColumnsByName, NamespaceId, TableId, TableSchema,
};
use metric::{Attributes, MetricObserver, Observation};
use super::*;
use crate::namespace_cache::MemoryNamespaceCache;
/// Deterministically generate a schema containing tables with the specified
/// column cardinality.
fn new_schema(tables: &[usize]) -> NamespaceSchema {
let tables = tables
.iter()
.enumerate()
.map(|(i, &n)| {
let columns = (0..n)
.enumerate()
.map(|(i, _)| Column {
id: ColumnId::new(i as _),
column_type: ColumnType::Bool,
name: i.to_string(),
table_id: TableId::new(i as _),
})
.collect::<Vec<_>>();
(
i.to_string(),
TableSchema {
id: TableId::new(i as _),
partition_template: Default::default(),
columns: ColumnsByName::new(columns),
},
)
})
.collect();
NamespaceSchema {
id: NamespaceId::new(42),
tables,
max_columns_per_table: 100,
max_tables: 42,
retention_period_ns: None,
partition_template: Default::default(),
}
}
fn assert_histogram_hit(
metrics: &metric::Registry,
metric_name: &'static str,
attr: impl Into<Attributes>,
count: u64,
) {
let histogram = metrics
.get_instrument::<Metric<DurationHistogram>>(metric_name)
.expect("failed to read metric")
.get_observer(&attr.into())
.expect("failed to get observer")
.fetch();
let hit_count = histogram.sample_count();
assert_eq!(
hit_count, count,
"metric did not record correct number of calls"
);
}
#[tokio::test]
async fn test_put() {
let ns = NamespaceName::new("test").expect("namespace name is valid");
let registry = metric::Registry::default();
let cache = Arc::new(MemoryNamespaceCache::default());
let cache = Arc::new(InstrumentedCache::new(cache, ®istry));
// No tables
let schema = new_schema(&[]);
cache.put_schema(ns.clone(), schema.to_owned());
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "insert")],
1,
);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "update")],
0,
);
assert_eq!(cache.table_count.observe(), Observation::U64Gauge(0));
assert_eq!(cache.column_count.observe(), Observation::U64Gauge(0));
// Add a table with 1 column
let schema = new_schema(&[1]);
assert_matches!(cache.put_schema(ns.clone(), schema.to_owned()), (result, _) => {
assert_eq!(*result, schema);
});
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "insert")],
1,
);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "update")],
1,
);
assert_eq!(cache.table_count.observe(), Observation::U64Gauge(1));
assert_eq!(cache.column_count.observe(), Observation::U64Gauge(1));
// Increase the number of columns in this one table
let schema = new_schema(&[5]);
cache.put_schema(ns.clone(), schema);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "insert")],
1,
);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "update")],
2,
);
assert_eq!(cache.table_count.observe(), Observation::U64Gauge(1));
assert_eq!(cache.column_count.observe(), Observation::U64Gauge(5));
// Add another table
let schema = new_schema(&[5, 5]);
cache.put_schema(ns.clone(), schema);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "insert")],
1,
);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "update")],
3,
);
assert_eq!(cache.table_count.observe(), Observation::U64Gauge(2));
assert_eq!(cache.column_count.observe(), Observation::U64Gauge(10));
// Add another table and adjust an existing table (increased column count)
let schema = new_schema(&[5, 10, 4]);
cache.put_schema(ns.clone(), schema);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "insert")],
1,
);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "update")],
4,
);
assert_eq!(cache.table_count.observe(), Observation::U64Gauge(3));
assert_eq!(cache.column_count.observe(), Observation::U64Gauge(19));
// Add a new namespace
let ns = NamespaceName::new("another").expect("namespace name is valid");
let schema = new_schema(&[10, 12, 9]);
cache.put_schema(ns.clone(), schema);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "insert")],
2,
);
assert_histogram_hit(
®istry,
"namespace_cache_put_duration",
&[("op", "update")],
4,
);
assert_eq!(cache.table_count.observe(), Observation::U64Gauge(6));
assert_eq!(cache.column_count.observe(), Observation::U64Gauge(50)); // 15 + new columns (31)
let _got = cache.get_schema(&ns).await.expect("should exist");
assert_histogram_hit(
®istry,
"namespace_cache_get_duration",
&[("result", "hit")],
1,
);
}
}
|
// Copyright 2018 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use std::{collections::HashSet, ops::Range};
// https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml
const EPHEMERAL_PORT_RANGE: Range<u32> = 49152..65535;
pub fn is_ephemeral(port: u32) -> bool {
port >= EPHEMERAL_PORT_RANGE.start && port < EPHEMERAL_PORT_RANGE.end
}
pub struct Tracker {
// TODO: use a bit-vec instead
used: HashSet<u32>,
// Track the next port we should attempt to begin allocating from as a
// heuristic.
next_allocation: u32,
}
impl Tracker {
pub fn allocate(&mut self) -> Option<u32> {
// Search for a port starting from `next_allocation` and wrapping around if none is
// found to try all the ports up until one before next_allocation.
(self.next_allocation..EPHEMERAL_PORT_RANGE.end)
.chain(EPHEMERAL_PORT_RANGE.start..self.next_allocation)
.find(|&p| self.used.insert(p))
.map(|x| {
self.next_allocation = x + 1;
x
})
}
pub fn free(&mut self, port: u32) {
if !self.used.remove(&port) {
panic!("Tried to free unallocated port.");
}
self.next_allocation = std::cmp::min(self.next_allocation, port);
}
pub fn new() -> Self {
Tracker {
used: HashSet::new(),
next_allocation: EPHEMERAL_PORT_RANGE.start,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ports_reused() {
let mut t = Tracker::new();
let p1 = t.allocate().unwrap();
let p2 = t.allocate().unwrap();
let p3 = t.allocate().unwrap();
t.free(p2);
let p4 = t.allocate().unwrap();
assert_eq!(p2, p4);
let p5 = t.allocate().unwrap();
t.free(p4);
t.free(p3);
let p6 = t.allocate().unwrap();
let p7 = t.allocate().unwrap();
assert_eq!(p4, p6);
assert_eq!(p3, p7);
t.free(p1);
t.free(p5);
t.free(p6);
t.free(p7);
}
}
|
use crate::fd::AsFd;
use crate::pid::Pid;
#[cfg(not(target_os = "espidf"))]
use crate::termios::{Action, OptionalActions, QueueSelector, Termios, Winsize};
use crate::{backend, io};
/// `tcgetattr(fd)`—Get terminal attributes.
///
/// Also known as the `TCGETS` (or `TCGETS2` on Linux) operation with `ioctl`.
///
/// # References
/// - [POSIX `tcgetattr`]
/// - [Linux `ioctl_tty`]
/// - [Linux `termios`]
///
/// [POSIX `tcgetattr`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcgetattr.html
/// [Linux `ioctl_tty`]: https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
/// [Linux `termios`]: https://man7.org/linux/man-pages/man3/termios.3.html
#[cfg(not(any(windows, target_os = "espidf", target_os = "wasi")))]
#[inline]
#[doc(alias = "TCGETS")]
#[doc(alias = "TCGETS2")]
#[doc(alias = "tcgetattr2")]
pub fn tcgetattr<Fd: AsFd>(fd: Fd) -> io::Result<Termios> {
backend::termios::syscalls::tcgetattr(fd.as_fd())
}
/// `tcgetwinsize(fd)`—Get the current terminal window size.
///
/// Also known as the `TIOCGWINSZ` operation with `ioctl`.
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
#[cfg(not(any(windows, target_os = "espidf", target_os = "wasi")))]
#[inline]
#[doc(alias = "TIOCGWINSZ")]
pub fn tcgetwinsize<Fd: AsFd>(fd: Fd) -> io::Result<Winsize> {
backend::termios::syscalls::tcgetwinsize(fd.as_fd())
}
/// `tcgetpgrp(fd)`—Get the terminal foreground process group.
///
/// Also known as the `TIOCGPGRP` operation with `ioctl`.
///
/// # References
/// - [POSIX]
/// - [Linux]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcgetpgrp.html
/// [Linux]: https://man7.org/linux/man-pages/man3/tcgetpgrp.3.html
#[cfg(not(any(windows, target_os = "wasi")))]
#[inline]
#[doc(alias = "TIOCGPGRP")]
pub fn tcgetpgrp<Fd: AsFd>(fd: Fd) -> io::Result<Pid> {
backend::termios::syscalls::tcgetpgrp(fd.as_fd())
}
/// `tcsetpgrp(fd, pid)`—Set the terminal foreground process group.
///
/// Also known as the `TIOCSPGRP` operation with `ioctl`.
///
/// # References
/// - [POSIX]
/// - [Linux]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcsetpgrp.html
/// [Linux]: https://man7.org/linux/man-pages/man3/tcsetpgrp.3.html
#[cfg(not(any(windows, target_os = "wasi")))]
#[inline]
#[doc(alias = "TIOCSPGRP")]
pub fn tcsetpgrp<Fd: AsFd>(fd: Fd, pid: Pid) -> io::Result<()> {
backend::termios::syscalls::tcsetpgrp(fd.as_fd(), pid)
}
/// `tcsetattr(fd)`—Set terminal attributes.
///
/// Also known as the `TCSETS` (or `TCSETS2 on Linux) operation with `ioctl`.
///
/// # References
/// - [POSIX `tcsetattr`]
/// - [Linux `ioctl_tty`]
/// - [Linux `termios`]
///
/// [POSIX `tcsetattr`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcsetattr.html
/// [Linux `ioctl_tty`]: https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
/// [Linux `termios`]: https://man7.org/linux/man-pages/man3/termios.3.html
#[cfg(not(target_os = "espidf"))]
#[inline]
#[doc(alias = "TCSETS")]
#[doc(alias = "TCSETS2")]
#[doc(alias = "tcsetattr2")]
pub fn tcsetattr<Fd: AsFd>(
fd: Fd,
optional_actions: OptionalActions,
termios: &Termios,
) -> io::Result<()> {
backend::termios::syscalls::tcsetattr(fd.as_fd(), optional_actions, termios)
}
/// `tcsendbreak(fd, 0)`—Transmit zero-valued bits.
///
/// Also known as the `TCSBRK` operation with `ioctl`, with a duration of 0.
///
/// This function always uses an effective duration parameter of zero. For the
/// equivalent of a `tcsendbreak` with a non-zero duration parameter, use
/// `tcdrain`.
///
/// # References
/// - [POSIX `tcsendbreak`]
/// - [Linux `ioctl_tty`]
/// - [Linux `termios`]
///
/// [POSIX `tcsendbreak`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcsendbreak.html
/// [Linux `ioctl_tty`]: https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
/// [Linux `termios`]: https://man7.org/linux/man-pages/man3/termios.3.html
#[inline]
#[doc(alias = "TCSBRK")]
pub fn tcsendbreak<Fd: AsFd>(fd: Fd) -> io::Result<()> {
backend::termios::syscalls::tcsendbreak(fd.as_fd())
}
/// `tcdrain(fd, duration)`—Wait until all pending output has been written.
///
/// # References
/// - [POSIX `tcdrain`]
/// - [Linux `ioctl_tty`]
/// - [Linux `termios`]
///
/// [POSIX `tcsetattr`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcdrain.html
/// [Linux `ioctl_tty`]: https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
/// [Linux `termios`]: https://man7.org/linux/man-pages/man3/termios.3.html
#[cfg(not(target_os = "espidf"))]
#[inline]
pub fn tcdrain<Fd: AsFd>(fd: Fd) -> io::Result<()> {
backend::termios::syscalls::tcdrain(fd.as_fd())
}
/// `tcflush(fd, queue_selector)`—Wait until all pending output has been
/// written.
///
/// # References
/// - [POSIX `tcflush`]
/// - [Linux `ioctl_tty`]
/// - [Linux `termios`]
///
/// [POSIX `tcflush`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcflush.html
/// [Linux `ioctl_tty`]: https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
/// [Linux `termios`]: https://man7.org/linux/man-pages/man3/termios.3.html
#[cfg(not(target_os = "espidf"))]
#[inline]
#[doc(alias = "TCFLSH")]
pub fn tcflush<Fd: AsFd>(fd: Fd, queue_selector: QueueSelector) -> io::Result<()> {
backend::termios::syscalls::tcflush(fd.as_fd(), queue_selector)
}
/// `tcflow(fd, action)`—Suspend or resume transmission or reception.
///
/// # References
/// - [POSIX `tcflow`]
/// - [Linux `ioctl_tty`]
/// - [Linux `termios`]
///
/// [POSIX `tcflow`]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcflow.html
/// [Linux `ioctl_tty`]: https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
/// [Linux `termios`]: https://man7.org/linux/man-pages/man3/termios.3.html
#[cfg(not(target_os = "espidf"))]
#[inline]
#[doc(alias = "TCXONC")]
pub fn tcflow<Fd: AsFd>(fd: Fd, action: Action) -> io::Result<()> {
backend::termios::syscalls::tcflow(fd.as_fd(), action)
}
/// `tcgetsid(fd)`—Return the session ID of the current session with `fd` as
/// its controlling terminal.
///
/// # References
/// - [POSIX]
/// - [Linux]
///
/// [POSIX]: https://pubs.opengroup.org/onlinepubs/9699919799/functions/tcgetsid.html
/// [Linux]: https://man7.org/linux/man-pages/man3/tcgetsid.3.html
#[inline]
#[doc(alias = "TIOCGSID")]
pub fn tcgetsid<Fd: AsFd>(fd: Fd) -> io::Result<Pid> {
backend::termios::syscalls::tcgetsid(fd.as_fd())
}
/// `tcsetwinsize(fd)`—Set the current terminal window size.
///
/// Also known as the `TIOCSWINSZ` operation with `ioctl`.
///
/// # References
/// - [Linux]
///
/// [Linux]: https://man7.org/linux/man-pages/man4/tty_ioctl.4.html
#[cfg(not(target_os = "espidf"))]
#[inline]
#[doc(alias = "TIOCSWINSZ")]
pub fn tcsetwinsize<Fd: AsFd>(fd: Fd, winsize: Winsize) -> io::Result<()> {
backend::termios::syscalls::tcsetwinsize(fd.as_fd(), winsize)
}
|
use crate::{
velement::{Children, Ns},
VElement, VNonKeyedElement, S,
};
macro_rules! elements {
($($ident:ident => $name:expr,)+) => {
$(
pub fn $ident<Message: 'static>() -> VNonKeyedElement<Message> {
VElement::new(Ns::Svg, $name)
}
)+
pub mod keyed {
use crate::{VElement, velement::Ns, VKeyedElement};
$(
pub fn $ident<Message: 'static>() -> VKeyedElement<Message> {
VElement::new(Ns::Svg, $name)
}
)+
}
}
}
macro_rules! string_attributes {
(
$($ident:ident => $name:expr,)+
) => {
impl<C: Children> VElement<C> where C::Message: 'static {
$(
pub fn $ident(self, value: impl Into<S>) -> Self {
self.attribute($name, value.into())
}
)+
}
}
}
macro_rules! to_string_attributes {
(
$($ident:ident: $ty:ty => $name:expr,)+
) => {
impl<C: Children> VElement<C> where C::Message: 'static {
$(
pub fn $ident(self, value: $ty) -> Self {
self.attribute($name, value.to_string())
}
)+
}
}
}
elements! {
a => "a",
animate => "animate",
animate_color => "animateColor",
animate_motion => "animateMotion",
animate_transform => "animateTransform",
circle => "circle",
clip_path => "clipPath",
color_profile => "color-profile",
cursor => "cursor",
defs => "defs",
desc => "desc",
discard => "discard",
ellipse => "ellipse",
fe_blend => "feBlend",
fe_color_matrix => "feColorMatrix",
fe_component_transfer => "feComponentTransfer",
fe_composite => "feComposite",
fe_convolve_matrix => "feConvolveMatrix",
fe_diffuse_lighting => "feDiffuseLighting",
fe_displacement_map => "feDisplacementMap",
fe_distant_light => "feDistantLight",
fe_drop_shadow => "feDropShadow",
fe_flood => "feFlood",
fe_func_a => "feFuncA",
fe_func_b => "feFuncB",
fe_func_g => "feFuncG",
fe_func_r => "feFuncR",
fe_gaussian_blur => "feGaussianBlur",
fe_image => "feImage",
fe_merge => "feMerge",
fe_merge_node => "feMergeNode",
fe_morphology => "feMorphology",
fe_offset => "feOffset",
fe_point_light => "fePointLight",
fe_specular_lighting => "feSpecularLighting",
fe_spot_light => "feSpotLight",
fe_tile => "feTile",
fe_turbulence => "feTurbulence",
filter => "filter",
font => "font",
font_face => "font-face",
font_face_format => "font-face-format",
font_face_name => "font-face-name",
font_face_src => "font-face-src",
font_face_uri => "font-face-uri",
foreign_object => "foreignObject",
g => "g",
glyph => "glyph",
glyph_ref => "glyphRef",
hatch => "hatch",
hatchpath => "hatchpath",
hkern => "hkern",
image => "image",
line => "line",
linear_gradient => "linearGradient",
marker => "marker",
mask => "mask",
mesh => "mesh",
meshgradient => "meshgradient",
meshpatch => "meshpatch",
meshrow => "meshrow",
metadata => "metadata",
missing_glyph => "missing-glyph",
mpath => "mpath",
path => "path",
pattern => "pattern",
polygon => "polygon",
polyline => "polyline",
radial_gradient => "radialGradient",
rect => "rect",
script => "script",
set => "set",
solidcolor => "solidcolor",
stop => "stop",
style => "style",
svg => "svg",
switch => "switch",
symbol => "symbol",
text => "text",
text_path => "textPath",
title => "title",
tref => "tref",
tspan => "tspan",
unknown => "unknown",
use_ => "use",
view => "view",
vkern => "vkern",
}
string_attributes! {
accumulate => "accumulate",
additive => "additive",
alignment_baseline => "alignment-baseline",
attribute_name => "attributeName",
attribute_type => "attributeType",
base_frequency => "baseFrequency",
base_profile => "baseProfile",
baseline_shift => "baseline-shift",
begin => "begin",
calc_mode => "calcMode",
clip_path => "clip-path",
clip_rule => "clip-rule",
clip_path_units => "clipPathUnits",
// color => "color",
color_interpolation => "color-interpolation",
color_interpolation_filters => "color-interpolation-filters",
color_profile => "color-profile",
color_rendering => "color-rendering",
content_script_type => "contentScriptType",
content_style_type => "contentStyleType",
cursor => "cursor",
cx => "cx",
cy => "cy",
d => "d",
direction => "direction",
display => "display",
dominant_baseline => "dominant-baseline",
dur => "dur",
dx => "dx",
dy => "dy",
edge_mode => "edgeMode",
end => "end",
fill => "fill",
fill_opacity => "fill-opacity",
fill_rule => "fill-rule",
filter => "filter",
filter_units => "filterUnits",
flood_color => "flood-color",
flood_opacity => "flood-opacity",
font_family => "font-family",
font_size => "font-size",
font_size_adjust => "font-size-adjust",
font_stretch => "font-stretch",
font_style => "font-style",
font_variant => "font-variant",
font_weight => "font-weight",
from => "from",
fx => "fx",
fy => "fy",
gradient_transform => "gradientTransform",
gradient_units => "gradientUnits",
// height => "height",
// href => "href",
image_rendering => "image-rendering",
in_ => "in",
in2 => "in2",
kernel_matrix => "kernelMatrix",
kernel_unit_length => "kernelUnitLength",
kerning => "kerning",
key_splines => "keySplines",
key_times => "keyTimes",
length_adjust => "lengthAdjust",
letter_spacing => "letter-spacing",
lighting_color => "lighting-color",
local => "local",
marker_end => "marker-end",
marker_mid => "marker-mid",
marker_start => "marker-start",
marker_height => "markerHeight",
marker_units => "markerUnits",
marker_width => "markerWidth",
mask => "mask",
mask_content_units => "maskContentUnits",
mask_units => "maskUnits",
// max => "max",
// min => "min",
mode => "mode",
opacity => "opacity",
operator => "operator",
order => "order",
overflow => "overflow",
paint_order => "paint-order",
pattern_content_units => "patternContentUnits",
pattern_transform => "patternTransform",
pattern_units => "patternUnits",
pointer_events => "pointer-events",
points => "points",
preserve_aspect_ratio => "preserveAspectRatio",
primitive_units => "primitiveUnits",
r => "r",
radius => "radius",
repeat_count => "repeatCount",
repeat_dur => "repeatDur",
required_features => "requiredFeatures",
restart => "restart",
result => "result",
rx => "rx",
ry => "ry",
shape_rendering => "shape-rendering",
std_deviation => "stdDeviation",
stitch_tiles => "stitchTiles",
stop_color => "stop-color",
stop_opacity => "stop-opacity",
stroke => "stroke",
stroke_dasharray => "stroke-dasharray",
stroke_dashoffset => "stroke-dashoffset",
stroke_linecap => "stroke-linecap",
stroke_linejoin => "stroke-linejoin",
stroke_opacity => "stroke-opacity",
stroke_width => "stroke-width",
text_anchor => "text-anchor",
text_decoration => "text-decoration",
text_rendering => "text-rendering",
text_length => "textLength",
to => "to",
transform => "transform",
// type_ => "type",
values => "values",
vector_effect => "vector-effect",
view_box => "viewBox",
visibility => "visibility",
// width => "width",
word_spacing => "word-spacing",
writing_mode => "writing-mode",
x => "x",
x1 => "x1",
x2 => "x2",
x_channel_selector => "xChannelSelector",
y => "y",
y1 => "y1",
y2 => "y2",
y_channel_selector => "yChannelSelector",
}
to_string_attributes! {
accent_height: f64 => "accent-height",
ascent: f64 => "ascent",
azimuth: f64 => "azimuth",
bias: f64 => "bias",
diffuse_constant: f64 => "diffuseConstant",
divisor: f64 => "divisor",
elevation: f64 => "elevation",
external_resources_required: bool => "externalResourcesRequired",
fr: f64 => "fr",
k1: f64 => "k1",
k2: f64 => "k2",
k3: f64 => "k3",
k4: f64 => "k4",
limiting_cone_angle: f64 => "limitingConeAngle",
num_octaves: i32 => "numOctaves",
overline_position: f64 => "overline-position",
overline_thickness: f64 => "overline-thickness",
path_length: f64 => "pathLength",
points_at_x: f64 => "pointsAtX",
points_at_y: f64 => "pointsAtY",
points_at_z: f64 => "pointsAtZ",
preserve_alpha: bool => "preserveAlpha",
ref_x: f64 => "refX",
ref_y: f64 => "refY",
scale: f64 => "scale",
seed: f64 => "seed",
specular_constant: f64 => "specularConstant",
specular_exponent: f64 => "specularExponent",
strikethrough_position: f64 => "strikethrough-position",
strikethrough_thickness: f64 => "strikethrough-thickness",
stroke_miterlimit: f64 => "stroke-miterlimit",
surface_scale: f64 => "surfaceScale",
// tabindex: i32 => "tabindex",
target_x: f64 => "targetX",
target_y: f64 => "targetY",
underline_position: f64 => "underline-position",
underline_thickness: f64 => "underline-thickness",
version: f64 => "version",
}
|
use futures::{Future, Sink, Stream};
#[derive(Debug)]
pub(super) struct State {
subscriptions: std::collections::HashMap<String, crate::proto::QoS>,
subscriptions_updated_send: futures::sync::mpsc::Sender<SubscriptionUpdate>,
subscriptions_updated_recv: futures::sync::mpsc::Receiver<SubscriptionUpdate>,
subscription_updates_waiting_to_be_sent: std::collections::VecDeque<SubscriptionUpdate>,
subscription_updates_waiting_to_be_acked:
std::collections::VecDeque<(crate::proto::PacketIdentifier, BatchedSubscriptionUpdate)>,
}
impl State {
pub(super) fn poll(
&mut self,
packet: &mut Option<crate::proto::Packet>,
packet_identifiers: &mut super::PacketIdentifiers,
) -> Result<(Vec<crate::proto::Packet>, Vec<SubscriptionUpdate>), super::Error> {
let mut subscription_updates = vec![];
match packet.take() {
Some(crate::proto::Packet::SubAck {
packet_identifier,
qos,
}) => match self.subscription_updates_waiting_to_be_acked.pop_front() {
Some((
packet_identifier_waiting_to_be_acked,
BatchedSubscriptionUpdate::Subscribe(subscribe_to),
)) => {
if packet_identifier != packet_identifier_waiting_to_be_acked {
self.subscription_updates_waiting_to_be_acked.push_front((
packet_identifier_waiting_to_be_acked,
BatchedSubscriptionUpdate::Subscribe(subscribe_to),
));
return Err(super::Error::UnexpectedSubAck(
packet_identifier,
super::UnexpectedSubUnsubAckReason::Expected(
packet_identifier_waiting_to_be_acked,
),
));
}
if subscribe_to.len() != qos.len() {
let expected = subscribe_to.len();
self.subscription_updates_waiting_to_be_acked.push_front((
packet_identifier_waiting_to_be_acked,
BatchedSubscriptionUpdate::Subscribe(subscribe_to),
));
return Err(super::Error::SubAckDoesNotContainEnoughQoS(
packet_identifier,
expected,
qos.len(),
));
}
packet_identifiers.discard(packet_identifier);
// We can't put subscribe_to back into self.subscription_updates_waiting_to_be_acked within the below loop
// since we would've partially consumed it.
// Instead, if there's an error, we'll update self.subscriptions anyway with the expected QoS, and set the error to be returned here.
// The error will reset the session and resend the subscription requests, including these that didn't match the expected QoS,
// so pretending the subscription succeeded does no harm.
let mut err = None;
for (
crate::proto::SubscribeTo {
topic_filter,
qos: expected_qos,
},
qos,
) in subscribe_to.into_iter().zip(qos)
{
match qos {
crate::proto::SubAckQos::Success(actual_qos) => {
if actual_qos >= expected_qos {
log::debug!(
"Subscribed to {} with {:?}",
topic_filter,
actual_qos
);
self.subscriptions.insert(topic_filter.clone(), actual_qos);
subscription_updates.push(SubscriptionUpdate::Subscribe(
crate::proto::SubscribeTo {
topic_filter,
qos: actual_qos,
},
));
} else {
if err.is_none() {
err = Some(super::Error::SubscriptionDowngraded(
topic_filter.clone(),
expected_qos,
actual_qos,
));
}
self.subscriptions.insert(topic_filter, expected_qos);
}
}
crate::proto::SubAckQos::Failure => {
if err.is_none() {
err = Some(super::Error::SubscriptionRejectedByServer);
}
self.subscriptions.insert(topic_filter, expected_qos);
}
}
}
if let Some(err) = err {
return Err(err);
}
}
Some((
packet_identifier_waiting_to_be_acked,
unsubscribe @ BatchedSubscriptionUpdate::Unsubscribe(_),
)) => {
self.subscription_updates_waiting_to_be_acked
.push_front((packet_identifier, unsubscribe));
return Err(super::Error::UnexpectedSubAck(
packet_identifier,
super::UnexpectedSubUnsubAckReason::ExpectedUnsubAck(
packet_identifier_waiting_to_be_acked,
),
));
}
None => {
return Err(super::Error::UnexpectedSubAck(
packet_identifier,
super::UnexpectedSubUnsubAckReason::DidNotExpect,
));
}
},
Some(crate::proto::Packet::UnsubAck { packet_identifier }) => {
match self.subscription_updates_waiting_to_be_acked.pop_front() {
Some((
packet_identifier_waiting_to_be_acked,
BatchedSubscriptionUpdate::Unsubscribe(unsubscribe_from),
)) => {
if packet_identifier != packet_identifier_waiting_to_be_acked {
self.subscription_updates_waiting_to_be_acked.push_front((
packet_identifier_waiting_to_be_acked,
BatchedSubscriptionUpdate::Unsubscribe(unsubscribe_from),
));
return Err(super::Error::UnexpectedUnsubAck(
packet_identifier,
super::UnexpectedSubUnsubAckReason::Expected(
packet_identifier_waiting_to_be_acked,
),
));
}
packet_identifiers.discard(packet_identifier);
for topic_filter in unsubscribe_from {
log::debug!("Unsubscribed from {}", topic_filter);
self.subscriptions.remove(&topic_filter);
subscription_updates
.push(SubscriptionUpdate::Unsubscribe(topic_filter));
}
}
Some((
packet_identifier_waiting_to_be_acked,
subscribe @ BatchedSubscriptionUpdate::Subscribe(_),
)) => {
self.subscription_updates_waiting_to_be_acked
.push_front((packet_identifier_waiting_to_be_acked, subscribe));
return Err(super::Error::UnexpectedUnsubAck(
packet_identifier,
super::UnexpectedSubUnsubAckReason::ExpectedSubAck(
packet_identifier_waiting_to_be_acked,
),
));
}
None => {
return Err(super::Error::UnexpectedUnsubAck(
packet_identifier,
super::UnexpectedSubUnsubAckReason::DidNotExpect,
));
}
}
}
other => *packet = other,
}
while let futures::Async::Ready(Some(subscription_to_update)) = self
.subscriptions_updated_recv
.poll()
.expect("Receiver::poll cannot fail")
{
self.subscription_updates_waiting_to_be_sent
.push_back(subscription_to_update);
}
let mut packets_waiting_to_be_sent = vec![];
if !self.subscription_updates_waiting_to_be_sent.is_empty() {
// Rather than send individual SUBSCRIBE and UNSUBSCRIBE packets for each update, we can send multiple updates in the same packet.
// subscription_updates_waiting_to_be_sent may contain Subscribe and Unsubscribe in arbitrary order, so we have to partition them into
// a group of Subscribe and a group of Unsubscribe.
//
// But the client have have unsubscribed to an earlier subscription, and both the Subscribe and the later Unsubscribe might be in this list.
// Similarly, the client have have re-subscribed after unsubscribing, and both the Unsubscribe and the later Subscribe might be in this list.
//
// So we cannot just make a group of all Subscribes, send that packet, then make a group of all Unsubscribes, then send that packet.
// Instead, we have to respect the ordering of Subscribes with Unsubscribes.
// So we make an intermediate set of all subscriptions based on the updates waiting to be sent, compute the diff from the current subscriptions,
// then send a SUBSCRIBE packet for any net new subscriptions and an UNSUBSCRIBE packet for any net new unsubscriptions.
let mut target_subscriptions = self.subscriptions.clone();
while let Some(subscription_update) =
self.subscription_updates_waiting_to_be_sent.pop_front()
{
match subscription_update {
SubscriptionUpdate::Subscribe(subscribe_to) => {
target_subscriptions.insert(subscribe_to.topic_filter, subscribe_to.qos)
}
SubscriptionUpdate::Unsubscribe(unsubscribe_from) => {
target_subscriptions.remove(&unsubscribe_from)
}
};
}
let mut pending_subscriptions = vec![];
for (topic_filter, &qos) in &target_subscriptions {
if self.subscriptions.get(topic_filter) != Some(&qos) {
// Current subscription doesn't exist, or exists but has different QoS
pending_subscriptions.push(crate::proto::SubscribeTo {
topic_filter: topic_filter.clone(),
qos,
});
}
}
pending_subscriptions.sort_by(|s1, s2| s1.topic_filter.cmp(&s2.topic_filter));
let mut pending_unsubscriptions = vec![];
for topic_filter in self.subscriptions.keys() {
if !target_subscriptions.contains_key(topic_filter) {
pending_unsubscriptions.push(topic_filter.clone());
}
}
pending_unsubscriptions.sort();
// Save the error, if any, from reserving a packet identifier
// This error is only returned if neither subscription nor unsubscription generated a packet to send
// This avoids having to discard a valid packet identifier for a SUBSCRIBE packet just because
// the unsubscription failed to reserve a packet identifier for an UNSUBSCRIBE packet.
let mut err = None;
if !pending_subscriptions.is_empty() {
match packet_identifiers.reserve() {
Ok(packet_identifier) => {
self.subscription_updates_waiting_to_be_acked.push_back((
packet_identifier,
BatchedSubscriptionUpdate::Subscribe(pending_subscriptions.clone()),
));
packets_waiting_to_be_sent.push(crate::proto::Packet::Subscribe {
packet_identifier,
subscribe_to: pending_subscriptions,
});
}
Err(err_) => {
err = Some(err_);
for pending_subscription in pending_subscriptions {
self.subscription_updates_waiting_to_be_sent
.push_front(SubscriptionUpdate::Subscribe(pending_subscription));
}
}
};
}
if !pending_unsubscriptions.is_empty() {
match packet_identifiers.reserve() {
Ok(packet_identifier) => {
self.subscription_updates_waiting_to_be_acked.push_back((
packet_identifier,
BatchedSubscriptionUpdate::Unsubscribe(pending_unsubscriptions.clone()),
));
packets_waiting_to_be_sent.push(crate::proto::Packet::Unsubscribe {
packet_identifier,
unsubscribe_from: pending_unsubscriptions,
});
}
Err(err_) => {
err = Some(err_);
for pending_unsubscription in pending_unsubscriptions {
self.subscription_updates_waiting_to_be_sent.push_front(
SubscriptionUpdate::Unsubscribe(pending_unsubscription),
);
}
}
};
}
if packets_waiting_to_be_sent.is_empty() {
if let Some(err) = err {
return Err(err);
}
}
}
Ok((packets_waiting_to_be_sent, subscription_updates))
}
pub(super) fn new_connection(
&mut self,
reset_session: bool,
packet_identifiers: &mut super::PacketIdentifiers,
) -> impl Iterator<Item = crate::proto::Packet> {
if reset_session {
let mut subscriptions = std::mem::replace(&mut self.subscriptions, Default::default());
let subscription_updates_waiting_to_be_acked = std::mem::replace(
&mut self.subscription_updates_waiting_to_be_acked,
Default::default(),
);
// Apply all pending (ie unacked) changes to the set of subscriptions, in order that they were original requested
for (packet_identifier, subscription_update_waiting_to_be_acked) in
subscription_updates_waiting_to_be_acked
{
packet_identifiers.discard(packet_identifier);
match subscription_update_waiting_to_be_acked {
BatchedSubscriptionUpdate::Subscribe(subscribe_to) => {
for crate::proto::SubscribeTo { topic_filter, qos } in subscribe_to {
subscriptions.insert(topic_filter, qos);
}
}
BatchedSubscriptionUpdate::Unsubscribe(unsubscribe_from) => {
for topic_filter in unsubscribe_from {
subscriptions.remove(&topic_filter);
}
}
}
}
// Generate a SUBSCRIBE packet for the final set of subscriptions
let mut subscriptions_waiting_to_be_acked: Vec<_> = subscriptions
.into_iter()
.map(|(topic_filter, qos)| crate::proto::SubscribeTo { topic_filter, qos })
.collect();
subscriptions_waiting_to_be_acked.sort_by(|subscribe_to1, subscribe_to2| {
subscribe_to1.topic_filter.cmp(&subscribe_to2.topic_filter)
});
if subscriptions_waiting_to_be_acked.is_empty() {
NewConnectionIter::Empty
} else {
let packet_identifier = packet_identifiers
.reserve()
.expect("reset session should have available packet identifiers");
self.subscription_updates_waiting_to_be_acked.push_back((
packet_identifier,
BatchedSubscriptionUpdate::Subscribe(subscriptions_waiting_to_be_acked.clone()),
));
NewConnectionIter::Single(std::iter::once(crate::proto::Packet::Subscribe {
packet_identifier,
subscribe_to: subscriptions_waiting_to_be_acked,
}))
}
} else {
// Re-create all pending (ie unacked) changes to the set of subscriptions
let unacked_packets: Vec<_> = self
.subscription_updates_waiting_to_be_acked
.iter()
.map(
|(packet_identifier, subscription_update)| match subscription_update {
BatchedSubscriptionUpdate::Subscribe(subscribe_to) => {
crate::proto::Packet::Subscribe {
packet_identifier: *packet_identifier,
subscribe_to: subscribe_to.clone(),
}
}
BatchedSubscriptionUpdate::Unsubscribe(unsubscribe_from) => {
crate::proto::Packet::Unsubscribe {
packet_identifier: *packet_identifier,
unsubscribe_from: unsubscribe_from.clone(),
}
}
},
)
.collect();
NewConnectionIter::Multiple(unacked_packets.into_iter())
}
}
pub(super) fn update_subscription(&mut self, subscription_update: SubscriptionUpdate) {
self.subscription_updates_waiting_to_be_sent
.push_back(subscription_update);
}
pub(super) fn update_subscription_handle(&self) -> UpdateSubscriptionHandle {
UpdateSubscriptionHandle(self.subscriptions_updated_send.clone())
}
}
impl Default for State {
fn default() -> Self {
let (subscriptions_updated_send, subscriptions_updated_recv) =
futures::sync::mpsc::channel(0);
State {
subscriptions: Default::default(),
subscriptions_updated_send,
subscriptions_updated_recv,
subscription_updates_waiting_to_be_sent: Default::default(),
subscription_updates_waiting_to_be_acked: Default::default(),
}
}
}
/// The kind of subscription update
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum SubscriptionUpdate {
Subscribe(crate::proto::SubscribeTo),
Unsubscribe(String),
}
#[derive(Debug)]
enum BatchedSubscriptionUpdate {
Subscribe(Vec<crate::proto::SubscribeTo>),
Unsubscribe(Vec<String>),
}
#[derive(Debug)]
enum NewConnectionIter {
Empty,
Single(std::iter::Once<crate::proto::Packet>),
Multiple(std::vec::IntoIter<crate::proto::Packet>),
}
impl Iterator for NewConnectionIter {
type Item = crate::proto::Packet;
fn next(&mut self) -> Option<Self::Item> {
match self {
NewConnectionIter::Empty => None,
NewConnectionIter::Single(packet) => packet.next(),
NewConnectionIter::Multiple(packets) => packets.next(),
}
}
}
/// Used to update subscriptions
pub struct UpdateSubscriptionHandle(futures::sync::mpsc::Sender<SubscriptionUpdate>);
impl UpdateSubscriptionHandle {
/// Subscribe to a topic with the given parameters.
///
/// The [`Future`] returned by this function resolves when the subscription update is received by the client.
/// The client has *not necessarily* sent out the subscription update to the server at that point,
/// and the server has *not necessarily* acked the subscription update at that point.
///
/// This is done because the client automatically resubscribes when the connection is broken and re-established, so the user
/// of the client needs to know about this every time the server acks the subscription, not just the first time they request it.
///
/// Furthermore, the client batches subscription updates, which can cause some subscription updates to never be sent (say because a subscription
/// was canceled out by a matching unsubscription before the subscription was ever sent to the server). So there is not a one-to-one correspondence
/// between subscription update requests and acks.
///
/// To know when the server has acked the subscription update, wait for the client to send an [`mqtt::Event::SubscriptionUpdate::Subscribe`] value
/// that contains a `mqtt::proto::SubscribeTo` value with the same topic filter.
/// Be careful about using `==` to determine this, since the QoS in the event may be higher than the one requested here.
pub fn subscribe(
&mut self,
subscribe_to: crate::proto::SubscribeTo,
) -> impl Future<Item = (), Error = UpdateSubscriptionError> {
self.0
.clone()
.send(SubscriptionUpdate::Subscribe(subscribe_to))
.then(|result| match result {
Ok(_) => Ok(()),
Err(_) => Err(UpdateSubscriptionError::ClientDoesNotExist),
})
}
/// Unsubscribe from the given topic.
///
/// The [`Future`] returned by this function resolves when the subscription update is received by the client.
/// The client has *not necessarily* sent out the subscription update to the server at that point,
/// and the server has *not necessarily* acked the subscription update at that point.
///
/// This is done because the client automatically resubscribes when the connection is broken and re-established, so the user
/// of the client needs to know about this every time the server acks the subscription, not just the first time they request it.
///
/// Furthermore, the client batches subscription updates, which can cause some subscription updates to never be sent (say because a subscription
/// was canceled out by a matching unsubscription before the subscription was ever sent to the server). So there is not a one-to-one correspondence
/// between subscription update requests and acks.
///
/// To know when the server has acked the subscription update, wait for the client to send an [`mqtt::Event::SubscriptionUpdate::Unsubscribe`] value
/// for this topic filter.
pub fn unsubscribe(
&mut self,
unsubscribe_from: String,
) -> impl Future<Item = (), Error = UpdateSubscriptionError> {
self.0
.clone()
.send(SubscriptionUpdate::Unsubscribe(unsubscribe_from))
.then(|result| match result {
Ok(_) => Ok(()),
Err(_) => Err(UpdateSubscriptionError::ClientDoesNotExist),
})
}
}
#[derive(Clone, Copy, Debug)]
pub enum UpdateSubscriptionError {
ClientDoesNotExist,
}
impl std::fmt::Display for UpdateSubscriptionError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
UpdateSubscriptionError::ClientDoesNotExist => write!(f, "client does not exist"),
}
}
}
impl std::error::Error for UpdateSubscriptionError {}
|
use std::error::Error;
use std::fs;
use std::path::Path;
use heed::byteorder::BE;
use heed::types::*;
use heed::zerocopy::{AsBytes, FromBytes, Unaligned, I64};
use heed::{Database, EnvOpenOptions};
use serde::{Deserialize, Serialize};
fn main() -> Result<(), Box<dyn Error>> {
let path = Path::new("target").join("heed.mdb");
fs::create_dir_all(&path)?;
let env = EnvOpenOptions::new()
.map_size(10 * 1024 * 1024) // 10MB
.max_dbs(3000)
.open(path)?;
// you can specify that a database will support some typed key/data
//
// like here we specify that the key will be an array of two i32
// and the data will be an str
let db: Database<OwnedType<[i32; 2]>, Str> = env.create_database(Some("kikou"))?;
let mut wtxn = env.write_txn()?;
let _ret = db.put(&mut wtxn, &[2, 3], "what's up?")?;
let ret: Option<&str> = db.get(&wtxn, &[2, 3])?;
println!("{:?}", ret);
wtxn.commit()?;
// here the key will be an str and the data will be a slice of u8
let db: Database<Str, ByteSlice> = env.create_database(Some("kiki"))?;
let mut wtxn = env.write_txn()?;
let _ret = db.put(&mut wtxn, "hello", &[2, 3][..])?;
let ret: Option<&[u8]> = db.get(&wtxn, "hello")?;
println!("{:?}", ret);
wtxn.commit()?;
// serde types are also supported!!!
#[derive(Debug, Serialize, Deserialize)]
struct Hello<'a> {
string: &'a str,
}
let db: Database<Str, SerdeBincode<Hello>> = env.create_database(Some("serde-bincode"))?;
let mut wtxn = env.write_txn()?;
let hello = Hello { string: "hi" };
db.put(&mut wtxn, "hello", &hello)?;
let ret: Option<Hello> = db.get(&wtxn, "hello")?;
println!("serde-bincode:\t{:?}", ret);
wtxn.commit()?;
let db: Database<Str, SerdeJson<Hello>> = env.create_database(Some("serde-json"))?;
let mut wtxn = env.write_txn()?;
let hello = Hello { string: "hi" };
db.put(&mut wtxn, "hello", &hello)?;
let ret: Option<Hello> = db.get(&wtxn, "hello")?;
println!("serde-json:\t{:?}", ret);
wtxn.commit()?;
// it is prefered to use zerocopy when possible
#[derive(Debug, PartialEq, Eq, AsBytes, FromBytes, Unaligned)]
#[repr(C)]
struct ZeroBytes {
bytes: [u8; 12],
}
let db: Database<Str, UnalignedType<ZeroBytes>> =
env.create_database(Some("zerocopy-struct"))?;
let mut wtxn = env.write_txn()?;
let zerobytes = ZeroBytes { bytes: [24; 12] };
db.put(&mut wtxn, "zero", &zerobytes)?;
let ret = db.get(&wtxn, "zero")?;
println!("{:?}", ret);
wtxn.commit()?;
// you can ignore the data
let db: Database<Str, Unit> = env.create_database(Some("ignored-data"))?;
let mut wtxn = env.write_txn()?;
let _ret = db.put(&mut wtxn, "hello", &())?;
let ret: Option<()> = db.get(&wtxn, "hello")?;
println!("{:?}", ret);
let ret: Option<()> = db.get(&wtxn, "non-existant")?;
println!("{:?}", ret);
wtxn.commit()?;
// database opening and types are tested in a way
//
// we try to open a database twice with the same types
let _db: Database<Str, Unit> = env.create_database(Some("ignored-data"))?;
// and here we try to open it with other types
// asserting that it correctly returns an error
//
// NOTE that those types are not saved upon runs and
// therefore types cannot be checked upon different runs,
// the first database opening fix the types for this run.
let result = env.create_database::<Str, OwnedSlice<i32>>(Some("ignored-data"));
assert!(result.is_err());
// you can iterate over keys in order
type BEI64 = I64<BE>;
let db: Database<OwnedType<BEI64>, Unit> = env.create_database(Some("big-endian-iter"))?;
let mut wtxn = env.write_txn()?;
let _ret = db.put(&mut wtxn, &BEI64::new(0), &())?;
let _ret = db.put(&mut wtxn, &BEI64::new(68), &())?;
let _ret = db.put(&mut wtxn, &BEI64::new(35), &())?;
let _ret = db.put(&mut wtxn, &BEI64::new(42), &())?;
let rets: Result<Vec<(BEI64, _)>, _> = db.iter(&wtxn)?.collect();
println!("{:?}", rets);
// or iterate over ranges too!!!
let range = BEI64::new(35)..=BEI64::new(42);
let rets: Result<Vec<(BEI64, _)>, _> = db.range(&wtxn, &range)?.collect();
println!("{:?}", rets);
// delete a range of key
let range = BEI64::new(35)..=BEI64::new(42);
let deleted: usize = db.delete_range(&mut wtxn, &range)?;
let rets: Result<Vec<(BEI64, _)>, _> = db.iter(&wtxn)?.collect();
println!("deleted: {:?}, {:?}", deleted, rets);
wtxn.commit()?;
Ok(())
}
|
#[macro_use]
extern crate clap;
extern crate victoria_dom;
use clap::App;
use std::fs::File;
use std::io::BufReader;
use std::io::{self, Read};
use std::process;
use victoria_dom::DOM;
use walkdir::WalkDir;
static mut PARAM_VERBOSITY: u64 = 0;
fn v_printer(verbosity: u64, message: &'static str) {
unsafe {
if PARAM_VERBOSITY >= verbosity {
println!("{}", message);
}
}
}
fn get_piped() -> String {
let mut input = String::new();
match io::stdin().lock().read_to_string(&mut input) {
Ok(n) => {
println!("{} bytes read", n);
//println!("{}", input);
return input;
}
Err(error) => {
println!("error: {}", error);
process::exit(1);
}
}
}
fn get_file(path: String) -> String {
let file = File::open(&path);
match file {
Ok(file) => {
let mut buf_reader = BufReader::new(file);
let mut contents = String::new();
buf_reader.read_to_string(&mut contents);
return contents;
}
Err(e) => {
println!("file not found \n{:?}", e);
return "".to_string();
}
}
}
fn get_folder(path: String) -> Vec<String> {
let mut files = Vec::new();
for entry in WalkDir::new(path) {
let entry = entry.unwrap();
files.push(get_file(entry.path().display().to_string()));
}
return files;
}
fn parser(html: String, selector: &str, single: bool) {
let dom = DOM::new(html.as_str());
if single {
println!("{}", dom.at(selector).unwrap().to_string());
} else {
for node in dom.find(selector) {
println!("{}", node.to_string())
}
}
}
fn main() {
let yaml = load_yaml!("cli.yml");
let matches = App::from_yaml(yaml).get_matches();
unsafe {
PARAM_VERBOSITY = matches.occurrences_of("verbose");
};
let selector = matches.value_of("selector").unwrap();
let single = matches.occurrences_of("single") > 0;
if matches.value_of("input").is_some() {
if matches.occurrences_of("recursive") > 0 {
v_printer(2, "Using Folder recursivly");
for file in get_folder(matches.value_of("input").unwrap().to_string()) {
parser(file, selector, single);
}
} else {
v_printer(2, "Using Input File");
parser(
get_file(matches.value_of("input").unwrap().to_string()),
selector,
single,
);
}
} else {
v_printer(2, "Using Piped");
parser(get_piped(), selector, single);
}
}
|
use proconio::input;
use std::iter;
fn reverse(n: u64) -> u64 {
let mut n = n;
let mut m = 0;
while n > 0 {
m = m * 10 + n % 10;
n /= 10;
}
m
}
fn f(x: u64) -> u64 {
let y = reverse(x);
x.min(y).min(reverse(y))
}
fn main() {
assert_eq!(reverse(123), 321);
assert_eq!(reverse(12300), 321);
input! {
n: u64,
k: u64,
};
if k % 10 == 0 {
println!("0");
} else {
let k_rev = reverse(k);
let mut answer = iter::successors(Some(k), |x| x.checked_mul(10))
.chain(iter::successors(Some(k_rev), |x| x.checked_mul(10)))
.filter(|&x| 1 <= x && x <= n && f(x) == k)
.collect::<Vec<_>>();
answer.sort();
answer.dedup();
println!("{}", answer.len());
}
}
|
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)]
#[link(name = "windows")]
extern "system" {}
#[repr(transparent)]
pub struct ExtendedExecutionForegroundReason(pub i32);
impl ExtendedExecutionForegroundReason {
pub const Unspecified: Self = Self(0i32);
pub const SavingData: Self = Self(1i32);
pub const BackgroundAudio: Self = Self(2i32);
pub const Unconstrained: Self = Self(3i32);
}
impl ::core::marker::Copy for ExtendedExecutionForegroundReason {}
impl ::core::clone::Clone for ExtendedExecutionForegroundReason {
fn clone(&self) -> Self {
*self
}
}
#[repr(transparent)]
pub struct ExtendedExecutionForegroundResult(pub i32);
impl ExtendedExecutionForegroundResult {
pub const Allowed: Self = Self(0i32);
pub const Denied: Self = Self(1i32);
}
impl ::core::marker::Copy for ExtendedExecutionForegroundResult {}
impl ::core::clone::Clone for ExtendedExecutionForegroundResult {
fn clone(&self) -> Self {
*self
}
}
pub type ExtendedExecutionForegroundRevokedEventArgs = *mut ::core::ffi::c_void;
#[repr(transparent)]
pub struct ExtendedExecutionForegroundRevokedReason(pub i32);
impl ExtendedExecutionForegroundRevokedReason {
pub const Resumed: Self = Self(0i32);
pub const SystemPolicy: Self = Self(1i32);
}
impl ::core::marker::Copy for ExtendedExecutionForegroundRevokedReason {}
impl ::core::clone::Clone for ExtendedExecutionForegroundRevokedReason {
fn clone(&self) -> Self {
*self
}
}
pub type ExtendedExecutionForegroundSession = *mut ::core::ffi::c_void;
|
#[allow(unused_variables)]
fn main() {
let x = Some(1);
// match is exhaustive
let x = match x {
Some(x) => x,
None => 1,
};
// pattern non refutable
let x = 1;
let y: Option<&str> = None;
// You can't do that, that's refutable
// let Some(y) = y;
// If you wanna do that, use if let
if let Some(y) = y {
println!("{}", y);
}
// which is non-exhaustive, notice how the compiler didn't whine about missing None branch
let mut stack = Vec::new();
stack.push(1);
stack.push(2);
stack.push(3);
for x in &stack {
println!("{}", *x);
}
while let Some(top) = stack.pop() {
println!("{}", top);
}
let v = vec!['a', 'b', 'c'];
for (index, value) in v.iter().enumerate() {
println!("{} is at index {}", value, index);
}
// some destructuring
let (x, y, _) = (1, 2, 3);
let point = (1, 2);
// @todo: figure out why not borrow after move
// but I suspect it was copied
handle_point_move(point);
handle_point_ref(&point);
let x = 1;
match x {
1 | 2 => println!("one or two"),
3 => println!("three"),
_ => println!("anything"),
}
let x = 2;
match x {
// 1..3 => println!("one to three excluded"), // exclusive is experimental
1..=3 => println!("one to three"),
_ => println!("anything"),
}
let p = Point { x: 0, y: 0 };
match p {
Point { x: 0, y: 0 } => println!("On the origin of the axis at (0, 0)"),
Point { x, y: 0 } => println!("On the x axis at {}", x),
Point { x: 0, y } => println!("On the y axis at {}", y),
Point { x, y } => println!("On neither axis: ({}, {})", x, y),
}
let msg = Message::ChangeColor(0, 160, 255);
match msg {
Message::Quit => println!("The Quit variant has no data to destructure."),
Message::Move { x, y } => {
println!("Move in the x direction {} and in the y direction {}", x, y);
}
Message::Write(text) => println!("Text message: {}", text),
Message::ChangeColor(r, g, b) => {
println!("Change the color to red {}, green {}, and blue {}", r, g, b)
}
}
}
fn handle_point_ref(&(x, y): &(i32, i32)) {
println!("{}, {}", x, y);
return ();
}
fn handle_point_move((x, y): (i32, i32)) {
println!("{}, {}", x, y);
return ();
}
#[allow(dead_code)]
enum Message {
Quit,
Move { x: i32, y: i32 },
Write(String),
ChangeColor(i32, i32, i32),
}
struct Point {
x: i32,
y: i32,
}
|
use super::super::gl;
use super::{
BlendState, BufferState, ColorBufferState, CullFaceState, DepthBufferState, FrontFaceState,
ProgramState, TextureState, VertexArrayState, ViewportState,
};
use glutin::{ContextWrapper, PossiblyCurrent};
use winit::window::Window;
pub struct OpenGLContext {
pub color_buffer: ColorBufferState,
pub depth_buffer: DepthBufferState,
pub texture: TextureState,
pub blend: BlendState,
pub buffer: BufferState,
pub vertex_array: VertexArrayState,
pub program: ProgramState,
pub viewport: ViewportState,
pub culling: CullFaceState,
pub front_face: FrontFaceState,
}
impl OpenGLContext {
pub fn build_initialize(window_context: &ContextWrapper<PossiblyCurrent, Window>) -> Self {
gl::init_from_window(window_context);
let color_buffer = ColorBufferState::build_initialized();
let depth_buffer = DepthBufferState::build_initialized();
let texture = TextureState::build_initialized();
let blend = BlendState::build_initialized();
let buffer = BufferState::build_initialized();
let vertex_array = VertexArrayState::build_initialized();
let program = ProgramState::build_initialized();
let viewport = ViewportState::build_initialized();
let culling = CullFaceState::build_initialized();
let front_face = FrontFaceState::build_initialized();
Self {
color_buffer,
depth_buffer,
texture,
blend,
buffer,
vertex_array,
program,
viewport,
culling,
front_face,
}
}
pub fn clear_buffers(&self, mask: gl::GLbitfield) {
gl::clear(mask);
}
pub fn reset_state(&mut self) {
self.front_face.set(gl::CW);
self.culling.set_enabled(false);
self.color_buffer.set(0.0, 0.0, 0.0, 1.0);
self.clear_buffers(gl::COLOR_BUFFER_BIT | gl::DEPTH_BUFFER_BIT);
self.depth_buffer.set_enabled(true);
self.blend.set_enabled(true).configure(
gl::FUNC_ADD,
gl::SRC_ALPHA,
gl::ONE_MINUS_SRC_ALPHA,
);
}
}
|
#![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 AppointmentCalendarCancelMeetingRequest(pub ::windows::core::IInspectable);
impl AppointmentCalendarCancelMeetingRequest {
pub fn AppointmentCalendarLocalId(&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 AppointmentLocalId(&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 AppointmentOriginalStartTime(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>>(result__)
}
}
pub fn Subject(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Comment(&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).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn NotifyInvitees(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportCompletedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportFailedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarCancelMeetingRequest {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequest;{49460f8d-6434-40d7-ad46-6297419314d1})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarCancelMeetingRequest {
type Vtable = IAppointmentCalendarCancelMeetingRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x49460f8d_6434_40d7_ad46_6297419314d1);
}
impl ::windows::core::RuntimeName for AppointmentCalendarCancelMeetingRequest {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequest";
}
impl ::core::convert::From<AppointmentCalendarCancelMeetingRequest> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarCancelMeetingRequest) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarCancelMeetingRequest> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarCancelMeetingRequest) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarCancelMeetingRequest {
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 AppointmentCalendarCancelMeetingRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarCancelMeetingRequest> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarCancelMeetingRequest) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarCancelMeetingRequest> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarCancelMeetingRequest) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarCancelMeetingRequest {
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 AppointmentCalendarCancelMeetingRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarCancelMeetingRequest {}
unsafe impl ::core::marker::Sync for AppointmentCalendarCancelMeetingRequest {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarCancelMeetingRequestEventArgs(pub ::windows::core::IInspectable);
impl AppointmentCalendarCancelMeetingRequestEventArgs {
pub fn Request(&self) -> ::windows::core::Result<AppointmentCalendarCancelMeetingRequest> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentCalendarCancelMeetingRequest>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::super::Foundation::Deferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Deferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarCancelMeetingRequestEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequestEventArgs;{1a79be16-7f30-4e35-beef-9d2c7b6dcae1})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarCancelMeetingRequestEventArgs {
type Vtable = IAppointmentCalendarCancelMeetingRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1a79be16_7f30_4e35_beef_9d2c7b6dcae1);
}
impl ::windows::core::RuntimeName for AppointmentCalendarCancelMeetingRequestEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCancelMeetingRequestEventArgs";
}
impl ::core::convert::From<AppointmentCalendarCancelMeetingRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarCancelMeetingRequestEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarCancelMeetingRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarCancelMeetingRequestEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarCancelMeetingRequestEventArgs {
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 AppointmentCalendarCancelMeetingRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarCancelMeetingRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarCancelMeetingRequestEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarCancelMeetingRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarCancelMeetingRequestEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarCancelMeetingRequestEventArgs {
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 AppointmentCalendarCancelMeetingRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarCancelMeetingRequestEventArgs {}
unsafe impl ::core::marker::Sync for AppointmentCalendarCancelMeetingRequestEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarCreateOrUpdateAppointmentRequest(pub ::windows::core::IInspectable);
impl AppointmentCalendarCreateOrUpdateAppointmentRequest {
pub fn AppointmentCalendarLocalId(&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 Appointment(&self) -> ::windows::core::Result<super::Appointment> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::Appointment>(result__)
}
}
pub fn NotifyInvitees(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn ChangedProperties(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<::windows::core::HSTRING>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportCompletedAsync<'a, Param0: ::windows::core::IntoParam<'a, super::Appointment>>(&self, createdorupdatedappointment: Param0) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), createdorupdatedappointment.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportFailedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarCreateOrUpdateAppointmentRequest {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCreateOrUpdateAppointmentRequest;{2e62f2b2-ca96-48ac-9124-406b19fefa70})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarCreateOrUpdateAppointmentRequest {
type Vtable = IAppointmentCalendarCreateOrUpdateAppointmentRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2e62f2b2_ca96_48ac_9124_406b19fefa70);
}
impl ::windows::core::RuntimeName for AppointmentCalendarCreateOrUpdateAppointmentRequest {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCreateOrUpdateAppointmentRequest";
}
impl ::core::convert::From<AppointmentCalendarCreateOrUpdateAppointmentRequest> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarCreateOrUpdateAppointmentRequest) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarCreateOrUpdateAppointmentRequest> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarCreateOrUpdateAppointmentRequest) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarCreateOrUpdateAppointmentRequest {
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 AppointmentCalendarCreateOrUpdateAppointmentRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarCreateOrUpdateAppointmentRequest> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarCreateOrUpdateAppointmentRequest) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarCreateOrUpdateAppointmentRequest> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarCreateOrUpdateAppointmentRequest) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarCreateOrUpdateAppointmentRequest {
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 AppointmentCalendarCreateOrUpdateAppointmentRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarCreateOrUpdateAppointmentRequest {}
unsafe impl ::core::marker::Sync for AppointmentCalendarCreateOrUpdateAppointmentRequest {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs(pub ::windows::core::IInspectable);
impl AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {
pub fn Request(&self) -> ::windows::core::Result<AppointmentCalendarCreateOrUpdateAppointmentRequest> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentCalendarCreateOrUpdateAppointmentRequest>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::super::Foundation::Deferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Deferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs;{cf8ded28-002e-4bf7-8e9d-5e20d49aa3ba})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {
type Vtable = IAppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcf8ded28_002e_4bf7_8e9d_5e20d49aa3ba);
}
impl ::windows::core::RuntimeName for AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs";
}
impl ::core::convert::From<AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {
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 AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {
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 AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {}
unsafe impl ::core::marker::Sync for AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarForwardMeetingRequest(pub ::windows::core::IInspectable);
impl AppointmentCalendarForwardMeetingRequest {
pub fn AppointmentCalendarLocalId(&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 AppointmentLocalId(&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 AppointmentOriginalStartTime(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>>(result__)
}
}
#[cfg(feature = "Foundation_Collections")]
pub fn Invitees(&self) -> ::windows::core::Result<super::super::super::Foundation::Collections::IVectorView<super::AppointmentInvitee>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Collections::IVectorView<super::AppointmentInvitee>>(result__)
}
}
pub fn Subject(&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).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn ForwardHeader(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Comment(&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).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportCompletedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportFailedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarForwardMeetingRequest {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarForwardMeetingRequest;{82e5ee56-26b6-4253-8a8f-6cf5f2ff7884})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarForwardMeetingRequest {
type Vtable = IAppointmentCalendarForwardMeetingRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82e5ee56_26b6_4253_8a8f_6cf5f2ff7884);
}
impl ::windows::core::RuntimeName for AppointmentCalendarForwardMeetingRequest {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarForwardMeetingRequest";
}
impl ::core::convert::From<AppointmentCalendarForwardMeetingRequest> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarForwardMeetingRequest) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarForwardMeetingRequest> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarForwardMeetingRequest) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarForwardMeetingRequest {
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 AppointmentCalendarForwardMeetingRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarForwardMeetingRequest> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarForwardMeetingRequest) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarForwardMeetingRequest> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarForwardMeetingRequest) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarForwardMeetingRequest {
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 AppointmentCalendarForwardMeetingRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarForwardMeetingRequest {}
unsafe impl ::core::marker::Sync for AppointmentCalendarForwardMeetingRequest {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarForwardMeetingRequestEventArgs(pub ::windows::core::IInspectable);
impl AppointmentCalendarForwardMeetingRequestEventArgs {
pub fn Request(&self) -> ::windows::core::Result<AppointmentCalendarForwardMeetingRequest> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentCalendarForwardMeetingRequest>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::super::Foundation::Deferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Deferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarForwardMeetingRequestEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarForwardMeetingRequestEventArgs;{3109151a-23a2-42fd-9c82-c9a60d59f8a8})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarForwardMeetingRequestEventArgs {
type Vtable = IAppointmentCalendarForwardMeetingRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3109151a_23a2_42fd_9c82_c9a60d59f8a8);
}
impl ::windows::core::RuntimeName for AppointmentCalendarForwardMeetingRequestEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarForwardMeetingRequestEventArgs";
}
impl ::core::convert::From<AppointmentCalendarForwardMeetingRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarForwardMeetingRequestEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarForwardMeetingRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarForwardMeetingRequestEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarForwardMeetingRequestEventArgs {
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 AppointmentCalendarForwardMeetingRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarForwardMeetingRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarForwardMeetingRequestEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarForwardMeetingRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarForwardMeetingRequestEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarForwardMeetingRequestEventArgs {
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 AppointmentCalendarForwardMeetingRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarForwardMeetingRequestEventArgs {}
unsafe impl ::core::marker::Sync for AppointmentCalendarForwardMeetingRequestEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarProposeNewTimeForMeetingRequest(pub ::windows::core::IInspectable);
impl AppointmentCalendarProposeNewTimeForMeetingRequest {
pub fn AppointmentCalendarLocalId(&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 AppointmentLocalId(&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 AppointmentOriginalStartTime(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn NewStartTime(&self) -> ::windows::core::Result<super::super::super::Foundation::DateTime> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::DateTime = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::DateTime>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn NewDuration(&self) -> ::windows::core::Result<super::super::super::Foundation::TimeSpan> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::TimeSpan = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::TimeSpan>(result__)
}
}
pub fn Subject(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Comment(&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).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportCompletedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportFailedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarProposeNewTimeForMeetingRequest {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarProposeNewTimeForMeetingRequest;{ce1c63f5-edf6-43c3-82b7-be6b368c6900})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarProposeNewTimeForMeetingRequest {
type Vtable = IAppointmentCalendarProposeNewTimeForMeetingRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xce1c63f5_edf6_43c3_82b7_be6b368c6900);
}
impl ::windows::core::RuntimeName for AppointmentCalendarProposeNewTimeForMeetingRequest {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarProposeNewTimeForMeetingRequest";
}
impl ::core::convert::From<AppointmentCalendarProposeNewTimeForMeetingRequest> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarProposeNewTimeForMeetingRequest) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarProposeNewTimeForMeetingRequest> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarProposeNewTimeForMeetingRequest) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarProposeNewTimeForMeetingRequest {
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 AppointmentCalendarProposeNewTimeForMeetingRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarProposeNewTimeForMeetingRequest> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarProposeNewTimeForMeetingRequest) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarProposeNewTimeForMeetingRequest> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarProposeNewTimeForMeetingRequest) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarProposeNewTimeForMeetingRequest {
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 AppointmentCalendarProposeNewTimeForMeetingRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarProposeNewTimeForMeetingRequest {}
unsafe impl ::core::marker::Sync for AppointmentCalendarProposeNewTimeForMeetingRequest {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs(pub ::windows::core::IInspectable);
impl AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {
pub fn Request(&self) -> ::windows::core::Result<AppointmentCalendarProposeNewTimeForMeetingRequest> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentCalendarProposeNewTimeForMeetingRequest>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::super::Foundation::Deferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Deferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs;{d2d777d8-fed1-4280-a3ba-2e1f47609aa2})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {
type Vtable = IAppointmentCalendarProposeNewTimeForMeetingRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd2d777d8_fed1_4280_a3ba_2e1f47609aa2);
}
impl ::windows::core::RuntimeName for AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs";
}
impl ::core::convert::From<AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {
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 AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {
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 AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {}
unsafe impl ::core::marker::Sync for AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarSyncManagerSyncRequest(pub ::windows::core::IInspectable);
impl AppointmentCalendarSyncManagerSyncRequest {
pub fn AppointmentCalendarLocalId(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportCompletedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportFailedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarSyncManagerSyncRequest {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarSyncManagerSyncRequest;{12ab382b-7163-4a56-9a4e-7223a84adf46})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarSyncManagerSyncRequest {
type Vtable = IAppointmentCalendarSyncManagerSyncRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x12ab382b_7163_4a56_9a4e_7223a84adf46);
}
impl ::windows::core::RuntimeName for AppointmentCalendarSyncManagerSyncRequest {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarSyncManagerSyncRequest";
}
impl ::core::convert::From<AppointmentCalendarSyncManagerSyncRequest> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarSyncManagerSyncRequest) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarSyncManagerSyncRequest> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarSyncManagerSyncRequest) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarSyncManagerSyncRequest {
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 AppointmentCalendarSyncManagerSyncRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarSyncManagerSyncRequest> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarSyncManagerSyncRequest) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarSyncManagerSyncRequest> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarSyncManagerSyncRequest) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarSyncManagerSyncRequest {
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 AppointmentCalendarSyncManagerSyncRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarSyncManagerSyncRequest {}
unsafe impl ::core::marker::Sync for AppointmentCalendarSyncManagerSyncRequest {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarSyncManagerSyncRequestEventArgs(pub ::windows::core::IInspectable);
impl AppointmentCalendarSyncManagerSyncRequestEventArgs {
pub fn Request(&self) -> ::windows::core::Result<AppointmentCalendarSyncManagerSyncRequest> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentCalendarSyncManagerSyncRequest>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::super::Foundation::Deferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Deferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarSyncManagerSyncRequestEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarSyncManagerSyncRequestEventArgs;{ca17c6f7-0284-4edd-87ba-4d8f69dcf5c0})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarSyncManagerSyncRequestEventArgs {
type Vtable = IAppointmentCalendarSyncManagerSyncRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca17c6f7_0284_4edd_87ba_4d8f69dcf5c0);
}
impl ::windows::core::RuntimeName for AppointmentCalendarSyncManagerSyncRequestEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarSyncManagerSyncRequestEventArgs";
}
impl ::core::convert::From<AppointmentCalendarSyncManagerSyncRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarSyncManagerSyncRequestEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarSyncManagerSyncRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarSyncManagerSyncRequestEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarSyncManagerSyncRequestEventArgs {
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 AppointmentCalendarSyncManagerSyncRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarSyncManagerSyncRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarSyncManagerSyncRequestEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarSyncManagerSyncRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarSyncManagerSyncRequestEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarSyncManagerSyncRequestEventArgs {
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 AppointmentCalendarSyncManagerSyncRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarSyncManagerSyncRequestEventArgs {}
unsafe impl ::core::marker::Sync for AppointmentCalendarSyncManagerSyncRequestEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarUpdateMeetingResponseRequest(pub ::windows::core::IInspectable);
impl AppointmentCalendarUpdateMeetingResponseRequest {
pub fn AppointmentCalendarLocalId(&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 AppointmentLocalId(&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 AppointmentOriginalStartTime(&self) -> ::windows::core::Result<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IReference<super::super::super::Foundation::DateTime>>(result__)
}
}
pub fn Response(&self) -> ::windows::core::Result<super::AppointmentParticipantResponse> {
let this = self;
unsafe {
let mut result__: super::AppointmentParticipantResponse = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::AppointmentParticipantResponse>(result__)
}
}
pub fn Subject(&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).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn Comment(&self) -> ::windows::core::Result<::windows::core::HSTRING> {
let this = self;
unsafe {
let mut result__: ::core::mem::ManuallyDrop<::windows::core::HSTRING> = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), &mut result__).from_abi::<::windows::core::HSTRING>(result__)
}
}
pub fn SendUpdate(&self) -> ::windows::core::Result<bool> {
let this = self;
unsafe {
let mut result__: bool = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), &mut result__).from_abi::<bool>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportCompletedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn ReportFailedAsync(&self) -> ::windows::core::Result<super::super::super::Foundation::IAsyncAction> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::IAsyncAction>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarUpdateMeetingResponseRequest {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarUpdateMeetingResponseRequest;{a36d608c-c29d-4b94-b086-7e9ff7bd84a0})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarUpdateMeetingResponseRequest {
type Vtable = IAppointmentCalendarUpdateMeetingResponseRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa36d608c_c29d_4b94_b086_7e9ff7bd84a0);
}
impl ::windows::core::RuntimeName for AppointmentCalendarUpdateMeetingResponseRequest {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarUpdateMeetingResponseRequest";
}
impl ::core::convert::From<AppointmentCalendarUpdateMeetingResponseRequest> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarUpdateMeetingResponseRequest) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarUpdateMeetingResponseRequest> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarUpdateMeetingResponseRequest) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarUpdateMeetingResponseRequest {
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 AppointmentCalendarUpdateMeetingResponseRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarUpdateMeetingResponseRequest> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarUpdateMeetingResponseRequest) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarUpdateMeetingResponseRequest> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarUpdateMeetingResponseRequest) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarUpdateMeetingResponseRequest {
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 AppointmentCalendarUpdateMeetingResponseRequest {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarUpdateMeetingResponseRequest {}
unsafe impl ::core::marker::Sync for AppointmentCalendarUpdateMeetingResponseRequest {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentCalendarUpdateMeetingResponseRequestEventArgs(pub ::windows::core::IInspectable);
impl AppointmentCalendarUpdateMeetingResponseRequestEventArgs {
pub fn Request(&self) -> ::windows::core::Result<AppointmentCalendarUpdateMeetingResponseRequest> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentCalendarUpdateMeetingResponseRequest>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn GetDeferral(&self) -> ::windows::core::Result<super::super::super::Foundation::Deferral> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), &mut result__).from_abi::<super::super::super::Foundation::Deferral>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentCalendarUpdateMeetingResponseRequestEventArgs {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarUpdateMeetingResponseRequestEventArgs;{88759883-97bf-479d-aed5-0be8ce567d1e})");
}
unsafe impl ::windows::core::Interface for AppointmentCalendarUpdateMeetingResponseRequestEventArgs {
type Vtable = IAppointmentCalendarUpdateMeetingResponseRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x88759883_97bf_479d_aed5_0be8ce567d1e);
}
impl ::windows::core::RuntimeName for AppointmentCalendarUpdateMeetingResponseRequestEventArgs {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentCalendarUpdateMeetingResponseRequestEventArgs";
}
impl ::core::convert::From<AppointmentCalendarUpdateMeetingResponseRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: AppointmentCalendarUpdateMeetingResponseRequestEventArgs) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentCalendarUpdateMeetingResponseRequestEventArgs> for ::windows::core::IUnknown {
fn from(value: &AppointmentCalendarUpdateMeetingResponseRequestEventArgs) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentCalendarUpdateMeetingResponseRequestEventArgs {
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 AppointmentCalendarUpdateMeetingResponseRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentCalendarUpdateMeetingResponseRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: AppointmentCalendarUpdateMeetingResponseRequestEventArgs) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentCalendarUpdateMeetingResponseRequestEventArgs> for ::windows::core::IInspectable {
fn from(value: &AppointmentCalendarUpdateMeetingResponseRequestEventArgs) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentCalendarUpdateMeetingResponseRequestEventArgs {
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 AppointmentCalendarUpdateMeetingResponseRequestEventArgs {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentCalendarUpdateMeetingResponseRequestEventArgs {}
unsafe impl ::core::marker::Sync for AppointmentCalendarUpdateMeetingResponseRequestEventArgs {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentDataProviderConnection(pub ::windows::core::IInspectable);
impl AppointmentDataProviderConnection {
#[cfg(feature = "Foundation")]
pub fn SyncRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<AppointmentDataProviderConnection, AppointmentCalendarSyncManagerSyncRequestEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveSyncRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn CreateOrUpdateAppointmentRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<AppointmentDataProviderConnection, AppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveCreateOrUpdateAppointmentRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn CancelMeetingRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<AppointmentDataProviderConnection, AppointmentCalendarCancelMeetingRequestEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveCancelMeetingRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ForwardMeetingRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<AppointmentDataProviderConnection, AppointmentCalendarForwardMeetingRequestEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveForwardMeetingRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn ProposeNewTimeForMeetingRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<AppointmentDataProviderConnection, AppointmentCalendarProposeNewTimeForMeetingRequestEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveProposeNewTimeForMeetingRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
#[cfg(feature = "Foundation")]
pub fn UpdateMeetingResponseRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<AppointmentDataProviderConnection, AppointmentCalendarUpdateMeetingResponseRequestEventArgs>>>(&self, handler: Param0) -> ::windows::core::Result<super::super::super::Foundation::EventRegistrationToken> {
let this = self;
unsafe {
let mut result__: super::super::super::Foundation::EventRegistrationToken = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), handler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__)
}
}
#[cfg(feature = "Foundation")]
pub fn RemoveUpdateMeetingResponseRequested<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::EventRegistrationToken>>(&self, token: Param0) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), token.into_param().abi()).ok() }
}
pub fn Start(&self) -> ::windows::core::Result<()> {
let this = self;
unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this)).ok() }
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentDataProviderConnection {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentDataProviderConnection;{f3dd9d83-3254-465f-abdb-928046552cf4})");
}
unsafe impl ::windows::core::Interface for AppointmentDataProviderConnection {
type Vtable = IAppointmentDataProviderConnection_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf3dd9d83_3254_465f_abdb_928046552cf4);
}
impl ::windows::core::RuntimeName for AppointmentDataProviderConnection {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentDataProviderConnection";
}
impl ::core::convert::From<AppointmentDataProviderConnection> for ::windows::core::IUnknown {
fn from(value: AppointmentDataProviderConnection) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentDataProviderConnection> for ::windows::core::IUnknown {
fn from(value: &AppointmentDataProviderConnection) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentDataProviderConnection {
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 AppointmentDataProviderConnection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentDataProviderConnection> for ::windows::core::IInspectable {
fn from(value: AppointmentDataProviderConnection) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentDataProviderConnection> for ::windows::core::IInspectable {
fn from(value: &AppointmentDataProviderConnection) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentDataProviderConnection {
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 AppointmentDataProviderConnection {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentDataProviderConnection {}
unsafe impl ::core::marker::Sync for AppointmentDataProviderConnection {}
#[repr(transparent)]
#[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)]
pub struct AppointmentDataProviderTriggerDetails(pub ::windows::core::IInspectable);
impl AppointmentDataProviderTriggerDetails {
pub fn Connection(&self) -> ::windows::core::Result<AppointmentDataProviderConnection> {
let this = self;
unsafe {
let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed();
(::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AppointmentDataProviderConnection>(result__)
}
}
}
unsafe impl ::windows::core::RuntimeType for AppointmentDataProviderTriggerDetails {
const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.ApplicationModel.Appointments.DataProvider.AppointmentDataProviderTriggerDetails;{b3283c01-7e12-4e5e-b1ef-74fb68ac6f2a})");
}
unsafe impl ::windows::core::Interface for AppointmentDataProviderTriggerDetails {
type Vtable = IAppointmentDataProviderTriggerDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb3283c01_7e12_4e5e_b1ef_74fb68ac6f2a);
}
impl ::windows::core::RuntimeName for AppointmentDataProviderTriggerDetails {
const NAME: &'static str = "Windows.ApplicationModel.Appointments.DataProvider.AppointmentDataProviderTriggerDetails";
}
impl ::core::convert::From<AppointmentDataProviderTriggerDetails> for ::windows::core::IUnknown {
fn from(value: AppointmentDataProviderTriggerDetails) -> Self {
value.0 .0
}
}
impl ::core::convert::From<&AppointmentDataProviderTriggerDetails> for ::windows::core::IUnknown {
fn from(value: &AppointmentDataProviderTriggerDetails) -> Self {
value.0 .0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AppointmentDataProviderTriggerDetails {
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 AppointmentDataProviderTriggerDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> {
::windows::core::Param::Borrowed(&self.0 .0)
}
}
impl ::core::convert::From<AppointmentDataProviderTriggerDetails> for ::windows::core::IInspectable {
fn from(value: AppointmentDataProviderTriggerDetails) -> Self {
value.0
}
}
impl ::core::convert::From<&AppointmentDataProviderTriggerDetails> for ::windows::core::IInspectable {
fn from(value: &AppointmentDataProviderTriggerDetails) -> Self {
value.0.clone()
}
}
impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AppointmentDataProviderTriggerDetails {
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 AppointmentDataProviderTriggerDetails {
fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> {
::windows::core::Param::Borrowed(&self.0)
}
}
unsafe impl ::core::marker::Send for AppointmentDataProviderTriggerDetails {}
unsafe impl ::core::marker::Sync for AppointmentDataProviderTriggerDetails {}
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarCancelMeetingRequest(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarCancelMeetingRequest {
type Vtable = IAppointmentCalendarCancelMeetingRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x49460f8d_6434_40d7_ad46_6297419314d1);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarCancelMeetingRequest_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarCancelMeetingRequestEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarCancelMeetingRequestEventArgs {
type Vtable = IAppointmentCalendarCancelMeetingRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x1a79be16_7f30_4e35_beef_9d2c7b6dcae1);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarCancelMeetingRequestEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarCreateOrUpdateAppointmentRequest(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarCreateOrUpdateAppointmentRequest {
type Vtable = IAppointmentCalendarCreateOrUpdateAppointmentRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x2e62f2b2_ca96_48ac_9124_406b19fefa70);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarCreateOrUpdateAppointmentRequest_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, createdorupdatedappointment: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs {
type Vtable = IAppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xcf8ded28_002e_4bf7_8e9d_5e20d49aa3ba);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarCreateOrUpdateAppointmentRequestEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarForwardMeetingRequest(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarForwardMeetingRequest {
type Vtable = IAppointmentCalendarForwardMeetingRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x82e5ee56_26b6_4253_8a8f_6cf5f2ff7884);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarForwardMeetingRequest_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation_Collections")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation_Collections"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarForwardMeetingRequestEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarForwardMeetingRequestEventArgs {
type Vtable = IAppointmentCalendarForwardMeetingRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x3109151a_23a2_42fd_9c82_c9a60d59f8a8);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarForwardMeetingRequestEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarProposeNewTimeForMeetingRequest(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarProposeNewTimeForMeetingRequest {
type Vtable = IAppointmentCalendarProposeNewTimeForMeetingRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xce1c63f5_edf6_43c3_82b7_be6b368c6900);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarProposeNewTimeForMeetingRequest_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::DateTime) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::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 ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarProposeNewTimeForMeetingRequestEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarProposeNewTimeForMeetingRequestEventArgs {
type Vtable = IAppointmentCalendarProposeNewTimeForMeetingRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xd2d777d8_fed1_4280_a3ba_2e1f47609aa2);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarProposeNewTimeForMeetingRequestEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarSyncManagerSyncRequest(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarSyncManagerSyncRequest {
type Vtable = IAppointmentCalendarSyncManagerSyncRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x12ab382b_7163_4a56_9a4e_7223a84adf46);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarSyncManagerSyncRequest_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,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarSyncManagerSyncRequestEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarSyncManagerSyncRequestEventArgs {
type Vtable = IAppointmentCalendarSyncManagerSyncRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xca17c6f7_0284_4edd_87ba_4d8f69dcf5c0);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarSyncManagerSyncRequestEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarUpdateMeetingResponseRequest(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarUpdateMeetingResponseRequest {
type Vtable = IAppointmentCalendarUpdateMeetingResponseRequest_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xa36d608c_c29d_4b94_b086_7e9ff7bd84a0);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarUpdateMeetingResponseRequest_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 ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut super::AppointmentParticipantResponse) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentCalendarUpdateMeetingResponseRequestEventArgs(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentCalendarUpdateMeetingResponseRequestEventArgs {
type Vtable = IAppointmentCalendarUpdateMeetingResponseRequestEventArgs_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x88759883_97bf_479d_aed5_0be8ce567d1e);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentCalendarUpdateMeetingResponseRequestEventArgs_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentDataProviderConnection(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentDataProviderConnection {
type Vtable = IAppointmentDataProviderConnection_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xf3dd9d83_3254_465f_abdb_928046552cf4);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentDataProviderConnection_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, handler: ::windows::core::RawPtr, result__: *mut super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
#[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, token: super::super::super::Foundation::EventRegistrationToken) -> ::windows::core::HRESULT,
#[cfg(not(feature = "Foundation"))] usize,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
#[repr(transparent)]
#[doc(hidden)]
pub struct IAppointmentDataProviderTriggerDetails(pub ::windows::core::IInspectable);
unsafe impl ::windows::core::Interface for IAppointmentDataProviderTriggerDetails {
type Vtable = IAppointmentDataProviderTriggerDetails_abi;
const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0xb3283c01_7e12_4e5e_b1ef_74fb68ac6f2a);
}
#[repr(C)]
#[doc(hidden)]
pub struct IAppointmentDataProviderTriggerDetails_abi(
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT,
pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT,
);
|
// 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.
//! A state machine for associating a Client to a BSS.
//! Note: This implementation only supports simultaneous authentication with exactly one STA, the
//! AP. While 802.11 explicitly allows - and sometime requires - authentication with more than one
//! STA, Fuchsia does intentionally not yet support this use-case.
use {
crate::{
auth,
client::{Client, TimedEvent},
timer::*,
},
fidl_fuchsia_wlan_mlme as fidl_mlme,
log::{error, info},
wlan_common::{mac, time::deadline_after_beacons},
wlan_statemachine::*,
zerocopy::ByteSlice,
};
/// Client joined a BSS (synchronized timers and prepared its underlying hardware).
/// At this point the Client is able to listen to frames on the BSS' channel.
pub struct Joined;
impl Joined {
/// Initiates an open authentication with the currently joined BSS.
/// The returned state is unchanged in an error case. Otherwise, the state transitions into
/// "Authenticating".
/// Returns Ok(timeout) if authentication request was sent successfully, Err(()) otherwise.
fn authenticate(&self, sta: &mut Client, timeout_bcn_count: u8) -> Result<EventId, ()> {
match sta.send_open_auth_frame() {
Ok(()) => {
let deadline = deadline_after_beacons(timeout_bcn_count);
let event = TimedEvent::Authenticating;
let event_id = sta.timer.schedule_event(deadline, event);
Ok(event_id)
}
Err(e) => {
error!("{}", e);
sta.send_authenticate_conf(fidl_mlme::AuthenticateResultCodes::Refused);
Err(())
}
}
}
}
/// Client issued an authentication request frame to its joined BSS prior to joining this state.
/// At this point the client is waiting for an authentication response frame from the client.
/// Note: This assumes Open System authentication.
pub struct Authenticating {
timeout: EventId,
}
impl Authenticating {
/// Processes an inbound authentication frame.
/// SME will be notified via an MLME-AUTHENTICATE.confirm message whether the authentication
/// with the BSS was successful.
/// Returns Ok(()) if the authentication was successful, otherwise Err(()).
/// Note: The pending authentication timeout will be canceled in any case.
fn on_auth_frame(&self, sta: &mut Client, auth_hdr: &mac::AuthHdr) -> Result<(), ()> {
sta.timer.cancel_event(self.timeout);
match auth::is_valid_open_ap_resp(auth_hdr) {
Ok(()) => {
sta.send_authenticate_conf(fidl_mlme::AuthenticateResultCodes::Success);
Ok(())
}
Err(e) => {
error!("authentication with BSS failed: {}", e);
sta.send_authenticate_conf(fidl_mlme::AuthenticateResultCodes::Refused);
Err(())
}
}
}
/// Processes an inbound deauthentication frame.
/// This always results in an MLME-AUTHENTICATE.confirm message to MLME's SME peer.
/// The pending authentication timeout will be canceled in this process.
fn on_deauth_frame(&self, sta: &mut Client, deauth_hdr: &mac::DeauthHdr) {
sta.timer.cancel_event(self.timeout);
info!(
"received spurious deauthentication frame while authenticating with BSS (unusual); \
authentication failed: {:?}",
{ deauth_hdr.reason_code }
);
sta.send_authenticate_conf(fidl_mlme::AuthenticateResultCodes::Refused);
}
/// Invoked when the pending timeout fired. The original authentication request is now
/// considered to be expired and invalid - the authentication failed. As a consequence,
/// an MLME-AUTHENTICATION.confirm message is reported to MLME's SME peer indicating the
/// timeout.
fn on_timeout(&self, sta: &mut Client) {
// At this point, the event should already be canceled by the state's owner. However,
// ensure the timeout is canceled in any case.
sta.timer.cancel_event(self.timeout);
sta.send_authenticate_conf(fidl_mlme::AuthenticateResultCodes::AuthFailureTimeout);
}
}
/// Client received a "successful" authentication response from the BSS.
pub struct Authenticated;
impl Authenticated {
/// Processes an inbound deauthentication frame.
/// This always results in an MLME-DEAUTHENTICATE.indication message to MLME's SME peer.
fn on_deauth_frame(&self, sta: &mut Client, deauth_hdr: &mac::DeauthHdr) {
let reason_code = fidl_mlme::ReasonCode::from_primitive(deauth_hdr.reason_code.0)
.unwrap_or(fidl_mlme::ReasonCode::UnspecifiedReason);
sta.send_deauthenticate_ind(reason_code);
}
}
statemachine!(
/// Client state machine.
/// Note: Only authentication is supported right now.
pub enum States,
// Regular successful flow:
() => Joined,
Joined => Authenticating,
Authenticating => Authenticated,
// Deauthentication & Timeout:
Authenticating => Joined,
// Deauthentication:
Authenticated => Joined,
);
impl States {
/// Returns the STA's initial state.
pub fn new_initial() -> States {
States::from(State::new(Joined))
}
/// Only Open System authentication is supported.
/// Shared Key authentication is intentionally unsupported within Fuchsia.
/// SAE will be supported sometime in the future.
pub fn authenticate(self, sta: &mut Client, timeout_bcn_count: u8) -> States {
match self {
// MLME-AUTHENTICATE.request messages are only processed when the Client is "Joined".
States::Joined(state) => match state.authenticate(sta, timeout_bcn_count) {
Ok(timeout) => state.transition_to(Authenticating { timeout }).into(),
Err(()) => state.into(),
},
// Reject MLME-AUTHENTICATE.request if STA is not in "Joined" state.
_ => {
error!("received MLME-AUTHENTICATE.request in invalid state");
sta.send_authenticate_conf(fidl_mlme::AuthenticateResultCodes::Refused);
self
}
}
}
/// Callback to process arbitrary IEEE 802.11 frames.
/// Frames are dropped if:
/// - frames are corrupted (too short)
/// - frames' frame class is not yet permitted
pub fn on_mac_frame<B: ByteSlice>(
self,
sta: &mut Client,
bytes: B,
body_aligned: bool,
) -> States {
// Parse mac frame. Drop corrupted ones.
let mac_frame = match mac::MacFrame::parse(bytes, body_aligned) {
Some(mac_frame) => mac_frame,
None => return self,
};
// Drop frames which are not permitted in the STA's current state.
let frame_class = mac::FrameClass::from(&mac_frame);
if !self.is_frame_class_permitted(frame_class) {
return self;
}
match mac_frame {
mac::MacFrame::Mgmt { mgmt_hdr, body, .. } => self.on_mgmt_frame(sta, &mgmt_hdr, body),
// Data and Control frames are not yet supported. Drop them.
_ => self,
}
}
/// Processes inbound management frames.
/// Only frames from the joined BSS are processed. Frames from other STAs are dropped.
fn on_mgmt_frame<B: ByteSlice>(
self,
sta: &mut Client,
mgmt_hdr: &mac::MgmtHdr,
body: B,
) -> States {
if mgmt_hdr.addr3 != sta.bssid.0 {
return self;
}
// Parse management frame. Drop corrupted ones.
let mgmt_body = match mac::MgmtBody::parse({ mgmt_hdr.frame_ctrl }.mgmt_subtype(), body) {
Some(x) => x,
None => return self,
};
match self {
States::Authenticating(state) => match mgmt_body {
mac::MgmtBody::Authentication { auth_hdr, .. } => {
match state.on_auth_frame(sta, &auth_hdr) {
Ok(()) => state.transition_to(Authenticated).into(),
Err(()) => state.transition_to(Joined).into(),
}
}
mac::MgmtBody::Deauthentication { deauth_hdr, .. } => {
state.on_deauth_frame(sta, &deauth_hdr);
state.transition_to(Joined).into()
}
_ => state.into(),
},
States::Authenticated(state) => match mgmt_body {
mac::MgmtBody::Deauthentication { deauth_hdr, .. } => {
state.on_deauth_frame(sta, &deauth_hdr);
state.transition_to(Joined).into()
}
_ => state.into(),
},
_ => self,
}
}
/// Callback when a previously scheduled event fired.
pub fn on_timed_event(self, sta: &mut Client, event_id: EventId) -> States {
// Lookup the event matching the given id.
let event = match sta.timer.triggered(&event_id) {
Some(event) => event,
None => {
error!(
"event for given ID already consumed;\
this should NOT happen - ignoring event"
);
return self;
}
};
// Process event.
match event {
TimedEvent::Authenticating => match self {
States::Authenticating(state) => {
state.on_timeout(sta);
state.transition_to(Joined).into()
}
_ => {
error!("received Authenticating timeout in unexpected state; ignoring timeout");
self
}
},
}
}
/// Returns |true| iff a given FrameClass is permitted to be processed in the current state.
fn is_frame_class_permitted(&self, frame_class: mac::FrameClass) -> bool {
match self {
States::Joined(_) | States::Authenticating(_) => frame_class == mac::FrameClass::Class1,
States::Authenticated(_) => frame_class <= mac::FrameClass::Class2,
}
}
}
#[cfg(test)]
mod tests {
use {
super::*,
crate::{
buffer::FakeBufferProvider,
device::{Device, FakeDevice},
},
fuchsia_zircon::{self as zx, DurationNum},
wlan_common::{
assert_variant,
mac::{Bssid, MacAddr},
},
wlan_statemachine as statemachine,
};
const BSSID: Bssid = Bssid([6u8; 6]);
const IFACE_MAC: MacAddr = [7u8; 6];
fn make_client_station(device: Device, scheduler: Scheduler) -> Client {
let buf_provider = FakeBufferProvider::new();
let client = Client::new(device, buf_provider, scheduler, BSSID, IFACE_MAC);
client
}
#[test]
fn join_state_authenticate_success() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let state = Joined;
let timeout_id = state.authenticate(&mut sta, 10).expect("failed authenticating");
// Verify an event was queued up in the timer.
assert_variant!(sta.timer.triggered(&timeout_id), Some(TimedEvent::Authenticating));
// Verify authentication frame was sent to AP.
assert_eq!(device.wlan_queue.len(), 1);
let (frame, _txflags) = device.wlan_queue.remove(0);
#[rustfmt::skip]
let expected = vec![
// Mgmt Header:
0b1011_00_00, 0b00000000, // Frame Control
0, 0, // Duration
6, 6, 6, 6, 6, 6, // Addr1
7, 7, 7, 7, 7, 7, // Addr2
6, 6, 6, 6, 6, 6, // Addr3
0x10, 0, // Sequence Control
// Auth Header:
0, 0, // Algorithm Number (Open)
1, 0, // Txn Sequence Number
0, 0, // Status Code
];
assert_eq!(&frame[..], &expected[..]);
// Verify no MLME message was sent yet.
device.next_mlme_msg::<fidl_mlme::AuthenticateConfirm>().expect_err("unexpected message");
}
#[test]
fn join_state_authenticate_tx_failure() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta =
make_client_station(device.as_device_fail_wlan_tx(), scheduler.as_scheduler());
let state = Joined;
state.authenticate(&mut sta, 10).expect_err("should fail authenticating");
// Verify no event was queued up in the timer.
assert_eq!(sta.timer.scheduled_event_count(), 0);
// Verify MLME-AUTHENTICATE.confirm message was sent.
let msg = device.next_mlme_msg::<fidl_mlme::AuthenticateConfirm>().expect("no message");
assert_eq!(
msg,
fidl_mlme::AuthenticateConfirm {
peer_sta_address: BSSID.0,
auth_type: fidl_mlme::AuthenticationTypes::OpenSystem,
result_code: fidl_mlme::AuthenticateResultCodes::Refused,
}
);
}
#[test]
fn authenticating_state_auth_success() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let timeout =
sta.timer.schedule_event(zx::Time::after(1.seconds()), TimedEvent::Authenticating);
let state = Authenticating { timeout };
// Verify authentication was considered successful.
state
.on_auth_frame(
&mut sta,
&mac::AuthHdr {
auth_alg_num: mac::AuthAlgorithmNumber::OPEN,
auth_txn_seq_num: 2,
status_code: mac::StatusCode::SUCCESS,
},
)
.expect("failed processing auth frame");
// Verify timeout was canceled.
assert_variant!(sta.timer.triggered(&timeout), None);
// Verify MLME-AUTHENTICATE.confirm message was sent.
let msg = device.next_mlme_msg::<fidl_mlme::AuthenticateConfirm>().expect("no message");
assert_eq!(
msg,
fidl_mlme::AuthenticateConfirm {
peer_sta_address: BSSID.0,
auth_type: fidl_mlme::AuthenticationTypes::OpenSystem,
result_code: fidl_mlme::AuthenticateResultCodes::Success,
}
);
}
#[test]
fn authenticating_state_auth_rejected() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let timeout =
sta.timer.schedule_event(zx::Time::after(1.seconds()), TimedEvent::Authenticating);
let state = Authenticating { timeout };
// Verify authentication was considered successful.
state
.on_auth_frame(
&mut sta,
&mac::AuthHdr {
auth_alg_num: mac::AuthAlgorithmNumber::OPEN,
auth_txn_seq_num: 2,
status_code: mac::StatusCode::NOT_IN_SAME_BSS,
},
)
.expect_err("expected failure processing auth frame");
// Verify timeout was canceled.
assert_variant!(sta.timer.triggered(&timeout), None);
// Verify MLME-AUTHENTICATE.confirm message was sent.
let msg = device.next_mlme_msg::<fidl_mlme::AuthenticateConfirm>().expect("no message");
assert_eq!(
msg,
fidl_mlme::AuthenticateConfirm {
peer_sta_address: BSSID.0,
auth_type: fidl_mlme::AuthenticationTypes::OpenSystem,
result_code: fidl_mlme::AuthenticateResultCodes::Refused,
}
);
}
#[test]
fn authenticating_state_timeout() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let timeout =
sta.timer.schedule_event(zx::Time::after(1.seconds()), TimedEvent::Authenticating);
let state = Authenticating { timeout };
state.on_timeout(&mut sta);
// Verify timeout was canceled.
assert_variant!(sta.timer.triggered(&timeout), None);
// Verify MLME-AUTHENTICATE.confirm message was sent.
let msg = device.next_mlme_msg::<fidl_mlme::AuthenticateConfirm>().expect("no message");
assert_eq!(
msg,
fidl_mlme::AuthenticateConfirm {
peer_sta_address: BSSID.0,
auth_type: fidl_mlme::AuthenticationTypes::OpenSystem,
result_code: fidl_mlme::AuthenticateResultCodes::AuthFailureTimeout,
}
);
}
#[test]
fn authenticating_state_deauth() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let timeout =
sta.timer.schedule_event(zx::Time::after(1.seconds()), TimedEvent::Authenticating);
let state = Authenticating { timeout };
state.on_deauth_frame(
&mut sta,
&mac::DeauthHdr { reason_code: mac::ReasonCode::NO_MORE_STAS },
);
// Verify timeout was canceled.
assert_variant!(sta.timer.triggered(&timeout), None);
// Verify MLME-AUTHENTICATE.confirm message was sent.
let msg = device.next_mlme_msg::<fidl_mlme::AuthenticateConfirm>().expect("no message");
assert_eq!(
msg,
fidl_mlme::AuthenticateConfirm {
peer_sta_address: BSSID.0,
auth_type: fidl_mlme::AuthenticationTypes::OpenSystem,
result_code: fidl_mlme::AuthenticateResultCodes::Refused,
}
);
}
#[test]
fn authenticated_state_deauth() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let state = Authenticated;
state.on_deauth_frame(
&mut sta,
&mac::DeauthHdr { reason_code: mac::ReasonCode::NO_MORE_STAS },
);
// Verify MLME-DEAUTHENTICATE.indication message was sent.
let msg =
device.next_mlme_msg::<fidl_mlme::DeauthenticateIndication>().expect("no message");
assert_eq!(
msg,
fidl_mlme::DeauthenticateIndication {
peer_sta_address: BSSID.0,
reason_code: fidl_mlme::ReasonCode::NoMoreStas,
}
);
}
#[test]
fn state_transitions_joined_authing() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let mut state = States::new_initial();
assert_variant!(state, States::Joined(_), "not in joined state");
// Successful: Joined > Authenticating
state = state.authenticate(&mut sta, 10);
assert_variant!(state, States::Authenticating(_), "not in auth'ing state");
}
#[test]
fn state_transitions_authing_success() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let mut state = States::from(statemachine::testing::new_state(Authenticating {
timeout: EventId::default(),
}));
// Successful: Joined > Authenticating > Authenticated
#[rustfmt::skip]
let auth_resp_success = vec![
// Mgmt Header:
0b1011_00_00, 0b00000000, // Frame Control
0, 0, // Duration
6, 6, 6, 6, 6, 6, // Addr1
7, 7, 7, 7, 7, 7, // Addr2
6, 6, 6, 6, 6, 6, // Addr3
0x10, 0, // Sequence Control
// Auth Header:
0, 0, // Algorithm Number (Open)
2, 0, // Txn Sequence Number
0, 0, // Status Code
];
state = state.on_mac_frame(&mut sta, &auth_resp_success[..], false);
assert_variant!(state, States::Authenticated(_), "not in auth'ed state");
}
#[test]
fn state_transitions_authing_failure() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let mut state = States::from(statemachine::testing::new_state(Authenticating {
timeout: EventId::default(),
}));
// Failure: Joined > Authenticating > Joined
#[rustfmt::skip]
let auth_resp_failure = vec![
// Mgmt Header:
0b1011_00_00, 0b00000000, // Frame Control
0, 0, // Duration
6, 6, 6, 6, 6, 6, // Addr1
7, 7, 7, 7, 7, 7, // Addr2
6, 6, 6, 6, 6, 6, // Addr3
0x10, 0, // Sequence Control
// Auth Header:
0, 0, // Algorithm Number (Open)
2, 0, // Txn Sequence Number
42, 0, // Status Code
];
state = state.on_mac_frame(&mut sta, &auth_resp_failure[..], false);
assert_variant!(state, States::Joined(_), "not in joined state");
}
#[test]
fn state_transitions_authing_timeout() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let mut state = States::new_initial();
assert_variant!(state, States::Joined(_), "not in joined state");
// Timeout: Joined > Authenticating > Joined
state = state.authenticate(&mut sta, 10);
let timeout_id = assert_variant!(state, States::Authenticating(ref state) => {
state.timeout
}, "not in auth'ing state");
state = state.on_timed_event(&mut sta, timeout_id);
assert_variant!(state, States::Joined(_), "not in joined state");
}
#[test]
fn state_transitions_authing_deauth() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let mut state = States::from(statemachine::testing::new_state(Authenticating {
timeout: EventId::default(),
}));
// Deauthenticate: Authenticating > Joined
#[rustfmt::skip]
let deauth = vec![
// Mgmt Header:
0b1100_00_00, 0b00000000, // Frame Control
0, 0, // Duration
6, 6, 6, 6, 6, 6, // Addr1
7, 7, 7, 7, 7, 7, // Addr2
6, 6, 6, 6, 6, 6, // Addr3
0x10, 0, // Sequence Control
// Deauth Header:
5, 0, // Algorithm Number (Open)
];
state = state.on_mac_frame(&mut sta, &deauth[..], false);
assert_variant!(state, States::Joined(_), "not in joined state");
}
#[test]
fn state_transitions_authed() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let mut state = States::from(statemachine::testing::new_state(Authenticated));
// Deauthenticate: Authenticated > Joined
#[rustfmt::skip]
let deauth = vec![
// Mgmt Header:
0b1100_00_00, 0b00000000, // Frame Control
0, 0, // Duration
6, 6, 6, 6, 6, 6, // Addr1
7, 7, 7, 7, 7, 7, // Addr2
6, 6, 6, 6, 6, 6, // Addr3
0x10, 0, // Sequence Control
// Deauth Header:
5, 0, // Algorithm Number (Open)
];
state = state.on_mac_frame(&mut sta, &deauth[..], false);
assert_variant!(state, States::Joined(_), "not in joined state");
}
#[test]
fn state_transitions_foreign_auth_resp() {
let mut device = FakeDevice::new();
let mut scheduler = FakeScheduler::new();
let mut sta = make_client_station(device.as_device(), scheduler.as_scheduler());
let mut state = States::from(statemachine::testing::new_state(Authenticating {
timeout: EventId::default(),
}));
// Send foreign auth response. State should not change.
#[rustfmt::skip]
let auth_resp_success = vec![
// Mgmt Header:
0b1011_00_00, 0b00000000, // Frame Control
0, 0, // Duration
5, 5, 5, 5, 5, 5, // Addr1
7, 7, 7, 7, 7, 7, // Addr2
5, 5, 5, 5, 5, 5, // Addr3
0x10, 0, // Sequence Control
// Auth Header:
0, 0, // Algorithm Number (Open)
2, 0, // Txn Sequence Number
0, 0, // Status Code
];
state = state.on_mac_frame(&mut sta, &auth_resp_success[..], false);
assert_variant!(state, States::Authenticating(_), "not in auth'ing state");
// Verify that an authentication response from the joined BSS still moves the Client
// forward.
#[rustfmt::skip]
let auth_resp_success = vec![
// Mgmt Header:
0b1011_00_00, 0b00000000, // Frame Control
0, 0, // Duration
6, 6, 6, 6, 6, 6, // Addr1
7, 7, 7, 7, 7, 7, // Addr2
6, 6, 6, 6, 6, 6, // Addr3
0x10, 0, // Sequence Control
// Auth Header:
0, 0, // Algorithm Number (Open)
2, 0, // Txn Sequence Number
0, 0, // Status Code
];
state = state.on_mac_frame(&mut sta, &auth_resp_success[..], false);
assert_variant!(state, States::Authenticated(_), "not in auth'ed state");
}
}
|
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(PartialEq, Clone, Serialize, Deserialize, Debug)]
pub struct Activity {
pub id: String,
pub lat: f64,
pub lon: f64,
}
#[allow(dead_code)]
impl Activity {
fn new(id: String, lat: f64, lon: f64) -> Activity {
Activity { id, lat, lon }
}
}
#[derive(PartialEq, Clone, Serialize, Deserialize, Debug)]
pub struct Resource {
pub id: String,
pub lat: f64,
pub lon: f64,
}
#[allow(dead_code)]
impl Resource {
pub fn new(id: String, lat: f64, lon: f64) -> Resource {
Resource { id, lat, lon }
}
}
#[derive(PartialEq, Clone, Serialize, Deserialize, Debug)]
pub struct Allocation {
pub activity_id: String,
pub dist: f64,
pub time: f64,
pub travel_to: f64,
pub travel_from: f64,
}
#[allow(dead_code)]
impl Allocation {
pub fn new(activity_id: String, dist: f64, time: f64, travel_from: f64, travel_to: f64) -> Allocation {
Allocation { activity_id, dist, time, travel_to, travel_from }
}
}
#[derive(PartialEq, Clone, Serialize, Deserialize, Debug)]
pub struct Route {
pub resource_id: String,
pub allocation: Vec<String>,
pub time: f64,
}
#[allow(dead_code)]
impl Route {
pub fn new(resource_id: String, time: f64) -> Route {
Route { resource_id, allocation: Vec::new(), time }
}
}
#[derive(PartialEq, Clone, Serialize, Deserialize, Default, Debug)]
pub struct Status {
pub start_time: f64,
pub new_data: bool,
pub changed: bool,
pub quality: f64,
pub distance: f64,
pub value: f64,
pub travel_time: f64,
}
#[derive(PartialEq, Clone, Serialize, Deserialize, Default, Debug)]
pub struct SchemaData {
pub activity: HashMap<String, Activity>,
pub resource: HashMap<String, Resource>,
pub allocation: HashMap<String, Allocation>,
pub route: Vec<Route>,
pub status: Option<Status>,
}
|
use nodes::prelude::*;
pub struct Aside {
inner: NodeP
}
impl Aside {
pub fn new(inner: NodeP) -> Aside {
Aside {
inner: inner
}
}
}
impl Node for Aside {
fn childs(&self, out: &mut Vec<NodeP>) {
self.inner.childs(out);
}
fn layout(&self, env: LayoutChain, w: &mut Writer) {
// TODO: Add counter
w.anchor(&mut |w| self.inner.layout(env.clone(), w));
}
fn fields(&self) -> Option<&Fields> {
None
}
}
|
extern crate ws;
use ws::listen;
fn main() {
let listen_url = "0.0.0.0:8082";
//let listen_url ="127.0.0.1:8082";
println!("Runing Server");
listen(listen_url, |out| {
move |msg| {
let response: String = format!("Hello {}", msg);
println!("{}", response);
out.send(response)
}
})
.unwrap()
// TODO: Addressが既に使われている場合、unwrap()でErrが返されpanicになる
}
|
use std::mem;
use std::cell::UnsafeCell;
pub struct Arena {
data: UnsafeCell<Vec<Vec<u8>>>,
}
impl Arena {
pub fn with_capacity(capacity: usize) -> Arena {
Arena {
data: UnsafeCell::new(vec![Vec::with_capacity(capacity)]),
}
}
fn alloc_bytes(&self, bytes: usize, align: usize) -> *mut u8 {
let mut data = unsafe { &mut *self.data.get() };
let (ptr, len, capacity) = {
let last = &data.last().unwrap();
let len = last.len();
(last.as_ptr() as usize + len, len, last.capacity())
};
let offset = ((ptr + align - 1) & !(align - 1)) - ptr;
if len + offset + bytes > capacity {
let size = capacity.max(bytes);
data.push(Vec::with_capacity(size.saturating_add(size)));
}
let last = &mut data.last_mut().unwrap();
unsafe {
last.set_len(len + offset + bytes);
last.as_mut_ptr().offset((len + offset) as isize)
}
}
pub fn alloc<'a, T: Copy>(&'a self, value: T) -> &'a mut T {
let ptr = self.alloc_bytes(mem::size_of::<T>(), mem::align_of::<T>());
let result: &'a mut T = unsafe { &mut *(ptr as *mut T) };
*result = value;
result
}
pub fn alloc_slice<'a, T: Copy>(&'a self, values: &[T]) -> &'a mut [T] {
let ptr = self.alloc_bytes(mem::size_of::<T>() * values.len(), mem::align_of::<T>());
let result: &'a mut [T] = unsafe { std::slice::from_raw_parts_mut(ptr as *mut T, values.len()) };
result.copy_from_slice(values);
result
}
pub fn alloc_slice_repeat<'a, T: Copy>(&'a self, value: T, len: usize) -> &'a mut [T] {
let ptr = self.alloc_bytes(mem::size_of::<T>() * len, mem::align_of::<T>());
let result: &'a mut [T] = unsafe { std::slice::from_raw_parts_mut(ptr as *mut T, len) };
for item in result.iter_mut() {
*item = value;
}
result
}
pub fn alloc_slice_default<'a, T: Copy + Default>(&'a self, len: usize) -> &'a mut [T] {
self.alloc_slice_repeat(T::default(), len)
}
pub fn alloc_str<'a>(&'a self, string: &str) -> &'a mut str {
let bytes = self.alloc_slice(string.as_bytes());
unsafe { std::str::from_utf8_unchecked_mut(bytes) }
}
}
#[test]
fn test_overflow() {
let mut arena = Arena::with_capacity(4);
let x: &mut u64 = arena.alloc(3);
assert_eq!(*x, 3);
assert_eq!(arena.data.len(), 2);
}
#[test]
fn test_alignment() {
let mut arena = Arena::with_capacity(1024);
let x: &mut u8 = arena.alloc(3);
assert_eq!(x as *mut u8 as usize % mem::align_of::<u8>(), 0);
let x: &mut u16 = arena.alloc(3);
assert_eq!(x as *mut u16 as usize % mem::align_of::<u16>(), 0);
let x: &mut u32 = arena.alloc(3);
assert_eq!(x as *mut u32 as usize % mem::align_of::<u32>(), 0);
let x: &mut u64 = arena.alloc(3);
assert_eq!(x as *mut u64 as usize % mem::align_of::<u64>(), 0);
}
#[test]
fn test_slice() {
let mut arena = Arena::with_capacity(1024);
let xs: [u32; 16] = [0; 16];
let ys = arena.alloc_slice(&xs);
assert_eq!(xs, ys);
}
pub struct Slab<T> {
next: usize,
entries: Vec<Entry<T>>,
}
enum Entry<T> {
Empty(usize),
Value(T),
}
impl<T> Slab<T> {
pub fn new() -> Slab<T> {
Slab {
next: 0,
entries: Vec::new(),
}
}
pub fn insert(&mut self, value: T) -> usize {
let index = self.next;
if index == self.entries.len() {
self.entries.push(Entry::Value(value));
self.next = self.entries.len();
} else {
if let Entry::Empty(next) = self.entries[index] {
self.next = next;
self.entries[index] = Entry::Value(value);
} else {
unreachable!()
}
}
index
}
pub fn remove(&mut self, index: usize) -> Option<T> {
if let Some(entry @ Entry::Value(_)) = self.entries.get_mut(index) {
if let Entry::Value(value) = std::mem::replace(entry, Entry::Empty(self.next)) {
self.next = index;
Some(value)
} else {
unreachable!()
}
} else {
None
}
}
pub fn get(&self, index: usize) -> Option<&T> {
match self.entries.get(index) {
Some(Entry::Value(value)) => Some(value),
_ => None,
}
}
pub fn get_mut(&mut self, index: usize) -> Option<&mut T> {
match self.entries.get_mut(index) {
Some(Entry::Value(value)) => Some(value),
_ => None,
}
}
pub fn iter<'a>(&'a self) -> Iter<'a, T> {
Iter { entries: self.entries.iter() }
}
pub fn iter_mut<'a>(&'a mut self) -> IterMut<'a, T> {
IterMut { entries: self.entries.iter_mut() }
}
}
impl<T> IntoIterator for Slab<T> {
type Item = T;
type IntoIter = IntoIter<T>;
fn into_iter(self) -> IntoIter<T> {
IntoIter { entries: self.entries.into_iter() }
}
}
pub struct IntoIter<T> {
entries: std::vec::IntoIter<Entry<T>>,
}
impl<T> Iterator for IntoIter<T> {
type Item = T;
#[inline]
fn next(&mut self) -> Option<T> {
while let Some(entry) = self.entries.next() {
if let Entry::Value(value) = entry {
return Some(value);
}
}
None
}
}
pub struct Iter<'a, T> {
entries: std::slice::Iter<'a, Entry<T>>,
}
impl<'a, T> Iterator for Iter<'a, T> {
type Item = &'a T;
#[inline]
fn next(&mut self) -> Option<&'a T> {
while let Some(entry) = self.entries.next() {
if let Entry::Value(value) = entry {
return Some(value);
}
}
None
}
}
pub struct IterMut<'a, T> {
entries: std::slice::IterMut<'a, Entry<T>>,
}
impl<'a, T> Iterator for IterMut<'a, T> {
type Item = &'a mut T;
#[inline]
fn next(&mut self) -> Option<&'a mut T> {
while let Some(entry) = self.entries.next() {
if let Entry::Value(value) = entry {
return Some(value);
}
}
None
}
}
|
/// print a markdown template, with other arguments taking `$0` to `$9` places in the template.
///
/// Example:
///
/// ```
/// use lazy_static::lazy_static;
/// use minimad::mad_inline;
/// use termimad::*;
///
/// let skin = MadSkin::default();
/// mad_print_inline!(
/// &skin,
/// "**$0 formula:** *$1*", // the markdown template, interpreted once
/// "Disk", // fills $0
/// "2*π*r", // fills $1. Note that the stars don't mess the markdown
/// );
/// ```
#[macro_export]
macro_rules! mad_print_inline {
($skin: expr, $md: literal $(, $value: expr )* $(,)? ) => {
$skin.print_composite(mad_inline!($md $(, $value)*));
};
}
/// write a markdown template, with other arguments taking `$0` to `$9` places in the template.
///
/// Example:
///
/// ```
/// use lazy_static::lazy_static;
/// use minimad::mad_inline;
/// use termimad::*;
///
/// let skin = MadSkin::default();
/// mad_write_inline!(
/// &mut std::io::stdout(),
/// &skin,
/// "**$0 formula:** *$1*", // the markdown template, interpreted once
/// "Disk", // fills $0
/// "2*π*r", // fills $1. Note that the stars don't mess the markdown
/// ).unwrap();
/// ```
#[macro_export]
macro_rules! mad_write_inline {
($w: expr, $skin: expr, $md: literal $(, $value: expr )* $(,)? ) => {{
use std::io::Write;
$skin.write_composite($w, mad_inline!($md $(, $value)*))
}};
}
|
/// File defining raw text
///
use core::*;
use latex_file::*;
|
use crate::*;
use std::cell::RefCell;
use std::thread;
use std::time::Duration;
#[derive(Default)]
pub struct ThreadResources {
count: usize
}
#[derive(Default)]
pub struct ThreadTest {
resources: RefCell<ThreadResources>,
pub window: Window,
layout: FlexboxLayout,
font: Font,
counter: TextInput,
timer_start_btn: Button,
timer_stop_btn: Button,
sleep_btn: Button,
thread_sleep_btn: Button,
timer: AnimationTimer,
notice: Notice
}
fn timer_tick(app: &ThreadTest) {
let mut rc = app.resources.borrow_mut();
rc.count += 1;
app.counter.set_text(&format!("{}", rc.count));
}
fn start_timer(app: &ThreadTest) {
app.timer.start();
}
fn stop_timer(app: &ThreadTest) {
app.timer.stop();
}
fn sleep() {
thread::sleep(Duration::new(5, 0));
}
fn thread_sleep(app: &ThreadTest) {
app.counter.set_text("Sleeping for 5 sec! (off the GUI thread)");
let sender = app.notice.sender();
thread::spawn(move || {
thread::sleep(Duration::new(5, 0));
sender.notice();
});
}
fn notice_me(app: &ThreadTest) {
app.counter.set_text("Done sleeping of the main thread!");
}
mod partial_canvas_test_ui {
use super::*;
use crate::{PartialUi, NwgError, ControlHandle};
use stretch::style::*;
impl PartialUi for ThreadTest {
fn build_partial<W: Into<ControlHandle>>(data: &mut ThreadTest, _parent: Option<W>) -> Result<(), NwgError> {
Font::builder()
.size(40)
.family("Consolas")
.build(&mut data.font)?;
Window::builder()
.flags(WindowFlags::WINDOW)
.size((300, 300))
.position((250, 100))
.title("Threads")
.build(&mut data.window)?;
TextInput::builder()
.parent(&data.window)
.font(Some(&data.font))
.build(&mut data.counter)?;
Button::builder()
.text("Start timer")
.parent(&data.window)
.build(&mut data.timer_start_btn)?;
Button::builder()
.text("Stop timer")
.parent(&data.window)
.build(&mut data.timer_stop_btn)?;
Button::builder()
.text("Sleep")
.parent(&data.window)
.build(&mut data.sleep_btn)?;
Button::builder()
.text("Sleep (off thread)")
.parent(&data.window)
.build(&mut data.thread_sleep_btn)?;
AnimationTimer::builder()
.parent(&data.window)
.interval(Duration::from_millis(25))
.build(&mut data.timer)?;
Notice::builder()
.parent(&data.window)
.build(&mut data.notice)?;
FlexboxLayout::builder()
.parent(&data.window)
.flex_direction(FlexDirection::Column)
.auto_size(true)
.auto_spacing(Some(5))
.child(&data.counter)
.child(&data.timer_start_btn)
.child(&data.timer_stop_btn)
.child(&data.sleep_btn)
.child(&data.thread_sleep_btn)
.build(&data.layout)?;
Ok(())
}
fn process_event<'a>(&self, evt: Event, mut _evt_data: &EventData, handle: ControlHandle) {
use crate::Event as E;
match evt {
E::OnButtonClick =>
if &handle == &self.timer_start_btn {
start_timer(self);
} else if &handle == &self.timer_stop_btn {
stop_timer(self);
} else if &handle == &self.sleep_btn {
sleep();
} else if &handle == &self.thread_sleep_btn {
thread_sleep(self);
},
E::OnTimerTick =>
if &handle == &self.timer {
timer_tick(self)
},
E::OnNotice =>
if &handle == &self.notice {
notice_me(self)
},
_ => {}
}
}
fn handles(&self) -> Vec<&ControlHandle> {
vec![&self.window.handle]
}
}
}
|
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
#![allow(non_snake_case)]
extern crate core_foundation_sys;
extern crate libc;
#[cfg(feature = "with-chrono")]
extern crate chrono;
use base::TCFType;
pub unsafe trait ConcreteCFType: TCFType {}
#[macro_export]
macro_rules! declare_TCFType {
(
$(#[$doc:meta])*
$ty:ident, $raw:ident
) => {
$(#[$doc])*
pub struct $ty($raw);
impl Drop for $ty {
fn drop(&mut self) {
unsafe { $crate::base::CFRelease(self.as_CFTypeRef()) }
}
}
}
}
#[macro_export]
macro_rules! impl_TCFType {
($ty:ident, $ty_ref:ident, $ty_id:ident) => {
impl_TCFType!($ty<>, $ty_ref, $ty_id);
unsafe impl $crate::ConcreteCFType for $ty { }
};
($ty:ident<$($p:ident $(: $bound:path)*),*>, $ty_ref:ident, $ty_id:ident) => {
impl<$($p $(: $bound)*),*> $crate::base::TCFType for $ty<$($p),*> {
type Ref = $ty_ref;
#[inline]
fn as_concrete_TypeRef(&self) -> $ty_ref {
self.0
}
#[inline]
unsafe fn wrap_under_get_rule(reference: $ty_ref) -> Self {
let reference = $crate::base::CFRetain(reference as *const ::std::os::raw::c_void) as $ty_ref;
$crate::base::TCFType::wrap_under_create_rule(reference)
}
#[inline]
fn as_CFTypeRef(&self) -> $crate::base::CFTypeRef {
self.as_concrete_TypeRef() as $crate::base::CFTypeRef
}
#[inline]
unsafe fn wrap_under_create_rule(reference: $ty_ref) -> Self {
// we need one PhantomData for each type parameter so call ourselves
// again with @Phantom $p to produce that
$ty(reference $(, impl_TCFType!(@Phantom $p))*)
}
#[inline]
fn type_id() -> $crate::base::CFTypeID {
unsafe {
$ty_id()
}
}
}
impl Clone for $ty {
#[inline]
fn clone(&self) -> $ty {
unsafe {
$ty::wrap_under_get_rule(self.0)
}
}
}
impl PartialEq for $ty {
#[inline]
fn eq(&self, other: &$ty) -> bool {
self.as_CFType().eq(&other.as_CFType())
}
}
impl Eq for $ty { }
unsafe impl<'a> $crate::base::ToVoid<$ty> for &'a $ty {
fn to_void(&self) -> *const ::std::os::raw::c_void {
use $crate::base::TCFTypeRef;
self.as_concrete_TypeRef().as_void_ptr()
}
}
unsafe impl $crate::base::ToVoid<$ty> for $ty {
fn to_void(&self) -> *const ::std::os::raw::c_void {
use $crate::base::TCFTypeRef;
self.as_concrete_TypeRef().as_void_ptr()
}
}
unsafe impl $crate::base::ToVoid<$ty> for $ty_ref {
fn to_void(&self) -> *const ::std::os::raw::c_void {
use $crate::base::TCFTypeRef;
self.as_void_ptr()
}
}
};
(@Phantom $x:ident) => { ::std::marker::PhantomData };
}
#[macro_export]
macro_rules! impl_CFTypeDescription {
($ty:ident) => {
// it's fine to use an empty <> list
impl_CFTypeDescription!($ty<>);
};
($ty:ident<$($p:ident $(: $bound:path)*),*>) => {
impl<$($p $(: $bound)*),*> ::std::fmt::Debug for $ty<$($p),*> {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
self.as_CFType().fmt(f)
}
}
}
}
#[macro_export]
macro_rules! impl_CFComparison {
($ty:ident, $compare:ident) => {
impl PartialOrd for $ty {
#[inline]
fn partial_cmp(&self, other: &$ty) -> Option<::std::cmp::Ordering> {
unsafe {
Some($compare(self.as_concrete_TypeRef(), other.as_concrete_TypeRef(), ::std::ptr::null_mut()).into())
}
}
}
impl Ord for $ty {
#[inline]
fn cmp(&self, other: &$ty) -> ::std::cmp::Ordering {
self.partial_cmp(other).unwrap()
}
}
}
}
pub mod array;
pub mod attributed_string;
pub mod base;
pub mod boolean;
pub mod data;
pub mod date;
pub mod dictionary;
pub mod error;
pub mod filedescriptor;
pub mod number;
pub mod set;
pub mod string;
pub mod url;
pub mod bundle;
pub mod propertylist;
pub mod runloop;
pub mod timezone;
pub mod uuid;
|
#[derive(Debug)]
enum Errors {}
const INPUT: &str = include_str!("../../input/01");
fn solution(input: &str) -> i32 {
let mut seen = std::collections::BTreeSet::new();
let mut current = 0;
seen.insert(current);
input
.lines()
.filter_map(|x| x.parse::<i32>().ok())
.cycle() // "the device might need to repeat its list of frequencies many times ..."
.take_while(|c| {
current += *c;
seen.insert(current)
})
.last(); // Only called because the iterator is lazy, otherwise it won't do anything...
current
}
fn main() -> Result<(), Errors> {
println!("Solution: {}", solution(INPUT));
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn chronal_calibration_part_2() {
assert_eq!(452, solution(INPUT));
}
#[test]
fn example_1() {
assert_eq!(0, solution("+1\n-1"));
}
#[test]
fn example_2() {
assert_eq!(10, solution("+3\n+3\n+4\n-2\n-4"));
}
#[test]
fn example_3() {
assert_eq!(5, solution("-6\n+3\n+8\n+5\n-6"));
}
#[test]
fn example_4() {
assert_eq!(14, solution("+7\n+7\n-2\n-7\n-4"));
}
}
|
pub mod component;
pub mod paddle;
|
// Copyright 2017 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.
// check that we don't StorageDead booleans before they are used
fn main() {
let mut should_break = false;
loop {
if should_break {
break;
}
should_break = true;
}
}
// END RUST SOURCE
// START rustc.main.SimplifyCfg-initial.after.mir
// bb0: {
// StorageLive(_1);
// _1 = const false;
// goto -> bb2;
// }
// bb1: {
// resume;
// }
// bb2: {
// falseUnwind -> [real: bb3, cleanup: bb1];
// }
// bb3: {
// StorageLive(_4);
// _4 = _1;
// switchInt(move _4) -> [false: bb5, otherwise: bb4];
// }
// bb4: {
// _0 = ();
// StorageDead(_4);
// StorageDead(_1);
// return;
// }
// bb5: {
// _3 = ();
// StorageDead(_4);
// _1 = const true;
// _2 = ();
// goto -> bb2;
// }
// END rustc.main.SimplifyCfg-initial.after.mir
|
use std::cell::RefCell;
use std::rc::Rc;
use wasm_bindgen::prelude::*;
use wasm_bindgen::JsCast;
use web_sys::{Element, Event};
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(js_namespace = console)]
fn log(s: &str);
}
macro_rules! console_log {
($($t:tt)*) => (log(&format_args!($($t)*).to_string()))
}
#[wasm_bindgen]
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[wasm_bindgen]
pub fn create_element(tag: String, container: String) -> Result<(), JsValue> {
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let node = document.create_element(tag.as_str()).unwrap();
document
.query_selector(container.as_str())
.unwrap()
.unwrap()
.append_child(&node)?;
Ok(())
}
#[wasm_bindgen]
pub fn del_element(query_selector: String) -> Result<(), JsValue> {
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let current_node = document
.query_selector(query_selector.as_str())
.unwrap()
.unwrap();
let parent_node = current_node.parent_node().unwrap();
parent_node.remove_child(¤t_node)?;
Ok(())
}
struct Global {
pub document: Rc<web_sys::Document>,
pub window: Rc<web_sys::Window>,
pub count: i32,
}
impl Global {
fn new() -> Self {
let window = Rc::new(web_sys::window().unwrap());
let document = Rc::new(window.document().unwrap());
Global {
window,
document,
count: 0,
}
}
pub fn get_instance() -> Rc<RefCell<Global>> {
static mut GLOBAL: Option<Rc<RefCell<Global>>> = None;
unsafe {
GLOBAL
.get_or_insert_with(|| Rc::new(RefCell::new(Global::new())))
.clone()
}
}
}
struct Store {
count: i32,
input_value: String,
input_value_elem: Option<Vec<Rc<Element>>>,
}
impl Store {
fn new() -> Self {
Store {
count: 0,
input_value: "".to_string(),
input_value_elem: None,
}
}
pub fn get_instance() -> Rc<RefCell<Store>> {
static mut STORE: Option<Rc<RefCell<Store>>> = None;
unsafe {
STORE
.get_or_insert_with(|| Rc::new(RefCell::new(Store::new())))
.clone()
}
}
pub fn push_input_value_elem(&mut self, elem: Rc<Element>) {
if self.input_value_elem.is_none() {
self.input_value_elem = Some(vec![elem]);
} else {
self.input_value_elem.as_mut().unwrap().push(elem);
}
}
}
#[wasm_bindgen]
pub fn test_dom() -> Result<(), JsValue> {
let global = Global::get_instance();
// let window = global.borrow_mut().window.clone();
let document = global.borrow_mut().document.clone();
let element = document.create_element("div").unwrap();
element.set_attribute("id", "app")?;
let body = document.body().unwrap();
body.append_child(&element)?;
{
let span = document.create_element("span").unwrap();
let span = Rc::new(span);
let store = Store::get_instance();
span.set_inner_html(store.borrow().input_value.as_str());
if store.borrow_mut().input_value_elem.is_none() {
store.borrow_mut().input_value_elem = Some(vec![]);
}
store
.borrow_mut()
.input_value_elem
.as_mut()
.unwrap()
.push(Rc::clone(&span));
element.append_child(&span)?;
}
let span = document.create_element("span").unwrap();
let span = Rc::new(span);
let store = Store::get_instance();
span.set_inner_html(store.borrow().input_value.as_str());
store.borrow_mut().push_input_value_elem(Rc::clone(&span));
element.append_child(&span)?;
{
let input_elem = document.create_element("input").unwrap();
let input_closure = Closure::wrap(Box::new(move |event: Event| {
if let Some(target) = event.target() {
if let Some(input_el) =
wasm_bindgen::JsCast::dyn_ref::<web_sys::HtmlInputElement>(&target)
{
let v = input_el.value();
let title = v.trim();
let store = Store::get_instance();
store.borrow_mut().input_value = title.to_string();
console_log!("here");
update_text();
}
}
}) as Box<dyn FnMut(_)>);
input_elem
.add_event_listener_with_callback("input", input_closure.as_ref().unchecked_ref())?;
input_closure.forget();
element.append_child(&input_elem)?;
}
{
let button_elem = document.create_element("button").unwrap();
button_elem.set_inner_html("change title");
let click_closure = Closure::wrap(Box::new(move || {
span.set_inner_html("rom");
}) as Box<dyn FnMut()>);
button_elem
.add_event_listener_with_callback("click", click_closure.as_ref().unchecked_ref())?;
click_closure.forget();
element.append_child(&button_elem)?;
}
{
let add_btn_elem = document.create_element("button").unwrap();
add_btn_elem.set_inner_html("+1");
let click_closure = Closure::wrap(Box::new(move || {
add_count(1);
get_count();
}) as Box<dyn FnMut()>);
add_btn_elem
.add_event_listener_with_callback("click", click_closure.as_ref().unchecked_ref())?;
click_closure.forget();
element.append_child(&add_btn_elem)?;
}
{
let add_btn_elem = document.create_element("button").unwrap();
add_btn_elem.set_inner_html("+2");
let click_closure = Closure::wrap(Box::new(move || {
add_count(2);
get_count();
}) as Box<dyn FnMut()>);
add_btn_elem
.add_event_listener_with_callback("click", click_closure.as_ref().unchecked_ref())?;
click_closure.forget();
element.append_child(&add_btn_elem)?;
}
get_count();
Ok(())
}
pub fn update_text() {
let store = Store::get_instance();
let value = &store.borrow().input_value.clone();
store
.borrow_mut()
.input_value_elem
.as_mut()
.unwrap()
.iter()
.for_each(|x| {
x.set_inner_html(value);
});
}
pub fn get_count() {
let store = Store::get_instance();
let count = store.borrow().count;
console_log!("{}", count);
}
pub fn add_count(x: i32) {
let store = Store::get_instance();
store.borrow_mut().count += x;
}
#[wasm_bindgen(start)]
pub fn start() {
// let env = env_logger::Env::default();
// env_logger::init_from_env(env);
// env_logger::init();
console_log!("starting!");
}
|
//! Represents the `output` array table in the package manifest.
use std::collections::BTreeSet;
use std::fmt::{Display, Formatter, Result as FmtResult};
use serde::de::{Deserializer, Error as DeError};
use serde::ser::Serializer;
use serde::{Deserialize, Serialize};
use crate::hash::Hash;
use crate::id::OutputId;
use crate::name::Name;
/// Represents the `output` array table in the package manifest.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Outputs(BTreeSet<Entry>);
impl Outputs {
/// Creates a new `Outputs` table with the default output set to the given precomputed hash and
/// references.
///
/// # What is meant by a "precomputed hash"
///
/// Since the store follows an intensional model (see Eelco Dolstra's writings on the theorized
/// "intensional model" within Nix and NixOS), this precomputed hash is used only to identify
/// compatible trusted substitutes for safe sharing between untrusted users. It may be
/// rewritten to something else after the builder has been run.
pub fn new<T>(precomputed_hash: Hash, refs: T) -> Self
where
T: IntoIterator<Item = OutputId>,
{
let refs = refs.into_iter().collect();
let mut set = BTreeSet::new();
set.insert(Entry::new(Output::Default, precomputed_hash, refs));
Outputs(set)
}
/// Appends a new named output with the given name, precomputed hash [`Hash`], and references.
///
/// # What is meant by a "precomputed hash"
///
/// Since the store follows an intensional model (see Eelco Dolstra's writings on the theorized
/// "intensional model" within Nix and NixOS), this precomputed hash is used only to identify
/// compatible trusted substitutes for safe sharing between untrusted users. It may be
/// rewritten to something else after the builder has been run.
#[inline]
pub fn append<T>(&mut self, name: Name, precomputed_hash: Hash, refs: T)
where
T: IntoIterator<Item = OutputId>,
{
let refs = refs.into_iter().collect();
let output = Entry::new(Output::Named(name), precomputed_hash, refs);
self.0.insert(output);
}
/// Renders the given output entries as a set of [`OutputId`]s with `name` and `version`.
///
/// [`OutputId`]: ../struct.OutputId.html
pub fn iter_with(&self, name: Name, version: String) -> impl Iterator<Item = OutputId> + '_ {
self.0
.iter()
.map(move |out| out.to_output_id(name.clone(), version.clone()))
}
}
impl<'de> Deserialize<'de> for Outputs {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let set: BTreeSet<Entry> = Deserialize::deserialize(deserializer)?;
let num_default_outputs = set.iter().filter(|out| out.is_default_output()).count();
if num_default_outputs == 1 {
Ok(Outputs(set))
} else if num_default_outputs > 1 {
Err(DeError::custom("cannot have multiple default outputs"))
} else {
Err(DeError::custom("missing default output"))
}
}
}
impl Serialize for Outputs {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.0.serialize(serializer)
}
}
/// Types of build outputs that a manifest can have.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
enum Output {
/// The unnamed default output.
///
/// Contains the actual application/library being installed. When a package is installed by a
/// user, this is likely what they are looking for. Manifests are required to have one and only
/// one default output.
Default,
/// An optional "named" output.
///
/// Contains extra components or artifacts not typically included in a base installation. For
/// example, the `doc` named output could contain rendered HTML documentation, the `man` named
/// output could contain man pages, the `debug` named output could contain debugging symbols,
/// etc. Users can request to install these add-on outputs on top of the default output.
Named(Name),
}
impl Output {
/// Returns whether this output is an [`Output::Default`].
///
/// [`Output::Default`]: ./struct.Output.html#variant.Default
pub fn is_default_output(&self) -> bool {
*self == Output::Default
}
}
impl Default for Output {
fn default() -> Self {
Output::Default
}
}
impl Display for Output {
fn fmt(&self, fmt: &mut Formatter) -> FmtResult {
match *self {
Output::Default => write!(fmt, ""),
Output::Named(ref name) => write!(fmt, "{}", name),
}
}
}
impl Into<Option<Name>> for Output {
fn into(self) -> Option<Name> {
match self {
Output::Default => None,
Output::Named(name) => Some(name),
}
}
}
impl<'de> Deserialize<'de> for Output {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let s: &str = Deserialize::deserialize(deserializer)?;
if s.is_empty() {
Ok(Output::Default)
} else {
let out = s
.parse()
.map_err(|_err| DeError::custom("failed to deserialize"))?;
Ok(Output::Named(out))
}
}
}
impl Serialize for Output {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match *self {
Output::Default => None::<&str>.serialize(serializer),
Output::Named(_) => self.to_string().serialize(serializer),
}
}
}
/// A single serializable entry in the `Outputs` table.
#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
struct Entry {
#[serde(default, rename = "name")]
output_name: Output,
precomputed_hash: Hash,
#[serde(default, skip_serializing_if = "BTreeSet::is_empty")]
references: BTreeSet<OutputId>,
}
impl Entry {
/// Creates a new `Entry` with the given name, precomputed hash, and references.
#[inline]
pub const fn new(output_name: Output, hash: Hash, refs: BTreeSet<OutputId>) -> Self {
Entry {
output_name,
precomputed_hash: hash,
references: refs,
}
}
/// Returns whether this output entry is an [`Output::Default`].
///
/// [`Output::Default`]: ./struct.Output.html#variant.Default
#[inline]
fn is_default_output(&self) -> bool {
self.output_name.is_default_output()
}
/// Renders this entry as an `OutputId` using the given name and version information.
#[inline]
fn to_output_id(&self, name: Name, version: String) -> OutputId {
let output_name = self.output_name.clone();
let precomputed_hash = self.precomputed_hash;
OutputId::new(name, version, output_name.into(), precomputed_hash)
}
}
#[cfg(test)]
mod tests {
use toml::de;
use super::*;
#[derive(Debug, Deserialize, Serialize)]
struct Container {
#[serde(rename = "output")]
pub outputs: Outputs,
}
const EXAMPLE_OUTPUTS: &'static str = r#"
[[output]]
precomputed-hash = "fc3j3vub6kodu4jtfoakfs5xhumqi62m"
references = ["foo@1.2.3-fc3j3vub6kodu4jtfoakfs5xhumqi62m"]
[[output]]
name = "docs"
precomputed-hash = "fc3j3vub6kodu4jtfoakfs5xhumqi62m"
[[output]]
name = "man"
precomputed-hash = "fc3j3vub6kodu4jtfoakfs5xhumqi62m"
"#;
const MISSING_DEFAULT_OUTPUT: &'static str = r#"
[[output]]
name = "foo"
precomputed-hash = "fc3j3vub6kodu4jtfoakfs5xhumqi62m"
"#;
const MULTIPLE_DEFAULT_OUTPUTS: &'static str = r#"
[[output]]
precomputed-hash = "fc3j3vub6kodu4jtfoakfs5xhumqi62m"
references = ["foo@1.2.3-fc3j3vub6kodu4jtfoakfs5xhumqi62m"]
[[output]]
precomputed-hash = "xpyrto6ighxc4gfhxrexzcrlcdaipars"
[[output]]
name = "docs"
precomputed-hash = "4gw3yobvb2q3uwyu7i4qri3o5bvs2mrt"
"#;
#[test]
fn parse_from_string() {
let toml: Container = de::from_str(EXAMPLE_OUTPUTS).expect("Failed to deserialize");
let actual = toml.outputs;
let dummy_hash: Hash = "fc3j3vub6kodu4jtfoakfs5xhumqi62m"
.parse()
.expect("Failed to parse hash from text");
let dummy_ref = "foo@1.2.3-fc3j3vub6kodu4jtfoakfs5xhumqi62m"
.parse()
.expect("Failed to parse ID");
let mut expected = Outputs::new(dummy_hash.clone(), vec![dummy_ref]);
let docs_name = "docs".parse().expect("Failed to parse name 'docs'");
expected.append(docs_name, dummy_hash.clone(), None);
let man_name = "man".parse().expect("Failed to parse name 'man'");
expected.append(man_name, dummy_hash.clone(), None);
assert_eq!(actual, expected);
}
#[test]
fn rejects_missing_default_output() {
de::from_str::<Container>(MISSING_DEFAULT_OUTPUT)
.expect_err("Failed to reject `Outputs` missing default outputs");
}
#[test]
fn rejects_multiple_default_outputs() {
de::from_str::<Container>(MULTIPLE_DEFAULT_OUTPUTS)
.expect_err("Failed to reject `Outputs` with multiple default outputs");
}
}
|
use rand::{rngs::SmallRng, RngCore, SeedableRng};
use std::convert::TryInto;
use tokio::time::sleep;
mod proto {
tonic::include_proto!("ortiofay.olix0r.net");
}
#[derive(Clone)]
pub(crate) struct Api {
rng: SmallRng,
}
impl Api {
pub fn server() -> proto::ortiofay_server::OrtiofayServer<Self> {
proto::ortiofay_server::OrtiofayServer::new(Self {
rng: SmallRng::from_entropy(),
})
}
}
#[tonic::async_trait]
impl proto::ortiofay_server::Ortiofay for Api {
async fn get(
&self,
req: tonic::Request<proto::ResponseSpec>,
) -> Result<tonic::Response<proto::ResponseReply>, tonic::Status> {
use proto::response_spec as spec;
let proto::ResponseSpec {
latency,
result,
data: _,
} = req.into_inner();
if let Some(l) = latency {
if let Ok(l) = l.try_into() {
sleep(l).await;
}
}
match result {
None => Ok(tonic::Response::new(proto::ResponseReply::default())),
Some(spec::Result::Success(spec::Success { size })) => {
let mut data = Vec::with_capacity(size.try_into().unwrap_or(0));
self.rng.clone().fill_bytes(&mut data);
Ok(tonic::Response::new(proto::ResponseReply { data }))
}
Some(spec::Result::Error(spec::Error { code, message })) => {
let code = match code {
1 => tonic::Code::Cancelled,
2 => tonic::Code::Unknown,
3 => tonic::Code::InvalidArgument,
4 => tonic::Code::DeadlineExceeded,
5 => tonic::Code::NotFound,
6 => tonic::Code::AlreadyExists,
7 => tonic::Code::PermissionDenied,
8 => tonic::Code::ResourceExhausted,
9 => tonic::Code::FailedPrecondition,
10 => tonic::Code::Aborted,
11 => tonic::Code::OutOfRange,
12 => tonic::Code::Unimplemented,
13 => tonic::Code::Internal,
14 => tonic::Code::Unavailable,
15 => tonic::Code::DataLoss,
16 => tonic::Code::Unauthenticated,
_ => tonic::Code::InvalidArgument,
};
Err(tonic::Status::new(code, message))
}
}
}
}
|
#![recursion_limit = "128"]
extern crate proc_macro;
#[macro_use]
extern crate quote;
#[macro_use]
extern crate syn;
use proc_macro2::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{parse_macro_input, parse_quote, Data, DeriveInput, Fields, GenericParam, Generics, Index, Ident, DataStruct, Type};
use darling::{FromField, FromDeriveInput};
#[derive(Debug, FromDeriveInput)]
#[darling(attributes(inspect))]
struct StructArgs {
#[darling(default)]
no_default: Option<bool>,
}
#[derive(Debug, FromField)]
#[darling(attributes(inspect))]
struct FieldArgs {
#[darling(default)]
null_to: Option<syn::Lit>,
#[darling(default)]
speed: Option<f32>,
#[darling(default)]
skip: Option<bool>,
}
#[proc_macro_derive(Inspect, attributes(inspect))]
pub fn derive_inspect(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let no_default = StructArgs::from_derive_input(&input).unwrap().no_default.unwrap_or(false);
let name = input.ident;
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let inspect = inspect(&input.data, &name);
let (can_add, add) = match (no_default, input.data) {
(_, Data::Struct(DataStruct { fields: Fields::Unit, .. })) => (true, quote!(lazy.insert(entity, Self);)),
(false, _) => (true, quote!(lazy.insert(entity, Self::default());)),
(true, _) => (false, quote!({})),
};
let expanded = quote! {
impl<'a> #impl_generics ::amethyst_inspector::Inspect<'a> for #name #ty_generics #where_clause {
type SystemData = (
::amethyst::ecs::ReadStorage<'a, Self>,
::amethyst::ecs::Read<'a, ::amethyst::ecs::LazyUpdate>,
);
const CAN_ADD: bool = #can_add;
fn inspect((storage, lazy): &mut Self::SystemData, entity: ::amethyst::ecs::Entity, ui: &::amethyst_imgui::imgui::Ui<'_>) { #inspect }
fn add((storage, lazy): &mut Self::SystemData, entity: ::amethyst::ecs::Entity) { #add }
}
};
proc_macro::TokenStream::from(expanded)
}
fn inspect(data: &Data, name: &Ident) -> TokenStream {
match *data {
Data::Struct(ref data) => {
match data.fields {
Fields::Named(ref fields) => {
let recurse = fields.named.iter().map(|f| {
let args = FieldArgs::from_field(&f).unwrap();
let skip = args.skip.unwrap_or(false);
if skip { return quote_spanned! { f.span()=> {} }; };
let null_to = args.null_to.map(|x| quote!(#x)).unwrap_or(quote!(0.));
let speed = args.speed.unwrap_or(0.1);
let name = &f.ident;
let ty = &f.ty;
quote_spanned! {f.span()=>
changed = <#ty as ::amethyst_inspector::InspectControl>::control(&mut new_me.#name, #null_to, #speed, ::amethyst_imgui::imgui::im_str!("{}", stringify!(#name)), ui) || changed;
}
});
quote! {
let me = if let Some(x) = storage.get(entity) { x } else { return; };
let mut new_me = me.clone();
let mut changed = false;
ui.push_id(::amethyst_imgui::imgui::im_str!("{}", stringify!(#name)));
#(#recurse)*
if changed {
lazy.insert(entity, new_me);
}
ui.pop_id();
}
}
Fields::Unit => { quote!() },
_ => unimplemented!(),
}
},
_ => unimplemented!(),
}
}
|
#[doc = "Reader of register IER2"]
pub type R = crate::R<u32, super::IER2>;
#[doc = "Writer for register IER2"]
pub type W = crate::W<u32, super::IER2>;
#[doc = "Register IER2 `reset()`'s with value 0"]
impl crate::ResetValue for super::IER2 {
type Type = u32;
#[inline(always)]
fn reset_value() -> Self::Type {
0
}
}
#[doc = "Reader of field `TIM8IE`"]
pub type TIM8IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM8IE`"]
pub struct TIM8IE_W<'a> {
w: &'a mut W,
}
impl<'a> TIM8IE_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 `USART1IE`"]
pub type USART1IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `USART1IE`"]
pub struct USART1IE_W<'a> {
w: &'a mut W,
}
impl<'a> USART1IE_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 `TIM15IE`"]
pub type TIM15IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM15IE`"]
pub struct TIM15IE_W<'a> {
w: &'a mut W,
}
impl<'a> TIM15IE_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 `TIM16IE`"]
pub type TIM16IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM16IE`"]
pub struct TIM16IE_W<'a> {
w: &'a mut W,
}
impl<'a> TIM16IE_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 `TIM17IE`"]
pub type TIM17IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TIM17IE`"]
pub struct TIM17IE_W<'a> {
w: &'a mut W,
}
impl<'a> TIM17IE_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 `SAI1IE`"]
pub type SAI1IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SAI1IE`"]
pub struct SAI1IE_W<'a> {
w: &'a mut W,
}
impl<'a> SAI1IE_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 `SAI2IE`"]
pub type SAI2IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SAI2IE`"]
pub struct SAI2IE_W<'a> {
w: &'a mut W,
}
impl<'a> SAI2IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 6)) | (((value as u32) & 0x01) << 6);
self.w
}
}
#[doc = "Reader of field `DFSDM1IE`"]
pub type DFSDM1IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DFSDM1IE`"]
pub struct DFSDM1IE_W<'a> {
w: &'a mut W,
}
impl<'a> DFSDM1IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 7)) | (((value as u32) & 0x01) << 7);
self.w
}
}
#[doc = "Reader of field `CRCIE`"]
pub type CRCIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `CRCIE`"]
pub struct CRCIE_W<'a> {
w: &'a mut W,
}
impl<'a> CRCIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 8)) | (((value as u32) & 0x01) << 8);
self.w
}
}
#[doc = "Reader of field `TSCIE`"]
pub type TSCIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `TSCIE`"]
pub struct TSCIE_W<'a> {
w: &'a mut W,
}
impl<'a> TSCIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9);
self.w
}
}
#[doc = "Reader of field `ICACHEIE`"]
pub type ICACHEIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ICACHEIE`"]
pub struct ICACHEIE_W<'a> {
w: &'a mut W,
}
impl<'a> ICACHEIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 10)) | (((value as u32) & 0x01) << 10);
self.w
}
}
#[doc = "Reader of field `ADCIE`"]
pub type ADCIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `ADCIE`"]
pub struct ADCIE_W<'a> {
w: &'a mut W,
}
impl<'a> ADCIE_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 << 11)) | (((value as u32) & 0x01) << 11);
self.w
}
}
#[doc = "Reader of field `AESIE`"]
pub type AESIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `AESIE`"]
pub struct AESIE_W<'a> {
w: &'a mut W,
}
impl<'a> AESIE_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 << 12)) | (((value as u32) & 0x01) << 12);
self.w
}
}
#[doc = "Reader of field `HASHIE`"]
pub type HASHIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `HASHIE`"]
pub struct HASHIE_W<'a> {
w: &'a mut W,
}
impl<'a> HASHIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 13)) | (((value as u32) & 0x01) << 13);
self.w
}
}
#[doc = "Reader of field `RNGIE`"]
pub type RNGIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RNGIE`"]
pub struct RNGIE_W<'a> {
w: &'a mut W,
}
impl<'a> RNGIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 14)) | (((value as u32) & 0x01) << 14);
self.w
}
}
#[doc = "Reader of field `PKAIE`"]
pub type PKAIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PKAIE`"]
pub struct PKAIE_W<'a> {
w: &'a mut W,
}
impl<'a> PKAIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 15)) | (((value as u32) & 0x01) << 15);
self.w
}
}
#[doc = "Reader of field `SDMMC1IE`"]
pub type SDMMC1IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SDMMC1IE`"]
pub struct SDMMC1IE_W<'a> {
w: &'a mut W,
}
impl<'a> SDMMC1IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16);
self.w
}
}
#[doc = "Reader of field `FMC_REGIE`"]
pub type FMC_REGIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FMC_REGIE`"]
pub struct FMC_REGIE_W<'a> {
w: &'a mut W,
}
impl<'a> FMC_REGIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17);
self.w
}
}
#[doc = "Reader of field `OCTOSPI1_REGIE`"]
pub type OCTOSPI1_REGIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OCTOSPI1_REGIE`"]
pub struct OCTOSPI1_REGIE_W<'a> {
w: &'a mut W,
}
impl<'a> OCTOSPI1_REGIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18);
self.w
}
}
#[doc = "Reader of field `RTCIE`"]
pub type RTCIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RTCIE`"]
pub struct RTCIE_W<'a> {
w: &'a mut W,
}
impl<'a> RTCIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19);
self.w
}
}
#[doc = "Reader of field `PWRIE`"]
pub type PWRIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `PWRIE`"]
pub struct PWRIE_W<'a> {
w: &'a mut W,
}
impl<'a> PWRIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20);
self.w
}
}
#[doc = "Reader of field `SYSCFGIE`"]
pub type SYSCFGIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `SYSCFGIE`"]
pub struct SYSCFGIE_W<'a> {
w: &'a mut W,
}
impl<'a> SYSCFGIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 21)) | (((value as u32) & 0x01) << 21);
self.w
}
}
#[doc = "Reader of field `DMA1IE`"]
pub type DMA1IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMA1IE`"]
pub struct DMA1IE_W<'a> {
w: &'a mut W,
}
impl<'a> DMA1IE_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 << 22)) | (((value as u32) & 0x01) << 22);
self.w
}
}
#[doc = "Reader of field `DMA2IE`"]
pub type DMA2IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMA2IE`"]
pub struct DMA2IE_W<'a> {
w: &'a mut W,
}
impl<'a> DMA2IE_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 << 23)) | (((value as u32) & 0x01) << 23);
self.w
}
}
#[doc = "Reader of field `DMAMUX1IE`"]
pub type DMAMUX1IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `DMAMUX1IE`"]
pub struct DMAMUX1IE_W<'a> {
w: &'a mut W,
}
impl<'a> DMAMUX1IE_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 << 24)) | (((value as u32) & 0x01) << 24);
self.w
}
}
#[doc = "Reader of field `RCCIE`"]
pub type RCCIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `RCCIE`"]
pub struct RCCIE_W<'a> {
w: &'a mut W,
}
impl<'a> RCCIE_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 << 25)) | (((value as u32) & 0x01) << 25);
self.w
}
}
#[doc = "Reader of field `FLASHIE`"]
pub type FLASHIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FLASHIE`"]
pub struct FLASHIE_W<'a> {
w: &'a mut W,
}
impl<'a> FLASHIE_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 << 26)) | (((value as u32) & 0x01) << 26);
self.w
}
}
#[doc = "Reader of field `FLASH_REGIE`"]
pub type FLASH_REGIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `FLASH_REGIE`"]
pub struct FLASH_REGIE_W<'a> {
w: &'a mut W,
}
impl<'a> FLASH_REGIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 27)) | (((value as u32) & 0x01) << 27);
self.w
}
}
#[doc = "Reader of field `EXTIIE`"]
pub type EXTIIE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `EXTIIE`"]
pub struct EXTIIE_W<'a> {
w: &'a mut W,
}
impl<'a> EXTIIE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 28)) | (((value as u32) & 0x01) << 28);
self.w
}
}
#[doc = "Reader of field `OTFDEC1IE`"]
pub type OTFDEC1IE_R = crate::R<bool, bool>;
#[doc = "Write proxy for field `OTFDEC1IE`"]
pub struct OTFDEC1IE_W<'a> {
w: &'a mut W,
}
impl<'a> OTFDEC1IE_W<'a> {
#[doc = r"Sets the field bit"]
#[inline(always)]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r"Clears the field bit"]
#[inline(always)]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r"Writes raw bits to the field"]
#[inline(always)]
pub fn bit(self, value: bool) -> &'a mut W {
self.w.bits = (self.w.bits & !(0x01 << 29)) | (((value as u32) & 0x01) << 29);
self.w
}
}
impl R {
#[doc = "Bit 0 - TIM8IE"]
#[inline(always)]
pub fn tim8ie(&self) -> TIM8IE_R {
TIM8IE_R::new((self.bits & 0x01) != 0)
}
#[doc = "Bit 1 - USART1IE"]
#[inline(always)]
pub fn usart1ie(&self) -> USART1IE_R {
USART1IE_R::new(((self.bits >> 1) & 0x01) != 0)
}
#[doc = "Bit 2 - TIM15IE"]
#[inline(always)]
pub fn tim15ie(&self) -> TIM15IE_R {
TIM15IE_R::new(((self.bits >> 2) & 0x01) != 0)
}
#[doc = "Bit 3 - TIM16IE"]
#[inline(always)]
pub fn tim16ie(&self) -> TIM16IE_R {
TIM16IE_R::new(((self.bits >> 3) & 0x01) != 0)
}
#[doc = "Bit 4 - TIM17IE"]
#[inline(always)]
pub fn tim17ie(&self) -> TIM17IE_R {
TIM17IE_R::new(((self.bits >> 4) & 0x01) != 0)
}
#[doc = "Bit 5 - SAI1IE"]
#[inline(always)]
pub fn sai1ie(&self) -> SAI1IE_R {
SAI1IE_R::new(((self.bits >> 5) & 0x01) != 0)
}
#[doc = "Bit 6 - SAI2IE"]
#[inline(always)]
pub fn sai2ie(&self) -> SAI2IE_R {
SAI2IE_R::new(((self.bits >> 6) & 0x01) != 0)
}
#[doc = "Bit 7 - DFSDM1IE"]
#[inline(always)]
pub fn dfsdm1ie(&self) -> DFSDM1IE_R {
DFSDM1IE_R::new(((self.bits >> 7) & 0x01) != 0)
}
#[doc = "Bit 8 - CRCIE"]
#[inline(always)]
pub fn crcie(&self) -> CRCIE_R {
CRCIE_R::new(((self.bits >> 8) & 0x01) != 0)
}
#[doc = "Bit 9 - TSCIE"]
#[inline(always)]
pub fn tscie(&self) -> TSCIE_R {
TSCIE_R::new(((self.bits >> 9) & 0x01) != 0)
}
#[doc = "Bit 10 - ICACHEIE"]
#[inline(always)]
pub fn icacheie(&self) -> ICACHEIE_R {
ICACHEIE_R::new(((self.bits >> 10) & 0x01) != 0)
}
#[doc = "Bit 11 - ADCIE"]
#[inline(always)]
pub fn adcie(&self) -> ADCIE_R {
ADCIE_R::new(((self.bits >> 11) & 0x01) != 0)
}
#[doc = "Bit 12 - AESIE"]
#[inline(always)]
pub fn aesie(&self) -> AESIE_R {
AESIE_R::new(((self.bits >> 12) & 0x01) != 0)
}
#[doc = "Bit 13 - HASHIE"]
#[inline(always)]
pub fn hashie(&self) -> HASHIE_R {
HASHIE_R::new(((self.bits >> 13) & 0x01) != 0)
}
#[doc = "Bit 14 - RNGIE"]
#[inline(always)]
pub fn rngie(&self) -> RNGIE_R {
RNGIE_R::new(((self.bits >> 14) & 0x01) != 0)
}
#[doc = "Bit 15 - PKAIE"]
#[inline(always)]
pub fn pkaie(&self) -> PKAIE_R {
PKAIE_R::new(((self.bits >> 15) & 0x01) != 0)
}
#[doc = "Bit 16 - SDMMC1IE"]
#[inline(always)]
pub fn sdmmc1ie(&self) -> SDMMC1IE_R {
SDMMC1IE_R::new(((self.bits >> 16) & 0x01) != 0)
}
#[doc = "Bit 17 - FMC_REGIE"]
#[inline(always)]
pub fn fmc_regie(&self) -> FMC_REGIE_R {
FMC_REGIE_R::new(((self.bits >> 17) & 0x01) != 0)
}
#[doc = "Bit 18 - OCTOSPI1_REGIE"]
#[inline(always)]
pub fn octospi1_regie(&self) -> OCTOSPI1_REGIE_R {
OCTOSPI1_REGIE_R::new(((self.bits >> 18) & 0x01) != 0)
}
#[doc = "Bit 19 - RTCIE"]
#[inline(always)]
pub fn rtcie(&self) -> RTCIE_R {
RTCIE_R::new(((self.bits >> 19) & 0x01) != 0)
}
#[doc = "Bit 20 - PWRIE"]
#[inline(always)]
pub fn pwrie(&self) -> PWRIE_R {
PWRIE_R::new(((self.bits >> 20) & 0x01) != 0)
}
#[doc = "Bit 21 - SYSCFGIE"]
#[inline(always)]
pub fn syscfgie(&self) -> SYSCFGIE_R {
SYSCFGIE_R::new(((self.bits >> 21) & 0x01) != 0)
}
#[doc = "Bit 22 - DMA1IE"]
#[inline(always)]
pub fn dma1ie(&self) -> DMA1IE_R {
DMA1IE_R::new(((self.bits >> 22) & 0x01) != 0)
}
#[doc = "Bit 23 - DMA2IE"]
#[inline(always)]
pub fn dma2ie(&self) -> DMA2IE_R {
DMA2IE_R::new(((self.bits >> 23) & 0x01) != 0)
}
#[doc = "Bit 24 - DMAMUX1IE"]
#[inline(always)]
pub fn dmamux1ie(&self) -> DMAMUX1IE_R {
DMAMUX1IE_R::new(((self.bits >> 24) & 0x01) != 0)
}
#[doc = "Bit 25 - RCCIE"]
#[inline(always)]
pub fn rccie(&self) -> RCCIE_R {
RCCIE_R::new(((self.bits >> 25) & 0x01) != 0)
}
#[doc = "Bit 26 - FLASHIE"]
#[inline(always)]
pub fn flashie(&self) -> FLASHIE_R {
FLASHIE_R::new(((self.bits >> 26) & 0x01) != 0)
}
#[doc = "Bit 27 - FLASH_REGIE"]
#[inline(always)]
pub fn flash_regie(&self) -> FLASH_REGIE_R {
FLASH_REGIE_R::new(((self.bits >> 27) & 0x01) != 0)
}
#[doc = "Bit 28 - EXTIIE"]
#[inline(always)]
pub fn extiie(&self) -> EXTIIE_R {
EXTIIE_R::new(((self.bits >> 28) & 0x01) != 0)
}
#[doc = "Bit 29 - OTFDEC1IE"]
#[inline(always)]
pub fn otfdec1ie(&self) -> OTFDEC1IE_R {
OTFDEC1IE_R::new(((self.bits >> 29) & 0x01) != 0)
}
}
impl W {
#[doc = "Bit 0 - TIM8IE"]
#[inline(always)]
pub fn tim8ie(&mut self) -> TIM8IE_W {
TIM8IE_W { w: self }
}
#[doc = "Bit 1 - USART1IE"]
#[inline(always)]
pub fn usart1ie(&mut self) -> USART1IE_W {
USART1IE_W { w: self }
}
#[doc = "Bit 2 - TIM15IE"]
#[inline(always)]
pub fn tim15ie(&mut self) -> TIM15IE_W {
TIM15IE_W { w: self }
}
#[doc = "Bit 3 - TIM16IE"]
#[inline(always)]
pub fn tim16ie(&mut self) -> TIM16IE_W {
TIM16IE_W { w: self }
}
#[doc = "Bit 4 - TIM17IE"]
#[inline(always)]
pub fn tim17ie(&mut self) -> TIM17IE_W {
TIM17IE_W { w: self }
}
#[doc = "Bit 5 - SAI1IE"]
#[inline(always)]
pub fn sai1ie(&mut self) -> SAI1IE_W {
SAI1IE_W { w: self }
}
#[doc = "Bit 6 - SAI2IE"]
#[inline(always)]
pub fn sai2ie(&mut self) -> SAI2IE_W {
SAI2IE_W { w: self }
}
#[doc = "Bit 7 - DFSDM1IE"]
#[inline(always)]
pub fn dfsdm1ie(&mut self) -> DFSDM1IE_W {
DFSDM1IE_W { w: self }
}
#[doc = "Bit 8 - CRCIE"]
#[inline(always)]
pub fn crcie(&mut self) -> CRCIE_W {
CRCIE_W { w: self }
}
#[doc = "Bit 9 - TSCIE"]
#[inline(always)]
pub fn tscie(&mut self) -> TSCIE_W {
TSCIE_W { w: self }
}
#[doc = "Bit 10 - ICACHEIE"]
#[inline(always)]
pub fn icacheie(&mut self) -> ICACHEIE_W {
ICACHEIE_W { w: self }
}
#[doc = "Bit 11 - ADCIE"]
#[inline(always)]
pub fn adcie(&mut self) -> ADCIE_W {
ADCIE_W { w: self }
}
#[doc = "Bit 12 - AESIE"]
#[inline(always)]
pub fn aesie(&mut self) -> AESIE_W {
AESIE_W { w: self }
}
#[doc = "Bit 13 - HASHIE"]
#[inline(always)]
pub fn hashie(&mut self) -> HASHIE_W {
HASHIE_W { w: self }
}
#[doc = "Bit 14 - RNGIE"]
#[inline(always)]
pub fn rngie(&mut self) -> RNGIE_W {
RNGIE_W { w: self }
}
#[doc = "Bit 15 - PKAIE"]
#[inline(always)]
pub fn pkaie(&mut self) -> PKAIE_W {
PKAIE_W { w: self }
}
#[doc = "Bit 16 - SDMMC1IE"]
#[inline(always)]
pub fn sdmmc1ie(&mut self) -> SDMMC1IE_W {
SDMMC1IE_W { w: self }
}
#[doc = "Bit 17 - FMC_REGIE"]
#[inline(always)]
pub fn fmc_regie(&mut self) -> FMC_REGIE_W {
FMC_REGIE_W { w: self }
}
#[doc = "Bit 18 - OCTOSPI1_REGIE"]
#[inline(always)]
pub fn octospi1_regie(&mut self) -> OCTOSPI1_REGIE_W {
OCTOSPI1_REGIE_W { w: self }
}
#[doc = "Bit 19 - RTCIE"]
#[inline(always)]
pub fn rtcie(&mut self) -> RTCIE_W {
RTCIE_W { w: self }
}
#[doc = "Bit 20 - PWRIE"]
#[inline(always)]
pub fn pwrie(&mut self) -> PWRIE_W {
PWRIE_W { w: self }
}
#[doc = "Bit 21 - SYSCFGIE"]
#[inline(always)]
pub fn syscfgie(&mut self) -> SYSCFGIE_W {
SYSCFGIE_W { w: self }
}
#[doc = "Bit 22 - DMA1IE"]
#[inline(always)]
pub fn dma1ie(&mut self) -> DMA1IE_W {
DMA1IE_W { w: self }
}
#[doc = "Bit 23 - DMA2IE"]
#[inline(always)]
pub fn dma2ie(&mut self) -> DMA2IE_W {
DMA2IE_W { w: self }
}
#[doc = "Bit 24 - DMAMUX1IE"]
#[inline(always)]
pub fn dmamux1ie(&mut self) -> DMAMUX1IE_W {
DMAMUX1IE_W { w: self }
}
#[doc = "Bit 25 - RCCIE"]
#[inline(always)]
pub fn rccie(&mut self) -> RCCIE_W {
RCCIE_W { w: self }
}
#[doc = "Bit 26 - FLASHIE"]
#[inline(always)]
pub fn flashie(&mut self) -> FLASHIE_W {
FLASHIE_W { w: self }
}
#[doc = "Bit 27 - FLASH_REGIE"]
#[inline(always)]
pub fn flash_regie(&mut self) -> FLASH_REGIE_W {
FLASH_REGIE_W { w: self }
}
#[doc = "Bit 28 - EXTIIE"]
#[inline(always)]
pub fn extiie(&mut self) -> EXTIIE_W {
EXTIIE_W { w: self }
}
#[doc = "Bit 29 - OTFDEC1IE"]
#[inline(always)]
pub fn otfdec1ie(&mut self) -> OTFDEC1IE_W {
OTFDEC1IE_W { w: self }
}
}
|
extern crate facade;
use facade::oo_facade::run_oo;
use facade::fn_facade::run_fn;
fn main(){
run_oo();
run_fn();
} |
#[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::AES_DMAMIS {
#[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_DMAMIS_CINR {
bits: bool,
}
impl AES_DMAMIS_CINR {
#[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_DMAMIS_CINW<'a> {
w: &'a mut W,
}
impl<'a> _AES_DMAMIS_CINW<'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 << 0);
self.w.bits |= ((value as u32) & 1) << 0;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_DMAMIS_COUTR {
bits: bool,
}
impl AES_DMAMIS_COUTR {
#[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_DMAMIS_COUTW<'a> {
w: &'a mut W,
}
impl<'a> _AES_DMAMIS_COUTW<'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_DMAMIS_DINR {
bits: bool,
}
impl AES_DMAMIS_DINR {
#[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_DMAMIS_DINW<'a> {
w: &'a mut W,
}
impl<'a> _AES_DMAMIS_DINW<'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 << 2);
self.w.bits |= ((value as u32) & 1) << 2;
self.w
}
}
#[doc = r"Value of the field"]
pub struct AES_DMAMIS_DOUTR {
bits: bool,
}
impl AES_DMAMIS_DOUTR {
#[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_DMAMIS_DOUTW<'a> {
w: &'a mut W,
}
impl<'a> _AES_DMAMIS_DOUTW<'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 << 3);
self.w.bits |= ((value as u32) & 1) << 3;
self.w
}
}
impl R {
#[doc = r"Value of the register as raw bits"]
#[inline(always)]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bit 0 - Context In DMA Done Masked Interrupt Status"]
#[inline(always)]
pub fn aes_dmamis_cin(&self) -> AES_DMAMIS_CINR {
let bits = ((self.bits >> 0) & 1) != 0;
AES_DMAMIS_CINR { bits }
}
#[doc = "Bit 1 - Context Out DMA Done Masked Interrupt Status"]
#[inline(always)]
pub fn aes_dmamis_cout(&self) -> AES_DMAMIS_COUTR {
let bits = ((self.bits >> 1) & 1) != 0;
AES_DMAMIS_COUTR { bits }
}
#[doc = "Bit 2 - Data In DMA Done Masked Interrupt Status"]
#[inline(always)]
pub fn aes_dmamis_din(&self) -> AES_DMAMIS_DINR {
let bits = ((self.bits >> 2) & 1) != 0;
AES_DMAMIS_DINR { bits }
}
#[doc = "Bit 3 - Data Out DMA Done Masked Interrupt Status"]
#[inline(always)]
pub fn aes_dmamis_dout(&self) -> AES_DMAMIS_DOUTR {
let bits = ((self.bits >> 3) & 1) != 0;
AES_DMAMIS_DOUTR { 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 0 - Context In DMA Done Masked Interrupt Status"]
#[inline(always)]
pub fn aes_dmamis_cin(&mut self) -> _AES_DMAMIS_CINW {
_AES_DMAMIS_CINW { w: self }
}
#[doc = "Bit 1 - Context Out DMA Done Masked Interrupt Status"]
#[inline(always)]
pub fn aes_dmamis_cout(&mut self) -> _AES_DMAMIS_COUTW {
_AES_DMAMIS_COUTW { w: self }
}
#[doc = "Bit 2 - Data In DMA Done Masked Interrupt Status"]
#[inline(always)]
pub fn aes_dmamis_din(&mut self) -> _AES_DMAMIS_DINW {
_AES_DMAMIS_DINW { w: self }
}
#[doc = "Bit 3 - Data Out DMA Done Masked Interrupt Status"]
#[inline(always)]
pub fn aes_dmamis_dout(&mut self) -> _AES_DMAMIS_DOUTW {
_AES_DMAMIS_DOUTW { w: self }
}
}
|
//! The main Image API
use crate::parameters::*;
#[derive(Default, Debug, Clone, PartialEq)]
pub struct Image {
pub host: String,
pub prefixes: Vec<String>,
pub identifier: String,
pub region: Region,
pub size: Size,
pub rotation: Rotation,
pub quality: Quality,
pub format: Format
}
impl Image {
/// Creates a new Image API with the host required or optionally the host
/// + prefixes. The host argument requires the full base url with the scheme
/// included.
///
/// ```rust,ignore
/// use iiif::*;
///
/// // Including prefixes upfront
/// let api1 = Image::new(https://ids.lib.harvard.edu/ids/iiif/);
///
/// // Adding prefixes later
/// let mut api2 = Image::new("https://ids.lib.harvard.edu");
/// api2.prefixes(vec!["ids", "iiif"]);
/// ```
///
pub fn new(host: &str) -> Image {
Image {
host: host.into(),
..Default::default()
}
}
/// Sets the prefix/es, these can be optionally provided in the host field
/// when creating a new Image struct, if placed in there they can't be changed later.
pub fn prefixes(&mut self, prefixes: Vec<&str>) {
self.prefixes = prefixes.iter().map(|s| s.to_string()).collect();
}
/// Set the image identifier for the next request
pub fn identifier(&mut self, identifier: &str) {
self.identifier = identifier.into()
}
/// Sets the current image region to full, this is the default and unnecessary
/// for a newly created Image struct
pub fn full_region(&mut self) {
self.region = Region::Full;
}
/// Sets the region is defined as an area where the width and height are both equal to the length of the shorter dimension of the complete image. The region may be positioned anywhere in the longer dimension of the image content at the server’s discretion, and centered is often a reasonable default.
pub fn square_region(&mut self) {
self.region = Region::Square;
}
/// Sets the region of the full image to be returned is specified in terms of absolute pixel values. The value of x represents the number of pixels from the 0 position on the horizontal axis. The value of y represents the number of pixels from the 0 position on the vertical axis. Thus the x,y position 0,0 is the upper left-most pixel of the image. w represents the width of the region and h represents the height of the region in pixels.
pub fn absolute_region(&mut self, x: usize, y: usize, w: usize, h: usize) {
self.region = Region::Abs(Absolute{ x, y, w, h });
}
/// Sets region to be returned is specified as a sequence of percentages of the full image’s dimensions, as reported in the image information document. Thus, x represents the number of pixels from the 0 position on the horizontal axis, calculated as a percentage of the reported width. w represents the width of the region, also calculated as a percentage of the reported width. The same applies to y and h respectively
pub fn pct_region(&mut self, x: f32, y: f32, w: f32, h: f32) {
self.region = Region::Pct({Percentage{ x, y, w, h }})
}
/// Sets the image or region is returned at the maximum size available, as indicated by maxWidth, maxHeight, maxArea in the profile description.
pub fn max_size(&mut self) {
self.size = Size::Max;
}
/// Sets the image or region should be scaled so that its width is exactly equal to w, and the height will be a calculated value that maintains the aspect ratio of the extracted region.
///
/// Do not use this method in conjunction with height, use `width_height(w, h)` instead.
pub fn width(&mut self, w: usize) {
self.size = Size::W(w);
}
/// Sets the image or region should be scaled so that its height is exactly equal to h, and the width will be a calculated value that maintains the aspect ratio of the extracted region.
pub fn height(&mut self, w: usize) {
self.size = Size::W(w);
}
/// Sets the width and height of the returned image is scaled to n% of the width and height of the extracted region. The aspect ratio of the returned image is the same as that of the extracted region.
pub fn pct_size(&mut self, n: u16) {
self.size = Size::Pct(n);
}
/// Sets the width and height of the returned image are exactly w and h. The aspect ratio of the returned image may be different than the extracted region, resulting in a distorted image.
pub fn width_height(&mut self, w: usize, h: usize) {
self.size = Size::WH(w,h);
}
/// Sets the image content is scaled for the best fit such that the resulting width and height are less than or equal to the requested width and height. The exact scaling may be determined by the service provider, based on characteristics including image quality and system performance. The dimensions of the returned image content are calculated to maintain the aspect ratio of the extracted region.
pub fn less_than_width_height(&mut self, w: usize, h: usize) {
self.size = Size::LtWH(w,h);
}
/// Sets the image to be mirrored
pub fn mirrored(&mut self) {
self.rotation = Rotation::Mirror(0.0);
}
/// Sets the image to be rotated 90 degrees
pub fn rotate_right(&mut self) {
self.rotation = Rotation::Normal(90.0);
}
/// Sets the image to be rotated 270 degrees
pub fn rotate_left(&mut self) {
self.rotation = Rotation::Normal(270.0);
}
/// Sets the quality to be full color
pub fn full_color(&mut self) {
self.quality = Quality::Color;
}
/// Sets the image quality to be gray
pub fn gray(&mut self) {
self.quality = Quality::Gray;
}
/// Sets the image quality to be bitonal
pub fn bitonal(&mut self) {
self.quality = Quality::Bitonal;
}
/// Sets the image format to be jpg
pub fn jpg(&mut self) {
self.format = Format::Jpg;
}
/// Sets the image format to be tif
pub fn tif(&mut self) {
self.format = Format::Tif;
}
/// Sets the image format to be png
pub fn png(&mut self) {
self.format = Format::Png;
}
/// Sets the image format to be gif
pub fn gif(&mut self) {
self.format = Format::Gif;
}
/// Sets the image format to be jp2
pub fn jp2(&mut self) {
self.format = Format::Jp2;
}
/// Sets the image format to be pdf
pub fn pdf(&mut self) {
self.format = Format::Pdf;
}
/// Sets the image format to be webp
pub fn webp(&mut self) {
self.format = Format::Webp;
}
} |
use clap::{App, Arg};
use serde_derive::Deserialize;
use std::process::exit;
static REGISTRY: &str = "typeable";
static REPOSITORY: &str = "octopod-web-app-example";
#[derive(Debug, Deserialize)]
struct Resp {
results: Vec<Tag>,
}
#[derive(Debug, Deserialize)]
struct Tag {
name: String,
}
async fn do_request() -> reqwest::Result<Resp> {
let url = format!(
"https://hub.docker.com/v2/repositories/{}/{}/tags",
REGISTRY, REPOSITORY
);
let body = reqwest::get(&url).await?.json::<Resp>().await?;
Ok(body)
}
#[tokio::main]
async fn main() -> std::io::Result<()> {
let matches = App::new("tag_check")
.version("0.1")
.arg(
Arg::with_name("project-name")
.long("project-name")
.short("p")
.required(true)
.takes_value(true),
)
.arg(
Arg::with_name("base-domain")
.long("base-domain")
.short("d")
.required(true)
.takes_value(true),
)
.arg(
Arg::with_name("namespace")
.long("namespace")
.short("s")
.required(true)
.takes_value(true),
)
.arg(
Arg::with_name("name")
.long("name")
.short("n")
.required(true)
.takes_value(true),
)
.arg(
Arg::with_name("tag")
.long("tag")
.short("t")
.required(true)
.takes_value(true),
)
.get_matches();
let _project_name = matches
.value_of("project-name")
.expect("could not get project-name");
let _base_domain = matches
.value_of("base-domain")
.expect("could not get base-domain");
let _namespace = matches
.value_of("namespace")
.expect("could not get namepace");
let _name = matches.value_of("name").expect("could not get name");
let tag = matches.value_of("tag").expect("could not get tag");
let mut tag_found = false;
match do_request().await {
Ok(resp) => tag_found = resp.results.iter().any(|t| t.name == tag),
Err(err) => eprintln!("could not get tags, reason: {:?}", err),
}
if !tag_found {
exit(1)
}
Ok(())
}
|
#[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::EV2_CTRL {
#[doc = r" Modifies the contents of the register"]
#[inline]
pub fn modify<F>(&self, f: F)
where
for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W,
{
let bits = self.register.get();
let r = R { bits: bits };
let mut w = W { bits: bits };
f(&r, &mut w);
self.register.set(w.bits);
}
#[doc = r" Reads the contents of the register"]
#[inline]
pub fn read(&self) -> R {
R {
bits: self.register.get(),
}
}
#[doc = r" Writes to the register"]
#[inline]
pub fn write<F>(&self, f: F)
where
F: FnOnce(&mut W) -> &mut W,
{
let mut w = W::reset_value();
f(&mut w);
self.register.set(w.bits);
}
#[doc = r" Writes the reset value to the register"]
#[inline]
pub fn reset(&self) {
self.write(|w| w)
}
}
#[doc = r" Value of the field"]
pub struct MATCHSELR {
bits: u8,
}
impl MATCHSELR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = "Possible values of the field `HEVENT`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HEVENTR {
#[doc = "Selects the L state and the L match register selected by MATCHSEL."]
SELECTS_THE_L_STATE_,
#[doc = "Selects the H state and the H match register selected by MATCHSEL."]
SELECTS_THE_H_STATE_,
}
impl HEVENTR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
HEVENTR::SELECTS_THE_L_STATE_ => false,
HEVENTR::SELECTS_THE_H_STATE_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> HEVENTR {
match value {
false => HEVENTR::SELECTS_THE_L_STATE_,
true => HEVENTR::SELECTS_THE_H_STATE_,
}
}
#[doc = "Checks if the value of the field is `SELECTS_THE_L_STATE_`"]
#[inline]
pub fn is_selects_the_l_state_(&self) -> bool {
*self == HEVENTR::SELECTS_THE_L_STATE_
}
#[doc = "Checks if the value of the field is `SELECTS_THE_H_STATE_`"]
#[inline]
pub fn is_selects_the_h_state_(&self) -> bool {
*self == HEVENTR::SELECTS_THE_H_STATE_
}
}
#[doc = "Possible values of the field `OUTSEL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OUTSELR {
#[doc = "Selects the inputs elected by IOSEL."]
SELECTS_THE_INPUTS_E,
#[doc = "Selects the outputs selected by IOSEL."]
SELECTS_THE_OUTPUTS_,
}
impl OUTSELR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
OUTSELR::SELECTS_THE_INPUTS_E => false,
OUTSELR::SELECTS_THE_OUTPUTS_ => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> OUTSELR {
match value {
false => OUTSELR::SELECTS_THE_INPUTS_E,
true => OUTSELR::SELECTS_THE_OUTPUTS_,
}
}
#[doc = "Checks if the value of the field is `SELECTS_THE_INPUTS_E`"]
#[inline]
pub fn is_selects_the_inputs_e(&self) -> bool {
*self == OUTSELR::SELECTS_THE_INPUTS_E
}
#[doc = "Checks if the value of the field is `SELECTS_THE_OUTPUTS_`"]
#[inline]
pub fn is_selects_the_outputs_(&self) -> bool {
*self == OUTSELR::SELECTS_THE_OUTPUTS_
}
}
#[doc = r" Value of the field"]
pub struct IOSELR {
bits: u8,
}
impl IOSELR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = "Possible values of the field `IOCOND`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum IOCONDR {
#[doc = "LOW"]
LOW,
#[doc = "Rise"]
RISE,
#[doc = "Fall"]
FALL,
#[doc = "HIGH"]
HIGH,
}
impl IOCONDR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
IOCONDR::LOW => 0,
IOCONDR::RISE => 1,
IOCONDR::FALL => 2,
IOCONDR::HIGH => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> IOCONDR {
match value {
0 => IOCONDR::LOW,
1 => IOCONDR::RISE,
2 => IOCONDR::FALL,
3 => IOCONDR::HIGH,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `LOW`"]
#[inline]
pub fn is_low(&self) -> bool {
*self == IOCONDR::LOW
}
#[doc = "Checks if the value of the field is `RISE`"]
#[inline]
pub fn is_rise(&self) -> bool {
*self == IOCONDR::RISE
}
#[doc = "Checks if the value of the field is `FALL`"]
#[inline]
pub fn is_fall(&self) -> bool {
*self == IOCONDR::FALL
}
#[doc = "Checks if the value of the field is `HIGH`"]
#[inline]
pub fn is_high(&self) -> bool {
*self == IOCONDR::HIGH
}
}
#[doc = "Possible values of the field `COMBMODE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum COMBMODER {
#[doc = "OR. The event occurs when either the specified match or I/O condition occurs."]
OR_THE_EVENT_OCCURS,
#[doc = "MATCH. Uses the specified match only."]
MATCH_USES_THE_SPEC,
#[doc = "IO. Uses the specified I/O condition only."]
IO_USES_THE_SPECIFI,
#[doc = "AND. The event occurs when the specified match and I/O condition occur simultaneously."]
AND_THE_EVENT_OCCUR,
}
impl COMBMODER {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
COMBMODER::OR_THE_EVENT_OCCURS => 0,
COMBMODER::MATCH_USES_THE_SPEC => 1,
COMBMODER::IO_USES_THE_SPECIFI => 2,
COMBMODER::AND_THE_EVENT_OCCUR => 3,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> COMBMODER {
match value {
0 => COMBMODER::OR_THE_EVENT_OCCURS,
1 => COMBMODER::MATCH_USES_THE_SPEC,
2 => COMBMODER::IO_USES_THE_SPECIFI,
3 => COMBMODER::AND_THE_EVENT_OCCUR,
_ => unreachable!(),
}
}
#[doc = "Checks if the value of the field is `OR_THE_EVENT_OCCURS`"]
#[inline]
pub fn is_or_the_event_occurs(&self) -> bool {
*self == COMBMODER::OR_THE_EVENT_OCCURS
}
#[doc = "Checks if the value of the field is `MATCH_USES_THE_SPEC`"]
#[inline]
pub fn is_match_uses_the_spec(&self) -> bool {
*self == COMBMODER::MATCH_USES_THE_SPEC
}
#[doc = "Checks if the value of the field is `IO_USES_THE_SPECIFI`"]
#[inline]
pub fn is_io_uses_the_specifi(&self) -> bool {
*self == COMBMODER::IO_USES_THE_SPECIFI
}
#[doc = "Checks if the value of the field is `AND_THE_EVENT_OCCUR`"]
#[inline]
pub fn is_and_the_event_occur(&self) -> bool {
*self == COMBMODER::AND_THE_EVENT_OCCUR
}
}
#[doc = "Possible values of the field `STATELD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum STATELDR {
#[doc = "STATEV value is added into STATE (the carry-out is ignored)."]
STATEV_VALUE_IS_ADDE,
#[doc = "STATEV value is loaded into STATE."]
STATEV_VALUE_IS_LOAD,
}
impl STATELDR {
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
match *self {
STATELDR::STATEV_VALUE_IS_ADDE => false,
STATELDR::STATEV_VALUE_IS_LOAD => true,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: bool) -> STATELDR {
match value {
false => STATELDR::STATEV_VALUE_IS_ADDE,
true => STATELDR::STATEV_VALUE_IS_LOAD,
}
}
#[doc = "Checks if the value of the field is `STATEV_VALUE_IS_ADDE`"]
#[inline]
pub fn is_statev_value_is_adde(&self) -> bool {
*self == STATELDR::STATEV_VALUE_IS_ADDE
}
#[doc = "Checks if the value of the field is `STATEV_VALUE_IS_LOAD`"]
#[inline]
pub fn is_statev_value_is_load(&self) -> bool {
*self == STATELDR::STATEV_VALUE_IS_LOAD
}
}
#[doc = r" Value of the field"]
pub struct STATEVR {
bits: u8,
}
impl STATEVR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
self.bits
}
}
#[doc = r" Value of the field"]
pub struct MATCHMEMR {
bits: bool,
}
impl MATCHMEMR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bit(&self) -> bool {
self.bits
}
#[doc = r" Returns `true` if the bit is clear (0)"]
#[inline]
pub fn bit_is_clear(&self) -> bool {
!self.bit()
}
#[doc = r" Returns `true` if the bit is set (1)"]
#[inline]
pub fn bit_is_set(&self) -> bool {
self.bit()
}
}
#[doc = "Possible values of the field `DIRECTION`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DIRECTIONR {
#[doc = "Direction independent. This event is triggered regardless of the count direction."]
DIRECTION_INDEPENDEN,
#[doc = "Counting up. This event is triggered only during up-counting when BIDIR = 1."]
COUNTING_UP_THIS_EV,
#[doc = "Counting down. This event is triggered only during down-counting when BIDIR = 1."]
COUNTING_DOWN_THIS_,
#[doc = r" Reserved"]
_Reserved(u8),
}
impl DIRECTIONR {
#[doc = r" Value of the field as raw bits"]
#[inline]
pub fn bits(&self) -> u8 {
match *self {
DIRECTIONR::DIRECTION_INDEPENDEN => 0,
DIRECTIONR::COUNTING_UP_THIS_EV => 1,
DIRECTIONR::COUNTING_DOWN_THIS_ => 2,
DIRECTIONR::_Reserved(bits) => bits,
}
}
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _from(value: u8) -> DIRECTIONR {
match value {
0 => DIRECTIONR::DIRECTION_INDEPENDEN,
1 => DIRECTIONR::COUNTING_UP_THIS_EV,
2 => DIRECTIONR::COUNTING_DOWN_THIS_,
i => DIRECTIONR::_Reserved(i),
}
}
#[doc = "Checks if the value of the field is `DIRECTION_INDEPENDEN`"]
#[inline]
pub fn is_direction_independen(&self) -> bool {
*self == DIRECTIONR::DIRECTION_INDEPENDEN
}
#[doc = "Checks if the value of the field is `COUNTING_UP_THIS_EV`"]
#[inline]
pub fn is_counting_up_this_ev(&self) -> bool {
*self == DIRECTIONR::COUNTING_UP_THIS_EV
}
#[doc = "Checks if the value of the field is `COUNTING_DOWN_THIS_`"]
#[inline]
pub fn is_counting_down_this_(&self) -> bool {
*self == DIRECTIONR::COUNTING_DOWN_THIS_
}
}
#[doc = r" Proxy"]
pub struct _MATCHSELW<'a> {
w: &'a mut W,
}
impl<'a> _MATCHSELW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 0;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `HEVENT`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum HEVENTW {
#[doc = "Selects the L state and the L match register selected by MATCHSEL."]
SELECTS_THE_L_STATE_,
#[doc = "Selects the H state and the H match register selected by MATCHSEL."]
SELECTS_THE_H_STATE_,
}
impl HEVENTW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
HEVENTW::SELECTS_THE_L_STATE_ => false,
HEVENTW::SELECTS_THE_H_STATE_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _HEVENTW<'a> {
w: &'a mut W,
}
impl<'a> _HEVENTW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: HEVENTW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Selects the L state and the L match register selected by MATCHSEL."]
#[inline]
pub fn selects_the_l_state_(self) -> &'a mut W {
self.variant(HEVENTW::SELECTS_THE_L_STATE_)
}
#[doc = "Selects the H state and the H match register selected by MATCHSEL."]
#[inline]
pub fn selects_the_h_state_(self) -> &'a mut W {
self.variant(HEVENTW::SELECTS_THE_H_STATE_)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 4;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `OUTSEL`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum OUTSELW {
#[doc = "Selects the inputs elected by IOSEL."]
SELECTS_THE_INPUTS_E,
#[doc = "Selects the outputs selected by IOSEL."]
SELECTS_THE_OUTPUTS_,
}
impl OUTSELW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
OUTSELW::SELECTS_THE_INPUTS_E => false,
OUTSELW::SELECTS_THE_OUTPUTS_ => true,
}
}
}
#[doc = r" Proxy"]
pub struct _OUTSELW<'a> {
w: &'a mut W,
}
impl<'a> _OUTSELW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: OUTSELW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "Selects the inputs elected by IOSEL."]
#[inline]
pub fn selects_the_inputs_e(self) -> &'a mut W {
self.variant(OUTSELW::SELECTS_THE_INPUTS_E)
}
#[doc = "Selects the outputs selected by IOSEL."]
#[inline]
pub fn selects_the_outputs_(self) -> &'a mut W {
self.variant(OUTSELW::SELECTS_THE_OUTPUTS_)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 5;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _IOSELW<'a> {
w: &'a mut W,
}
impl<'a> _IOSELW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 15;
const OFFSET: u8 = 6;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `IOCOND`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum IOCONDW {
#[doc = "LOW"]
LOW,
#[doc = "Rise"]
RISE,
#[doc = "Fall"]
FALL,
#[doc = "HIGH"]
HIGH,
}
impl IOCONDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
IOCONDW::LOW => 0,
IOCONDW::RISE => 1,
IOCONDW::FALL => 2,
IOCONDW::HIGH => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _IOCONDW<'a> {
w: &'a mut W,
}
impl<'a> _IOCONDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: IOCONDW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "LOW"]
#[inline]
pub fn low(self) -> &'a mut W {
self.variant(IOCONDW::LOW)
}
#[doc = "Rise"]
#[inline]
pub fn rise(self) -> &'a mut W {
self.variant(IOCONDW::RISE)
}
#[doc = "Fall"]
#[inline]
pub fn fall(self) -> &'a mut W {
self.variant(IOCONDW::FALL)
}
#[doc = "HIGH"]
#[inline]
pub fn high(self) -> &'a mut W {
self.variant(IOCONDW::HIGH)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 10;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `COMBMODE`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum COMBMODEW {
#[doc = "OR. The event occurs when either the specified match or I/O condition occurs."]
OR_THE_EVENT_OCCURS,
#[doc = "MATCH. Uses the specified match only."]
MATCH_USES_THE_SPEC,
#[doc = "IO. Uses the specified I/O condition only."]
IO_USES_THE_SPECIFI,
#[doc = "AND. The event occurs when the specified match and I/O condition occur simultaneously."]
AND_THE_EVENT_OCCUR,
}
impl COMBMODEW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
COMBMODEW::OR_THE_EVENT_OCCURS => 0,
COMBMODEW::MATCH_USES_THE_SPEC => 1,
COMBMODEW::IO_USES_THE_SPECIFI => 2,
COMBMODEW::AND_THE_EVENT_OCCUR => 3,
}
}
}
#[doc = r" Proxy"]
pub struct _COMBMODEW<'a> {
w: &'a mut W,
}
impl<'a> _COMBMODEW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: COMBMODEW) -> &'a mut W {
{
self.bits(variant._bits())
}
}
#[doc = "OR. The event occurs when either the specified match or I/O condition occurs."]
#[inline]
pub fn or_the_event_occurs(self) -> &'a mut W {
self.variant(COMBMODEW::OR_THE_EVENT_OCCURS)
}
#[doc = "MATCH. Uses the specified match only."]
#[inline]
pub fn match_uses_the_spec(self) -> &'a mut W {
self.variant(COMBMODEW::MATCH_USES_THE_SPEC)
}
#[doc = "IO. Uses the specified I/O condition only."]
#[inline]
pub fn io_uses_the_specifi(self) -> &'a mut W {
self.variant(COMBMODEW::IO_USES_THE_SPECIFI)
}
#[doc = "AND. The event occurs when the specified match and I/O condition occur simultaneously."]
#[inline]
pub fn and_the_event_occur(self) -> &'a mut W {
self.variant(COMBMODEW::AND_THE_EVENT_OCCUR)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 12;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `STATELD`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum STATELDW {
#[doc = "STATEV value is added into STATE (the carry-out is ignored)."]
STATEV_VALUE_IS_ADDE,
#[doc = "STATEV value is loaded into STATE."]
STATEV_VALUE_IS_LOAD,
}
impl STATELDW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> bool {
match *self {
STATELDW::STATEV_VALUE_IS_ADDE => false,
STATELDW::STATEV_VALUE_IS_LOAD => true,
}
}
}
#[doc = r" Proxy"]
pub struct _STATELDW<'a> {
w: &'a mut W,
}
impl<'a> _STATELDW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: STATELDW) -> &'a mut W {
{
self.bit(variant._bits())
}
}
#[doc = "STATEV value is added into STATE (the carry-out is ignored)."]
#[inline]
pub fn statev_value_is_adde(self) -> &'a mut W {
self.variant(STATELDW::STATEV_VALUE_IS_ADDE)
}
#[doc = "STATEV value is loaded into STATE."]
#[inline]
pub fn statev_value_is_load(self) -> &'a mut W {
self.variant(STATELDW::STATEV_VALUE_IS_LOAD)
}
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 14;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _STATEVW<'a> {
w: &'a mut W,
}
impl<'a> _STATEVW<'a> {
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 31;
const OFFSET: u8 = 15;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = r" Proxy"]
pub struct _MATCHMEMW<'a> {
w: &'a mut W,
}
impl<'a> _MATCHMEMW<'a> {
#[doc = r" Sets the field bit"]
pub fn set_bit(self) -> &'a mut W {
self.bit(true)
}
#[doc = r" Clears the field bit"]
pub fn clear_bit(self) -> &'a mut W {
self.bit(false)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub fn bit(self, value: bool) -> &'a mut W {
const MASK: bool = true;
const OFFSET: u8 = 20;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
#[doc = "Values that can be written to the field `DIRECTION`"]
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum DIRECTIONW {
#[doc = "Direction independent. This event is triggered regardless of the count direction."]
DIRECTION_INDEPENDEN,
#[doc = "Counting up. This event is triggered only during up-counting when BIDIR = 1."]
COUNTING_UP_THIS_EV,
#[doc = "Counting down. This event is triggered only during down-counting when BIDIR = 1."]
COUNTING_DOWN_THIS_,
}
impl DIRECTIONW {
#[allow(missing_docs)]
#[doc(hidden)]
#[inline]
pub fn _bits(&self) -> u8 {
match *self {
DIRECTIONW::DIRECTION_INDEPENDEN => 0,
DIRECTIONW::COUNTING_UP_THIS_EV => 1,
DIRECTIONW::COUNTING_DOWN_THIS_ => 2,
}
}
}
#[doc = r" Proxy"]
pub struct _DIRECTIONW<'a> {
w: &'a mut W,
}
impl<'a> _DIRECTIONW<'a> {
#[doc = r" Writes `variant` to the field"]
#[inline]
pub fn variant(self, variant: DIRECTIONW) -> &'a mut W {
unsafe { self.bits(variant._bits()) }
}
#[doc = "Direction independent. This event is triggered regardless of the count direction."]
#[inline]
pub fn direction_independen(self) -> &'a mut W {
self.variant(DIRECTIONW::DIRECTION_INDEPENDEN)
}
#[doc = "Counting up. This event is triggered only during up-counting when BIDIR = 1."]
#[inline]
pub fn counting_up_this_ev(self) -> &'a mut W {
self.variant(DIRECTIONW::COUNTING_UP_THIS_EV)
}
#[doc = "Counting down. This event is triggered only during down-counting when BIDIR = 1."]
#[inline]
pub fn counting_down_this_(self) -> &'a mut W {
self.variant(DIRECTIONW::COUNTING_DOWN_THIS_)
}
#[doc = r" Writes raw bits to the field"]
#[inline]
pub unsafe fn bits(self, value: u8) -> &'a mut W {
const MASK: u8 = 3;
const OFFSET: u8 = 21;
self.w.bits &= !((MASK as u32) << OFFSET);
self.w.bits |= ((value & MASK) as u32) << OFFSET;
self.w
}
}
impl R {
#[doc = r" Value of the register as raw bits"]
#[inline]
pub fn bits(&self) -> u32 {
self.bits
}
#[doc = "Bits 0:3 - Selects the Match register associated with this event (if any). A match can occur only when the counter selected by the HEVENT bit is running."]
#[inline]
pub fn matchsel(&self) -> MATCHSELR {
let bits = {
const MASK: u8 = 15;
const OFFSET: u8 = 0;
((self.bits >> OFFSET) & MASK as u32) as u8
};
MATCHSELR { bits }
}
#[doc = "Bit 4 - Select L/H counter. Do not set this bit if UNIFY = 1."]
#[inline]
pub fn hevent(&self) -> HEVENTR {
HEVENTR::_from({
const MASK: bool = true;
const OFFSET: u8 = 4;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bit 5 - Input/output select"]
#[inline]
pub fn outsel(&self) -> OUTSELR {
OUTSELR::_from({
const MASK: bool = true;
const OFFSET: u8 = 5;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 6:9 - Selects the input or output signal associated with this event (if any). Do not select an input in this register, if CKMODE is 1x. In this case the clock input is an implicit ingredient of every event."]
#[inline]
pub fn iosel(&self) -> IOSELR {
let bits = {
const MASK: u8 = 15;
const OFFSET: u8 = 6;
((self.bits >> OFFSET) & MASK as u32) as u8
};
IOSELR { bits }
}
#[doc = "Bits 10:11 - Selects the I/O condition for event n. (The detection of edges on outputs lag the conditions that switch the outputs by one SCT clock). In order to guarantee proper edge/state detection, an input must have a minimum pulse width of at least one SCT clock period ."]
#[inline]
pub fn iocond(&self) -> IOCONDR {
IOCONDR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 10;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bits 12:13 - Selects how the specified match and I/O condition are used and combined."]
#[inline]
pub fn combmode(&self) -> COMBMODER {
COMBMODER::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 12;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
#[doc = "Bit 14 - This bit controls how the STATEV value modifies the state selected by HEVENT when this event is the highest-numbered event occurring for that state."]
#[inline]
pub fn stateld(&self) -> STATELDR {
STATELDR::_from({
const MASK: bool = true;
const OFFSET: u8 = 14;
((self.bits >> OFFSET) & MASK as u32) != 0
})
}
#[doc = "Bits 15:19 - This value is loaded into or added to the state selected by HEVENT, depending on STATELD, when this event is the highest-numbered event occurring for that state. If STATELD and STATEV are both zero, there is no change to the STATE value."]
#[inline]
pub fn statev(&self) -> STATEVR {
let bits = {
const MASK: u8 = 31;
const OFFSET: u8 = 15;
((self.bits >> OFFSET) & MASK as u32) as u8
};
STATEVR { bits }
}
#[doc = "Bit 20 - If this bit is one and the COMBMODE field specifies a match component to the triggering of this event, then a match is considered to be active whenever the counter value is GREATER THAN OR EQUAL TO the value specified in the match register when counting up, LESS THEN OR EQUAL TO the match value when counting down. If this bit is zero, a match is only be active during the cycle when the counter is equal to the match value."]
#[inline]
pub fn matchmem(&self) -> MATCHMEMR {
let bits = {
const MASK: bool = true;
const OFFSET: u8 = 20;
((self.bits >> OFFSET) & MASK as u32) != 0
};
MATCHMEMR { bits }
}
#[doc = "Bits 21:22 - Direction qualifier for event generation. This field only applies when the counters are operating in BIDIR mode. If BIDIR = 0, the SCT ignores this field. Value 0x3 is reserved."]
#[inline]
pub fn direction(&self) -> DIRECTIONR {
DIRECTIONR::_from({
const MASK: u8 = 3;
const OFFSET: u8 = 21;
((self.bits >> OFFSET) & MASK as u32) as u8
})
}
}
impl W {
#[doc = r" Reset value of the register"]
#[inline]
pub fn reset_value() -> W {
W { bits: 0 }
}
#[doc = r" Writes raw bits to the register"]
#[inline]
pub unsafe fn bits(&mut self, bits: u32) -> &mut Self {
self.bits = bits;
self
}
#[doc = "Bits 0:3 - Selects the Match register associated with this event (if any). A match can occur only when the counter selected by the HEVENT bit is running."]
#[inline]
pub fn matchsel(&mut self) -> _MATCHSELW {
_MATCHSELW { w: self }
}
#[doc = "Bit 4 - Select L/H counter. Do not set this bit if UNIFY = 1."]
#[inline]
pub fn hevent(&mut self) -> _HEVENTW {
_HEVENTW { w: self }
}
#[doc = "Bit 5 - Input/output select"]
#[inline]
pub fn outsel(&mut self) -> _OUTSELW {
_OUTSELW { w: self }
}
#[doc = "Bits 6:9 - Selects the input or output signal associated with this event (if any). Do not select an input in this register, if CKMODE is 1x. In this case the clock input is an implicit ingredient of every event."]
#[inline]
pub fn iosel(&mut self) -> _IOSELW {
_IOSELW { w: self }
}
#[doc = "Bits 10:11 - Selects the I/O condition for event n. (The detection of edges on outputs lag the conditions that switch the outputs by one SCT clock). In order to guarantee proper edge/state detection, an input must have a minimum pulse width of at least one SCT clock period ."]
#[inline]
pub fn iocond(&mut self) -> _IOCONDW {
_IOCONDW { w: self }
}
#[doc = "Bits 12:13 - Selects how the specified match and I/O condition are used and combined."]
#[inline]
pub fn combmode(&mut self) -> _COMBMODEW {
_COMBMODEW { w: self }
}
#[doc = "Bit 14 - This bit controls how the STATEV value modifies the state selected by HEVENT when this event is the highest-numbered event occurring for that state."]
#[inline]
pub fn stateld(&mut self) -> _STATELDW {
_STATELDW { w: self }
}
#[doc = "Bits 15:19 - This value is loaded into or added to the state selected by HEVENT, depending on STATELD, when this event is the highest-numbered event occurring for that state. If STATELD and STATEV are both zero, there is no change to the STATE value."]
#[inline]
pub fn statev(&mut self) -> _STATEVW {
_STATEVW { w: self }
}
#[doc = "Bit 20 - If this bit is one and the COMBMODE field specifies a match component to the triggering of this event, then a match is considered to be active whenever the counter value is GREATER THAN OR EQUAL TO the value specified in the match register when counting up, LESS THEN OR EQUAL TO the match value when counting down. If this bit is zero, a match is only be active during the cycle when the counter is equal to the match value."]
#[inline]
pub fn matchmem(&mut self) -> _MATCHMEMW {
_MATCHMEMW { w: self }
}
#[doc = "Bits 21:22 - Direction qualifier for event generation. This field only applies when the counters are operating in BIDIR mode. If BIDIR = 0, the SCT ignores this field. Value 0x3 is reserved."]
#[inline]
pub fn direction(&mut self) -> _DIRECTIONW {
_DIRECTIONW { w: self }
}
}
|
#[doc = "Reader of register PCROP1BER"]
pub type R = crate::R<u32, super::PCROP1BER>;
#[doc = "Reader of field `PCROP1B_END`"]
pub type PCROP1B_END_R = crate::R<u8, u8>;
impl R {
#[doc = "Bits 0:7 - PCROP1B area end offset"]
#[inline(always)]
pub fn pcrop1b_end(&self) -> PCROP1B_END_R {
PCROP1B_END_R::new((self.bits & 0xff) as u8)
}
}
|
// auto generated, do not modify.
// created: Wed Jan 20 00:44:03 2016
// src-file: /QtNetwork/qtcpsocket.h
// dst-file: /src/network/qtcpsocket.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::qabstractsocket::QAbstractSocket; // 773
use std::ops::Deref;
use super::super::core::qobject::QObject; // 771
// <= use block end
// ext block begin =>
// #[link(name = "Qt5Core")]
// #[link(name = "Qt5Gui")]
// #[link(name = "Qt5Widgets")]
// #[link(name = "QtInline")]
extern {
fn QTcpSocket_Class_Size() -> c_int;
// proto: const QMetaObject * QTcpSocket::metaObject();
fn _ZNK10QTcpSocket10metaObjectEv(qthis: u64 /* *mut c_void*/);
// proto: void QTcpSocket::QTcpSocket(const QTcpSocket & );
fn _ZN10QTcpSocketC2ERKS_(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
// proto: void QTcpSocket::~QTcpSocket();
fn _ZN10QTcpSocketD2Ev(qthis: u64 /* *mut c_void*/);
// proto: void QTcpSocket::QTcpSocket(QObject * parent);
fn _ZN10QTcpSocketC2EP7QObject(qthis: u64 /* *mut c_void*/, arg0: *mut c_void);
} // <= ext block end
// body block begin =>
// class sizeof(QTcpSocket)=1
#[derive(Default)]
pub struct QTcpSocket {
qbase: QAbstractSocket,
pub qclsinst: u64 /* *mut c_void*/,
}
impl /*struct*/ QTcpSocket {
pub fn inheritFrom(qthis: u64 /* *mut c_void*/) -> QTcpSocket {
return QTcpSocket{qbase: QAbstractSocket::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
}
}
impl Deref for QTcpSocket {
type Target = QAbstractSocket;
fn deref(&self) -> &QAbstractSocket {
return & self.qbase;
}
}
impl AsRef<QAbstractSocket> for QTcpSocket {
fn as_ref(& self) -> & QAbstractSocket {
return & self.qbase;
}
}
// proto: const QMetaObject * QTcpSocket::metaObject();
impl /*struct*/ QTcpSocket {
pub fn metaObject<RetType, T: QTcpSocket_metaObject<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.metaObject(self);
// return 1;
}
}
pub trait QTcpSocket_metaObject<RetType> {
fn metaObject(self , rsthis: & QTcpSocket) -> RetType;
}
// proto: const QMetaObject * QTcpSocket::metaObject();
impl<'a> /*trait*/ QTcpSocket_metaObject<()> for () {
fn metaObject(self , rsthis: & QTcpSocket) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZNK10QTcpSocket10metaObjectEv()};
unsafe {_ZNK10QTcpSocket10metaObjectEv(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QTcpSocket::QTcpSocket(const QTcpSocket & );
impl /*struct*/ QTcpSocket {
pub fn new<T: QTcpSocket_new>(value: T) -> QTcpSocket {
let rsthis = value.new();
return rsthis;
// return 1;
}
}
pub trait QTcpSocket_new {
fn new(self) -> QTcpSocket;
}
// proto: void QTcpSocket::QTcpSocket(const QTcpSocket & );
impl<'a> /*trait*/ QTcpSocket_new for (&'a QTcpSocket) {
fn new(self) -> QTcpSocket {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QTcpSocketC2ERKS_()};
let ctysz: c_int = unsafe{QTcpSocket_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QTcpSocketC2ERKS_(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QTcpSocket{qbase: QAbstractSocket::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// proto: void QTcpSocket::~QTcpSocket();
impl /*struct*/ QTcpSocket {
pub fn free<RetType, T: QTcpSocket_free<RetType>>(& self, overload_args: T) -> RetType {
return overload_args.free(self);
// return 1;
}
}
pub trait QTcpSocket_free<RetType> {
fn free(self , rsthis: & QTcpSocket) -> RetType;
}
// proto: void QTcpSocket::~QTcpSocket();
impl<'a> /*trait*/ QTcpSocket_free<()> for () {
fn free(self , rsthis: & QTcpSocket) -> () {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QTcpSocketD2Ev()};
unsafe {_ZN10QTcpSocketD2Ev(rsthis.qclsinst)};
// return 1;
}
}
// proto: void QTcpSocket::QTcpSocket(QObject * parent);
impl<'a> /*trait*/ QTcpSocket_new for (&'a QObject) {
fn new(self) -> QTcpSocket {
// let qthis: *mut c_void = unsafe{calloc(1, 32)};
// unsafe{_ZN10QTcpSocketC2EP7QObject()};
let ctysz: c_int = unsafe{QTcpSocket_Class_Size()};
let qthis_ph: u64 = unsafe{calloc(1, ctysz as usize)} as u64;
let arg0 = self.qclsinst as *mut c_void;
unsafe {_ZN10QTcpSocketC2EP7QObject(qthis_ph, arg0)};
let qthis: u64 = qthis_ph;
let rsthis = QTcpSocket{qbase: QAbstractSocket::inheritFrom(qthis), qclsinst: qthis, ..Default::default()};
return rsthis;
// return 1;
}
}
// <= body block end
|
use firefly_diagnostics::{SourceSpan, Span, Spanned};
use firefly_syntax_base::{Deprecation, FunctionName};
use super::{Expr, Ident, Name, Type};
/// Type definitions
///
/// ## Examples
///
/// ```text
/// %% Simple types
/// -type foo() :: bar.
/// -opaque foo() :: bar.
///
/// %% Generic/parameterized types
/// -type foo(T) :: [T].
/// -opaque foo(T) :: [T].
/// ```
#[derive(Debug, Clone, Spanned)]
pub struct TypeDef {
#[span]
pub span: SourceSpan,
pub opaque: bool,
pub name: Ident,
pub params: Vec<Name>,
pub ty: Type,
}
impl PartialEq for TypeDef {
fn eq(&self, other: &Self) -> bool {
if self.opaque != other.opaque {
return false;
}
if self.name != other.name {
return false;
}
if self.params != other.params {
return false;
}
if self.ty != other.ty {
return false;
}
return true;
}
}
/// Function type specifications, used for both function specs and callback specs
///
/// ## Example
///
/// ```text
/// %% Monomorphic function
/// -spec foo(A :: map(), Opts :: list({atom(), term()})) -> {ok, map()} | {error, term()}.
///
/// %% Polymorphic function
/// -spec foo(A, Opts :: list({atom, term()})) -> {ok, A} | {error, term()}.
///
/// %% Multiple dispatch function
/// -spec foo(map(), Opts) -> {ok, map()} | {error, term()};
/// foo(list(), Opts) -> {ok, list()} | {error, term()}.
///
/// %% Using `when` to express subtype constraints
/// -spec foo(map(), Opts) -> {ok, map()} | {error, term()}
/// when Opts :: list({atom, term});
/// ```
#[derive(Debug, Clone, Spanned)]
pub struct TypeSpec {
#[span]
pub span: SourceSpan,
pub module: Option<Ident>,
pub function: Ident,
pub sigs: Vec<TypeSig>,
}
impl PartialEq for TypeSpec {
fn eq(&self, other: &Self) -> bool {
self.module == other.module && self.function == other.function && self.sigs == other.sigs
}
}
/// A callback declaration, which is functionally identical to `TypeSpec` in
/// its syntax, but is used to both define a callback function for a behaviour,
/// as well as provide an expected type specification for that function.
#[derive(Debug, Clone, Spanned)]
pub struct Callback {
#[span]
pub span: SourceSpan,
pub optional: bool,
pub module: Option<Ident>,
pub function: Ident,
pub sigs: Vec<TypeSig>,
}
impl PartialEq for Callback {
fn eq(&self, other: &Self) -> bool {
self.optional == other.optional
&& self.module == other.module
&& self.function == other.function
&& self.sigs == other.sigs
}
}
/// Contains type information for a single clause of a function type specification
#[derive(Debug, Clone, PartialEq, Spanned)]
pub struct TypeSig {
#[span]
pub span: SourceSpan,
pub params: Vec<Type>,
pub ret: Box<Type>,
pub guards: Option<Vec<TypeGuard>>,
}
/// Contains a single subtype constraint to be applied to a type specification
#[derive(Debug, Clone, Spanned)]
pub struct TypeGuard {
#[span]
pub span: SourceSpan,
pub var: Name,
pub ty: Type,
}
impl PartialEq for TypeGuard {
fn eq(&self, other: &TypeGuard) -> bool {
self.var == other.var && self.ty == other.ty
}
}
/// Represents a user-defined custom attribute.
///
/// ## Example
///
/// ```text
/// -my_attribute([foo, bar]).
/// ```
#[derive(Debug, Clone, Spanned)]
pub struct UserAttribute {
#[span]
pub span: SourceSpan,
pub name: Ident,
pub value: Expr,
}
impl PartialEq for UserAttribute {
fn eq(&self, other: &Self) -> bool {
self.name == other.name && self.value == other.value
}
}
/// Represents the set of allowed attributes in the body of a module
#[derive(Debug, Clone)]
pub enum Attribute {
Type(TypeDef),
Spec(TypeSpec),
Callback(Callback),
Custom(UserAttribute),
ExportType(SourceSpan, Vec<Span<FunctionName>>),
Export(SourceSpan, Vec<Span<FunctionName>>),
Import(SourceSpan, Ident, Vec<Span<FunctionName>>),
Removed(SourceSpan, Vec<(Span<FunctionName>, Ident)>),
Compile(SourceSpan, Expr),
Vsn(SourceSpan, Expr),
Author(SourceSpan, Expr),
OnLoad(SourceSpan, Span<FunctionName>),
Nifs(SourceSpan, Vec<Span<FunctionName>>),
Behaviour(SourceSpan, Ident),
Deprecation(Vec<Deprecation>),
}
impl Spanned for Attribute {
fn span(&self) -> SourceSpan {
match self {
Self::Type(attr) => attr.span(),
Self::Spec(attr) => attr.span(),
Self::Callback(attr) => attr.span(),
Self::Custom(attr) => attr.span(),
Self::ExportType(span, _)
| Self::Export(span, _)
| Self::Import(span, _, _)
| Self::Removed(span, _)
| Self::Compile(span, _)
| Self::Vsn(span, _)
| Self::Author(span, _)
| Self::OnLoad(span, _)
| Self::Nifs(span, _)
| Self::Behaviour(span, _) => *span,
Self::Deprecation(deprecations) => {
if let Some(d) = deprecations.first() {
d.span()
} else {
SourceSpan::UNKNOWN
}
}
}
}
}
impl PartialEq for Attribute {
fn eq(&self, other: &Self) -> bool {
let left = std::mem::discriminant(self);
let right = std::mem::discriminant(other);
if left != right {
return false;
}
match (self, other) {
(&Attribute::Type(ref x), &Attribute::Type(ref y)) => x == y,
(&Attribute::Spec(ref x), &Attribute::Spec(ref y)) => x == y,
(&Attribute::Callback(ref x), &Attribute::Callback(ref y)) => x == y,
(&Attribute::Custom(ref x), &Attribute::Custom(ref y)) => x == y,
(&Attribute::ExportType(_, ref x), &Attribute::ExportType(_, ref y)) => x == y,
(&Attribute::Export(_, ref x), &Attribute::Export(_, ref y)) => x == y,
(&Attribute::Import(_, ref x1, ref x2), &Attribute::Import(_, ref y1, ref y2)) => {
(x1 == y1) && (x2 == y2)
}
(&Attribute::Removed(_, ref x), &Attribute::Removed(_, ref y)) => x == y,
(&Attribute::Compile(_, ref x), &Attribute::Compile(_, ref y)) => x == y,
(&Attribute::Vsn(_, ref x), &Attribute::Vsn(_, ref y)) => x == y,
(&Attribute::Author(_, ref x), &Attribute::Author(_, ref y)) => x == y,
(&Attribute::OnLoad(_, ref x), &Attribute::OnLoad(_, ref y)) => x == y,
(&Attribute::Nifs(_, ref x), &Attribute::Nifs(_, ref y)) => x == y,
(&Attribute::Behaviour(_, ref x), &Attribute::Behaviour(_, ref y)) => x == y,
_ => false,
}
}
}
|
use std::fmt;
use super::hooks::HookError;
/// This error is returned by the `Manager::recycle` function
#[derive(Debug)]
pub enum RecycleError<E> {
/// Recycling failed for some other reason
Message(String),
/// The error was caused by the backend
Backend(E),
}
impl<E> From<E> for RecycleError<E> {
fn from(e: E) -> Self {
Self::Backend(e)
}
}
impl<E> fmt::Display for RecycleError<E>
where
E: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Message(msg) => write!(f, "An error occured while recycling an object: {}", msg),
Self::Backend(e) => write!(f, "An error occured while recycling an object: {}", e),
}
}
}
impl<E> std::error::Error for RecycleError<E> where E: std::error::Error {}
/// When `Pool::get` returns a timeout error this enum can be used
/// to figure out which step caused the timeout.
#[derive(Debug)]
pub enum TimeoutType {
/// The timeout happened while waiting for a slot to become available
Wait,
/// The timeout happened while creating the object
Create,
/// The timeout happened while recycling an object
Recycle,
}
/// Error structure for `Pool::get`
#[derive(Debug)]
pub enum PoolError<E> {
/// A timeout happened
Timeout(TimeoutType),
/// The backend reported an error
Backend(E),
/// The pool has been closed
Closed,
/// No runtime specified
NoRuntimeSpecified,
/// A post_create hook reported an error
PostCreateHook(HookError<E>),
/// A post_recycle hook reported an error
PostRecycleHook(HookError<E>),
}
impl<E> From<E> for PoolError<E> {
fn from(e: E) -> Self {
Self::Backend(e)
}
}
impl<E> fmt::Display for PoolError<E>
where
E: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Timeout(tt) => match tt {
TimeoutType::Wait => write!(
f,
"A timeout occured while waiting for a slot to become available"
),
TimeoutType::Create => write!(f, "A timeout occured while creating a new object"),
TimeoutType::Recycle => write!(f, "A timeout occured while recycling an object"),
},
Self::Backend(e) => write!(f, "An error occured while creating a new object: {}", e),
Self::Closed => write!(f, "The pool has been closed."),
Self::NoRuntimeSpecified => write!(f, "No runtime specified."),
Self::PostCreateHook(msg) => writeln!(f, "post_create hook failed: {}", msg),
Self::PostRecycleHook(msg) => writeln!(f, "post_recycle hook failed: {}", msg),
}
}
}
impl<E> std::error::Error for PoolError<E> where E: std::error::Error {}
|
// Copyright 2019 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
use {
fidl_fuchsia_wlan_service::{ErrCode, ScanRequest, ScanResult, WlanMarker, WlanProxy},
fidl_fuchsia_wlan_tap::WlantapPhyProxy,
fuchsia_component::client::connect_to_service,
fuchsia_zircon::DurationNum,
wlan_common::{bss::Protection, mac::Bssid},
wlan_hw_sim::*,
};
const CHANNEL: u8 = 1;
const BSS_WPA1: Bssid = Bssid([0x62, 0x73, 0x73, 0x66, 0x6f, 0x6f]);
const SSID_WPA1: &[u8] = b"wpa1___how_nice";
const BSS_WEP: Bssid = Bssid([0x62, 0x73, 0x73, 0x66, 0x6f, 0x72]);
const SSID_WEP: &[u8] = b"wep_is_soooo_secure";
const BSS_MIXED: Bssid = Bssid([0x62, 0x73, 0x73, 0x66, 0x6f, 0x7a]);
const SSID_MIXED: &[u8] = b"this_is_fine";
// TODO(fxb/36399): Refactor this test and other config tests to remove duplicate scan code.
async fn scan(
wlan_service: &WlanProxy,
phy: &WlantapPhyProxy,
helper: &mut test_utils::TestHelper,
) -> ScanResult {
helper
.run_until_complete_or_timeout(
10.seconds(),
"receive a scan response",
EventHandlerBuilder::new()
.on_set_channel(
MatchChannel::new().on_primary(
CHANNEL,
Sequence::start()
.then(
Beacon::send(&phy)
.bssid(BSS_WPA1)
.ssid(SSID_WPA1.to_vec())
.protection(Protection::Wpa1),
)
.then(
Beacon::send(&phy)
.bssid(BSS_WEP)
.ssid(SSID_WEP.to_vec())
.protection(Protection::Wep),
)
.then(
Beacon::send(&phy)
.bssid(BSS_MIXED)
.ssid(SSID_MIXED.to_vec())
.protection(Protection::Wpa1Wpa2Personal),
),
),
)
.build(),
wlan_service.scan(&mut ScanRequest { timeout: 5 }),
)
.await
.unwrap()
}
/// Test a client cannot connect to a wep or wpa network when configured off.
#[fuchsia_async::run_singlethreaded(test)]
async fn configure_legacy_privacy_off() {
let mut helper = test_utils::TestHelper::begin_test(default_wlantap_config_client()).await;
let wlan_service =
connect_to_service::<WlanMarker>().expect("Failed to connect to wlan service");
let () = loop_until_iface_is_found().await;
let proxy = helper.proxy();
let scan_result = scan(&wlan_service, &proxy, &mut helper).await;
assert_eq!(
ErrCode::Ok,
scan_result.error.code,
"The error message was: {}",
scan_result.error.description
);
let mut aps: Vec<_> = scan_result
.aps
.expect("Got empty scan results")
.into_iter()
.map(|ap| (ap.bssid, ap.is_compatible))
.collect();
aps.sort();
let mut expected_aps =
[(BSS_WPA1.0.to_vec(), false), (BSS_WEP.0.to_vec(), false), (BSS_MIXED.0.to_vec(), true)];
expected_aps.sort();
assert_eq!(&expected_aps, &aps[..]);
}
|
use super::memory;
use super::opcodes::Opcode::*;
use super::instructions::Instruction;
const SIGN: usize = 7;
const OVERFLOW: usize = 6;
const BREAK: usize = 4;
const DECIMAL: usize = 3;
const INTERRUPT: usize = 2;
const ZERO: usize = 1;
const CARRY: usize = 0;
pub struct Cpu {
reg_pc: u16, // 16 bit program counter The low and high 8-bit halves of the register are called PCL and PCH
reg_sp: u8, // 8 bit stack pointer // located at $0100-$01FF
reg_flag: Vec<u8>, // 8 bit flag register
// Work Registers
reg_a: u8, // Accumulator
reg_x: u8, // Indexed addressing
reg_y: u8, // Limited indexed addressing
memory: memory::Memory
}
impl Cpu {
pub fn new(mem: memory::Memory) -> Cpu {
Cpu {
reg_pc: 16,
reg_sp: 0xFD,
reg_flag: vec![0,0,1,1,0,1,0,0],
reg_a: 0,
reg_x: 0,
reg_y: 0,
memory: mem,
}
}
pub fn power_on_reset(&mut self) {
self.reg_pc = 16;
self.reg_sp = 0xFD;
self.reg_flag = vec![0,0,1,1,0,1,0,0];
}
fn read_u8(&self, pc: u16) -> u8 {
self.memory.read_u8(pc)
}
fn read_u16(&self, pc: u16) -> u16 {
self.memory.read_u16(pc)
}
/*fn read_rom_u8(&self, pc: u16) -> u8 {
self.memory.read_rom_u8(pc)
}
fn read_rom_u16(&self, pc: u16) -> u16 {
self.memory.read_rom_u16(pc)
}*/
fn write_u8(&mut self, addr: u16, obj: u8) {
self.memory.write_u8(addr, obj);
}
fn write_u16(&mut self, addr: u16, obj: u16){
self.memory.write_u16(addr,obj);
}
fn run_instruction(&mut self){
let instru = self.read_instruction();
self.incr_pc(1);
// Adjust information
println!("Instruction: {:#x}",instru.opcode);
println!("Program Counter: {:#x}",self.reg_pc);
self.execute_instruction(instru);
}
fn read_instruction(&mut self) -> Instruction {
Instruction{opcode: self.read_u8(self.reg_pc)}
}
fn execute_instruction(&mut self, instr: Instruction){
match instr.opcode() {
// The only thing changing is where the memory is coming from, so
// simple get the correct chunk and run the helper program
AdcImmediate => {
let m = self.immediate();
self.adc(m);
},
AdcZeroPage => {
let m = self.zero_page();
self.adc(m);
},
AdcZeroPageX => {
let m = self.zero_page_x();
self.adc(m);
},
AdcAbsolute => {
let m = self.absolute();
self.adc(m);
},
AdcAbsoluteX => {
let m = self.absolute_x();
self.adc(m);
},
AdcAbsoluteY => {
let m = self.absolute_y();
self.adc(m);
},
AdcIndirectX => {
let m = self.indirect_x();
self.adc(m);
},
AdcIndirectY => {
let m = self.indirect_y();
self.adc(m);
},
AndImmediate => {
let m = self.immediate();
self.and(m);
},
AndZeroPage => {
let m = self.zero_page();
self.and(m);
},
AndZeroPageX => {
let m = self.zero_page_x();
self.and(m);
},
AndAbsolute => {
let m = self.absolute();
self.and(m);
},
AndAbsoluteX => {
let m = self.absolute_x();
self.and(m);
},
AndAbsoluteY => {
let m = self.absolute_y();
self.and(m);
},
AndIndirectX => {
let m = self.indirect_x();
self.and(m);
},
AndIndirectY => {
let m = self.indirect_y();
self.and(m);
},
AslAccumulator => {
let b = self.reg_a;
self.asl(b);
},
AslZeroPage => {
let b = self.zero_page();
self.asl(b);
},
AslZeroPageX => {
let b = self.zero_page_x();
self.asl(b);
},
AslAbsolute => {
let b = self.absolute();
self.asl(b);
},
AslAbsoluteX => {
let b = self.absolute_x();
self.asl(b);
},
Bcc => {
let m = self.read_u8(self.reg_pc);
if self.reg_flag[CARRY] == 0 {
self.incr_pc(m);
} else {
self.reg_pc += 1;
}
},
Bcs => {
let m = self.read_u8(self.reg_pc);
if self.reg_flag[CARRY] == 1 {
self.incr_pc(m);
} else {
self.incr_pc(1);
}
},
Beq => {
let m = self.read_u8(self.reg_pc);
if self.reg_flag[ZERO] == 1 {
self.incr_pc(m);
} else {
self.incr_pc(1);
}
},
BitZeroPage => {
let m = self.zero_page();
let t = self.reg_a & m;
self.reg_flag[SIGN] = if (t & 0x80) == 0x80 { 1 } else { 0 };
self.reg_flag[OVERFLOW] = if (t & 0x40) == 0x40 { 1 } else { 0 };
self.reg_flag[ZERO] = if t == 0x00 { 1 } else { 0 };
},
BitAbsolute => {
let m = self.absolute();
let t = self.reg_a & m;
self.reg_flag[SIGN] = if (t & 0x80) == 0x80 { 1 } else { 0 };
self.reg_flag[OVERFLOW] = if (t & 0x40) == 0x40 { 1 } else { 0 };
self.reg_flag[ZERO] = if t == 0x00 { 1 } else { 0 };
},
Bmi => {
let m = self.read_u8(self.reg_pc);
if self.reg_flag[SIGN] == 1 {
self.incr_pc(m);
} else {
self.incr_pc(1);
}
},
Bne => {
let m = self.read_u8(self.reg_pc);
if self.reg_flag[ZERO] == 0 {
self.incr_pc(m);
} else {
self.incr_pc(1);
}
},
Bpl => {
let m = self.read_u8(self.reg_pc);
if self.reg_flag[SIGN] == 0 {
self.incr_pc(m);
} else {
self.incr_pc(1);
}
},
Brk => {
self.incr_pc(1); //Byte after the break command will not be evaluated
let pc = self.reg_pc;
let hi = (self.reg_pc >> 8) as u8;
let lo = self.reg_pc as u8;
let p = ((self.reg_flag[SIGN] as u8) << 7) + ((self.reg_flag[OVERFLOW] as u8) << 6) + ((self.reg_flag[BREAK] as u8) << 4) + ((self.reg_flag[DECIMAL] as u8) << 3) + ((self.reg_flag[INTERRUPT] as u8) << 2) + ((self.reg_flag[ZERO] as u8) << 1) +(self.reg_flag[CARRY] as u8);
self.write_u8(pc,hi); //Push(write) the PC high to the top of stack
self.reg_sp -= 1;
self.write_u8(pc,lo); //Push(write) the PC low to the top of stack
self.reg_sp -= 1;
self.write_u8(pc,p|0x10); //Push(write) something else on stack
self.reg_sp -= 1;
let l = self.read_u8(0xFFFE) as u16;
let h = (self.read_u8(0xFFFF) as u16) << 8;
self.reg_pc = h | l
},
Bvc => {
let m = self.read_u8(self.reg_pc);
if self.reg_flag[OVERFLOW] == 0 {
self.incr_pc(m);
} else {
self.incr_pc(1);
}
},
Bvs => {
let m = self.read_u8(self.reg_pc);
if self.reg_flag[OVERFLOW] == 1 {
self.incr_pc(m);
} else {
self.incr_pc(1);
}
},
Clc => {self.clear_carry();}, // Clear Carry Flags
Cld => {self.clear_decimal();}, // Clear Decimal Mode
Cli => {self.clear_interrupt();}, // Clear Interrupt Disable Bit
Clv => {self.clear_overflow();}, // Clear Overflow Flag
Sec => {self.set_carry();}, // Set Carry Flag
Sed => {self.set_decimal();}, // Set Decimal Mode
Sei => {self.set_interrupt();}, // Set Interrupt Disable Bit
CmpImmediate => {
let m = self.immediate();
let a = self.reg_a;
self.cmp(m,a);
},
CmpZeroPage => {
let m = self.zero_page();
let a = self.reg_a;
self.cmp(m,a);
},
CmpZeroPageX => {
let m = self.zero_page_x();
let a = self.reg_a;
self.cmp(m,a);
},
CmpAbsolute => {
let m = self.absolute();
let a = self.reg_a;
self.cmp(m,a);
},
CmpAbsoluteX => {
let m = self.absolute_x();
let a = self.reg_a;
self.cmp(m,a);
},
CmpAbsoluteY => {
let m = self.absolute_y();
let a = self.reg_a;
self.cmp(m,a);
},
CmpIndirectX => {
let m = self.indirect_x();
let a = self.reg_a;
self.cmp(m,a);
},
CmpIndirectY => {
let m = self.indirect_y();
let a = self.reg_a;
self.cmp(m,a);
},
CpxImmediate => {
let m = self.immediate();
let x = self.reg_x;
self.cmp(m,x);
},
CpxZeroPage => {
let m = self.zero_page();
let x = self.reg_x;
self.cmp(m,x);
},
CpxAbsolute => {
let m = self.absolute();
let x = self.reg_x;
self.cmp(m,x);
},
CpyImmediate => {
let m = self.immediate();
let y = self.reg_y;
self.cmp(m,y);
},
CpyZeroPage => {
let m = self.zero_page();
let y = self.reg_y;
self.cmp(m,y);
},
CpyAbsolute => {
let m = self.absolute();
let y = self.reg_y;
self.cmp(m,y);
},
DecZeroPage => {
let m = (self.zero_page() - 1) & 0xFF;
self.sign_zero_flags(m)
},
DecZeroPageX => {
let m = (self.zero_page_x() - 1) & 0xFF;
self.sign_zero_flags(m)
},
DecAbsolute => {
let m = (self.absolute() - 1) & 0xFF;
self.sign_zero_flags(m)
},
DecAbsoluteX => {
let m = (self.absolute_x() - 1) & 0xFF;
self.sign_zero_flags(m)
},
Dex => {
self.reg_x = self.reg_x - 1;
let x = self.reg_x;
self.sign_zero_flags(x);
},
Dey => {
self.reg_y = self.reg_y - 1;
let y = self.reg_y;
self.sign_zero_flags(y)
},
Inx => {
self.reg_x = self.reg_x + 1;
let x = self.reg_x;
self.sign_zero_flags(x)
},
Iny => {
self.reg_y = self.reg_y + 1;
let y = self.reg_y;
self.sign_zero_flags(y)
},
EorImmediate => {
let m = self.immediate();
self.eor(m);
},
EorZeroPage => {
let m = self.zero_page();
self.eor(m);
},
EorZeroPageX => {
let m = self.zero_page_x();
self.eor(m);
},
EorAbsolute => {
let m = self.absolute();
self.eor(m);
},
EorAbsoluteX => {
let m = self.absolute_x();
self.eor(m);
},
EorAbsoluteY => {
let m = self.absolute_y();
self.eor(m);
},
EorIndirectX => {
let m = self.indirect_x();
self.eor(m);
},
EorIndirectY => {
let m = self.indirect_y();
self.eor(m);
},
IncZeroPage => {
let m = (self.zero_page() + 1) & 0xFF;
self.sign_zero_flags(m);
},
IncZeroPageX => {
let m = (self.zero_page_x() + 1) & 0xFF;
self.sign_zero_flags(m);
},
IncAbsolute => {
let m = (self.absolute() + 1) & 0xFF;
self.sign_zero_flags(m);
},
IncAbsoluteX => {
let m = (self.absolute_x() + 1) & 0xFF;
self.sign_zero_flags(m);
},
JmpAbsolute => {
self.reg_pc = self.read_u16(self.reg_pc);
},
JmpIndirect => {
self.reg_pc = self.read_u16(self.reg_pc);
},
JsrAbsolute => {// push (PC+2),(PC+1) -> PCL,(PC+2) -> PCH
// TODO: Reconsider stack setup. Specialized functions or actual stack might be cool
let pc = self.reg_pc + 2;
let sp = self.reg_sp as u16;
self.write_u16(sp, pc); // Push PC + 2 onto stack
let jsr_addr = self.read_u16(self.reg_pc+1);
self.reg_pc = jsr_addr;
},
LdaImmediate => {
self.reg_a = self.immediate();
let l = self.reg_a;
self.sign_zero_flags(l);
},
LdaZeroPage => {
self.reg_a = self.zero_page();
let l = self.reg_a;
self.sign_zero_flags(l);
},
LdaZeroPageX => {
self.reg_a = self.zero_page_x();
let l = self.reg_a;
self.sign_zero_flags(l);
},
LdaAbsolute => {
self.reg_a = self.absolute();
let l = self.reg_a;
self.sign_zero_flags(l);
},
LdaAbsoluteX => {
self.reg_a = self.absolute_x();
let l = self.reg_a;
self.sign_zero_flags(l);
},
LdaAbsoluteY => {
self.reg_a = self.absolute_y();
let l = self.reg_a;
self.sign_zero_flags(l);
},
LdaIndirectX => {
self.reg_a = self.indirect_x();
let l = self.reg_a;
self.sign_zero_flags(l);
},
LdaIndirectY => {
self.reg_a = self.indirect_y();
let l = self.reg_a;
self.sign_zero_flags(l);
},
LdxImmediate => {
self.reg_x = self.immediate();
let l = self.reg_x;
self.sign_zero_flags(l);
},
LdxZeroPage => {
self.reg_x = self.zero_page();
let l = self.reg_x;
self.sign_zero_flags(l);
},
LdxZeroPageX => {
self.reg_x = self.zero_page_x();
let l = self.reg_x;
self.sign_zero_flags(l);
},
LdxAbsolute => {
self.reg_x = self.absolute();
let l = self.reg_x;
self.sign_zero_flags(l);
},
LdxAbsoluteX => {
self.reg_x = self.absolute_x();
let l = self.reg_x;
self.sign_zero_flags(l);
},
LdyImmediate => {
self.reg_y = self.immediate();
let l = self.reg_y;
self.sign_zero_flags(l);
},
LdyZeroPage => {
self.reg_y = self.zero_page();
let l = self.reg_y;
self.sign_zero_flags(l);
},
LdyZeroPageX => {
self.reg_y = self.zero_page_x();
let l = self.reg_y;
self.sign_zero_flags(l);
},
LdyAbsolute => {
self.reg_y = self.absolute();
let l = self.reg_y;
self.sign_zero_flags(l);
},
LdyAbsoluteX => {
self.reg_y = self.absolute_x();
let l = self.reg_y;
self.sign_zero_flags(l);
},
LsrAccumulator => {
let a = self.reg_a;
self.lsr(a);
},
LsrZeroPage => {
let b = self.zero_page();
self.lsr(b);
},
LsrZeroPageX => {
let b = self.zero_page_x();
self.lsr(b);
},
LSRAbsolute => {
let b = self.absolute();
self.lsr(b);
},
LSRAbsoluteX => {
let b = self.absolute_x();
self.lsr(b);
},
NopImplied => { /* No operation 2 cycles */},
OraImmediate => {
self.reg_a = self.reg_a | self.immediate();
let a = self.reg_a;
self.sign_zero_flags(a);
},
OraZeroPage => {
self.reg_a = self.reg_a | self.zero_page();
let a = self.reg_a;
self.sign_zero_flags(a);
},
OraZeroPageX => {
self.reg_a = self.reg_a | self.zero_page_x();
let a = self.reg_a;
self.sign_zero_flags(a);
},
OraAbsolute => {
self.reg_a = self.reg_a | self.absolute();
let a = self.reg_a;
self.sign_zero_flags(a);
},
OraAbsoluteX => {
self.reg_a = self.reg_a | self.absolute_x();
let a = self.reg_a;
self.sign_zero_flags(a);
},
OraAbsoluteY => {
self.reg_a = self.reg_a | self.absolute_y();
let a = self.reg_a;
self.sign_zero_flags(a);
},
OraIndirectX => {
self.reg_a = self.reg_a | self.indirect_x();
let a = self.reg_a;
self.sign_zero_flags(a);
},
OraIndirectY => {
self.reg_a = self.reg_a | self.indirect_y();
let a = self.reg_a;
self.sign_zero_flags(a);
},
Pha => { //Push A onto Stack
let a = self.reg_a;
let addr = 0x0100 + (self.reg_sp as u16);
self.write_u8(addr,a);
self.reg_sp -= 1;
},
Php => { //Push P onto Stack
let p = ((self.reg_flag[SIGN] as u8) << 7) + ((self.reg_flag[OVERFLOW] as u8) << 6) + ((self.reg_flag[BREAK] as u8) << 4) + ((self.reg_flag[DECIMAL] as u8) << 3) + ((self.reg_flag[INTERRUPT] as u8) << 2) + ((self.reg_flag[ZERO] as u8) << 1) +(self.reg_flag[CARRY] as u8);
let addr = 0x0100 + (self.reg_sp as u16);
self.write_u8(addr,p);
self.reg_sp -= 1;
},
Pla => { //Pull from Stack to A
self.reg_sp += 1;
let addr = 0x0100 + (self.reg_sp as u16);
let a = self.read_u8(addr);
self.reg_a = a;
self.sign_zero_flags(a);
},
Plp => { //Pull from Stack to P
self.reg_sp += 1;
let addr = 0x0100 + (self.reg_sp as u16);
let p = self.read_u8(addr);
self.convert_to_sign_zero_flags(p);
},
RolAccumulator => {
let a = self.reg_a;
self.rol(a);
},
RolZeroPage => {
let b = self.zero_page();
self.rol(b);
},
RolZeroPageX => {
let b = self.zero_page_x();
self.rol(b);
},
RolAbsolute => {
let b = self.absolute();
self.rol(b);
},
RolAbsoluteX => {
let b = self.absolute_x();
self.rol(b);
},
Roraccumulator => {
let a = self.reg_a;
self.ror(a);
},
RorZeroPage => {
let b = self.zero_page();
self.ror(b);
},
RorZeroPageX => {
let b = self.zero_page_x();
self.ror(b);
},
RorAbsolute => {
let b = self.absolute();
self.ror(b);
},
RorAbsoluteX => {
let b = self.absolute_x();
self.ror(b);
},
Rti => { // Return from interrupt
self.reg_sp -= 1;
let addr_p = (self.reg_sp as u16) + 0x0100;
let p = self.read_u8(addr_p);
self.convert_to_sign_zero_flags(p);
self.reg_sp -= 1;
let addr_l = (self.reg_sp as u16) + 0x0100;
let l = self.read_u8(addr_l) as u16;
self.reg_sp -= 1;
let addr_h = (self.reg_sp as u16) + 0x0100;
let h = (self.read_u8(addr_h) as u16) << 8;
self.reg_pc = h | l;
},
Rts => { // Return from subroutine: Operation: PC from S, PC + 1 -> PC
self.reg_sp += 1;
let addr_l = (self.reg_sp as u16) + 0x0100;
let l = self.read_u8(addr_l) as u16;
self.reg_sp += 1;
let addr_h = (self.reg_sp as u16) + 0x0100;
let h = (self.read_u8(addr_h) as u16) << 8;
self.reg_pc = ( h | l ) + l;
},
SbcImmediate => {
let m = self.immediate();
self.sbc(m);
},
SbcZeroPage => {
let m = self.zero_page();
self.sbc(m);
},
SbcZeroPageX => {
let m = self.zero_page_x();
self.sbc(m);
},
SbcAbsolute => {
let m = self.absolute();
self.sbc(m);
},
SbcAbsoluteX => {
let m = self.absolute_x();
self.sbc(m);
},
SbcAbsoluteY => {
let m = self.absolute_y();
self.sbc(m);
},
SbcIndirectX => {
let m = self.indirect_x();
self.sbc(m);
},
SbcIndirectY => {
let m = self.indirect_y();
self.sbc(m);
},
StaZeroPage => {
let a = self.reg_a;
let addr = self.zero_page() as u16;
self.st_axy(addr,a);
},
StaZeroPageX => {
let a = self.reg_a;
let addr = self.zero_page_x() as u16;
self.st_axy(addr,a);
},
StaAbsolute => {
let a = self.reg_a;
let addr = self.absolute() as u16;
self.st_axy(addr,a);
},
StaAbsoluteX => {
let a = self.reg_a;
let addr = self.absolute_x() as u16;
self.st_axy(addr,a);
},
StaAbsoluteY => {
let a = self.reg_a;
let addr = self.absolute_y() as u16;
self.st_axy(addr,a);
},
StaIndirectX => {
let a = self.reg_a;
let addr = self.indirect_x() as u16;
self.st_axy(addr,a);
},
StaIndirectY => {
let a = self.reg_a;
let addr = self.indirect_y() as u16;
self.st_axy(addr,a);
},
StxZeroPage => {
let x = self.reg_x;
let addr = self.zero_page() as u16;
self.st_axy(addr,x);
},
StxZeroPageX => {
let x = self.reg_x;
let addr = self.zero_page_x() as u16;
self.st_axy(addr,x);
},
StxAbsolute => {
let x = self.reg_x;
let addr = self.absolute() as u16;
self.st_axy(addr,x);
},
StyZeroPage => {
let y = self.reg_y;
let addr = self.zero_page() as u16;
self.st_axy(addr,y);
},
StyZeroPageX => {
let y = self.reg_y;
let addr = self.zero_page_x() as u16;
self.st_axy(addr,y);
},
StyAbsolute => {
let y = self.reg_y;
let addr = self.absolute() as u16;
self.st_axy(addr,y);
},
Tax => {self.reg_x = self.reg_a;}, // Transfer Accumulator to index x
Tay => {self.reg_y = self.reg_a;}, // Transfer Accumulator to index y
Tsx => {self.reg_x = self.reg_sp;}, // Transfer Stack Pointer to index x
Txa => {self.reg_a = self.reg_x;}, // Transfer index X to accumulator
Txs => {self.reg_sp = self.reg_x;}, // Transfer index X to stack pointer
Tya => {self.reg_a = self.reg_y;}, // Transfer index Y to accumulator
}
}
fn immediate(&mut self) -> u8 {
let m = self.read_u8(self.reg_pc);
self.incr_pc(1);
m
}
fn zero_page(&mut self) -> u8 {
let _addr = self.read_u8(self.reg_pc); //Fetch the operand from the next byte
self.incr_pc(1); //Increment the PC
self.read_u8(_addr as u16) //Fetch the value of the address/operand
}
fn zero_page_x(&mut self) -> u8 {
let mut _addr = self.read_u8(self.reg_pc); //Fetch the operand from the next byte
self.incr_pc(1); //Increment the PC
_addr = (_addr + self.reg_x) & 0xFF; //Add the X register to the address and wrap around if address +X > 0xF
self.read_u8(_addr as u16)
}
fn absolute(&mut self) -> u8 {
let _addr = self.read_u16(self.reg_pc); // Fetch the next addr pointing anywhere in memory
self.incr_pc(2);
self.read_u8(_addr)
}
fn absolute_x(&mut self) -> u8 {
let mut addr = self.read_u16(self.reg_pc); // Fetch the next addr pointing anywhere in memory
let _addr = addr & 0x100;
self.incr_pc(2);
addr += self.reg_x as u16;
// Check if there is a page crossing
/*if (addr & 0x100) ^ _addr {
self.read_u8(addr);
}*/
self.read_u8(addr)
}
fn absolute_y(&mut self) -> u8 {
let mut addr = self.read_u16(self.reg_pc); // Fetch the next addr pointing anywhere in memory
let _addr = addr & 0x100;
self.incr_pc(2);
addr += self.reg_y as u16;
// Check if there is a page crossing
/*if (addr & 0x100) ^ _addr {
self.read_u8(addr);
}*/
self.read_u8(addr)
}
fn indirect_x(&mut self) -> u8 {
let addr = self.read_u8(self.reg_pc); // Fetch the pointer address from the next byte in the PC
let tmp = (addr + self.reg_x) & 0xFF;
let _addr = self.read_u16(tmp as u16);
self.incr_pc(1);
self.read_u8(_addr)
}
fn indirect_y(&mut self) -> u8 {
let mut _addr = self.read_u8(self.reg_pc); //u8
let mut _addr = _addr as u16;
let mut addr = self.read_u16(_addr); //u16
self.incr_pc(1);
_addr = addr & 0x100;
addr += self.reg_y as u16;
if (addr & 0x100) != _addr {
self.read_u8(addr);
}
self.read_u8(addr)
}
// Basic functions
fn adc(&mut self, m: u8){ // Add Memory to Accumulator with Carry: A + M + C -> A, C
let ret = self.reg_a + m + self.reg_flag[CARRY];
self.reg_flag[OVERFLOW] = (ret ^ self.reg_a) & (ret ^ m) & 0x80;
self.reg_flag[CARRY] = ret & 0x100; //>> 8;
self.reg_flag[ZERO] = ret & 0xFF;
self.reg_flag[SIGN] = ret & 0xFF;
self.reg_a = ret & 0xFF;
self.reg_flag[ZERO] = !self.reg_flag[ZERO];
}
fn and(&mut self, m: u8){
self.reg_a = self.reg_a & m;
self.reg_flag[SIGN] = if (self.reg_a & 0x80) == 0x80 { 1 } else { 0 };
self.reg_flag[ZERO] = if self.reg_a == 0x00 { 1 } else { 0 };
}
fn asl(&mut self, b: u8) {
self.reg_flag[CARRY]= if (b & 0x80) == 0x80 { 1 } else { 0 };
let b = (b << 1) & 0xFE;
self.reg_flag[SIGN] = if (b & 0x80) == 0x80 { 1 } else { 0 };
self.reg_flag[ZERO] = if b == 0x00 { 1 } else { 0 };
}
fn cmp(&mut self, m: u8, z: u8) {
let t = z - m;
self.reg_flag[SIGN] = if (t & 0x80) == 0x80 { 1 } else { 0 };
self.reg_flag[CARRY] = if z >= m { 1 } else { 0 };
self.reg_flag[ZERO] = if t == 0x00 { 1 } else { 0 };
}
fn eor(&mut self, m: u8){
self.reg_a = self.reg_a ^ m;
self.reg_flag[SIGN] = if (self.reg_a & 0x80) == 0x80 { 1 } else { 0 };
self.reg_flag[ZERO] = if self.reg_a == 0 { 1 } else { 0 };
}
fn sign_zero_flags(&mut self, l: u8){
self.reg_flag[SIGN] = if (l & 0x80) == 0x80 { 1 } else { 0 };
self.reg_flag[ZERO] = if l == 0x00 { 1 } else { 0 };
}
fn lsr(&mut self, b: u8){
self.reg_flag[SIGN] = 0;
self.reg_flag[CARRY] = if (b & 0x01) == 0x01 { 1 } else { 0 };
let b = (b >> 1) & 0x7F;
self.reg_flag[ZERO] = if b == 0x00 { 1 } else { 0 };
}
fn rol(&mut self,b : u8){
let t = if (b & 0x80) == 0x80 { 1 } else { 0 };
let b = (b << 1) & 0xFE;
self.reg_flag[CARRY] = t;
self.sign_zero_flags(b);
}
fn ror(&mut self, b: u8){
let t = if (b & 0x01) == 0x01 { 1 } else { 0 };
let b = (b >> 1) & 0x7F;
self.reg_flag[CARRY] = t;
self.sign_zero_flags(b);
}
fn sbc(&mut self, m: u8){
let not_pc = !self.reg_flag[CARRY];
let mut t;
if self.reg_flag[DECIMAL] == 1 {
t = self.reg_a - m - not_pc; // TODO: Binary Coded Decimal on a and m
} else{
t = self.reg_a - m - not_pc;
self.reg_flag[OVERFLOW] = if t > 127 { 1 } else { 0 }; // TODO: VERIFY ACCURACY OF THIS METHOD ( || t < (0 - 128) )
}
self.reg_flag[CARRY] = if t >= 0 { 1 } else { 0 };
self.reg_flag[SIGN] = if (t & 0x80) == 0x80 { 0 } else { 1 };
self.reg_flag[ZERO] = if t == 0 { 1 } else { 0 };
self.reg_a = t & 0xFF;
}
fn st_axy(&mut self, addr: u16, obj: u8){
self.write_u8(addr,obj);
}
fn incr_pc(&mut self,num: u8){
self.reg_pc += num as u16;
}
fn convert_to_sign_zero_flags(&mut self, p: u8){
self.reg_flag[SIGN] = if (p & 0x80) == 0x80 { 1 } else { 0 };
self.reg_flag[OVERFLOW] = if (p & 0x40) == 0x40 { 1 } else { 0 };
self.reg_flag[BREAK] = if (p & 0x10) == 0x10 { 1 } else { 0 };
self.reg_flag[DECIMAL] = if (p & 0x08) == 0x08 { 1 } else { 0 };
self.reg_flag[INTERRUPT]= if (p & 0x04) == 0x04 { 1 } else { 0 };
self.reg_flag[ZERO] = if (p & 0x02) == 0x02 { 1 } else { 0 };
self.reg_flag[CARRY] = if (p & 0x01) == 0x01 { 1 } else { 0 };
}
/*fn set_zero(&mut self){self.reg_flag[ZERO] = 1;}
fn clear_zero(&mut self){self.reg_flag[ZERO] = 0;}
fn set_sign(&mut self){self.reg_flag[SIGN] = 1;}
fn clear_sign(&mut self){self.reg_flag[SIGN] = 0;}
fn set_break(&mut self){self.reg_flag[BREAK] = 1;}
fn clear_break(&mut self){self.reg_flag[BREAK] = 0;}
fn set_overflow(&mut self){self.reg_flag[OVERFLOW] = 1;}*/
fn clear_overflow(&mut self){self.reg_flag[OVERFLOW] = 0;}
fn set_decimal(&mut self){self.reg_flag[DECIMAL] = 1;}
fn clear_decimal(&mut self){self.reg_flag[DECIMAL] = 0;}
fn set_interrupt(&mut self){self.reg_flag[INTERRUPT] = 1;}
fn clear_interrupt(&mut self){self.reg_flag[INTERRUPT] = 0;}
fn set_carry(&mut self){self.reg_flag[CARRY] = 1;}
fn clear_carry(&mut self){self.reg_flag[CARRY] = 0;}
pub fn run(&mut self) {
let mut x = 0;
loop {
if x == 10{ panic!("instructions Complete!");}
self.run_instruction();
x += 1;
}
}
}
|
#[path = "random_integer_1/returns_integer_between_0_inclusive_and_max_exclusive.rs"]
pub mod returns_integer_between_0_inclusive_and_max_exclusive;
use self::returns_integer_between_0_inclusive_and_max_exclusive::EXCLUSIVE_MAX;
use super::*;
#[wasm_bindgen_test]
async fn returns_integer_between_0_inclusive_and_max_exclusive() {
start_once();
let promise = r#async::apply_3::promise(
module(),
returns_integer_between_0_inclusive_and_max_exclusive::function(),
vec![],
Default::default(),
)
.unwrap();
let resolved = JsFuture::from(promise).await.unwrap();
assert!(
js_sys::Number::is_integer(&resolved),
"{:?} is not an integer",
resolved
);
let resolved_usize = resolved.as_f64().unwrap() as usize;
assert!(resolved_usize < EXCLUSIVE_MAX);
}
fn module() -> Atom {
Atom::from_str("Elixir.Lumen.Web.Math.RandomInteger1")
}
|
use nj_sys as sys;
use std::{ffi::CString, ptr};
#[cfg(windows)]
mod delayload;
#[no_mangle]
fn ctor() {
println!("Hello from wallet");
#[cfg(windows)]
delayload::process();
unsafe {
let modname = CString::new("wallet").unwrap();
let filename = CString::new("lib.rs").unwrap();
let module = sys::napi_module {
nm_version: sys::NAPI_VERSION as i32,
nm_flags: 0,
nm_filename: filename.as_ptr(),
nm_modname: modname.as_ptr(),
nm_register_func: Some(init),
nm_priv: ptr::null_mut(),
reserved: [
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
ptr::null_mut(),
],
};
let module = Box::leak(Box::new(module));
sys::napi_module_register(module);
}
}
#[no_mangle]
unsafe extern "C" fn init(env: sys::napi_env, exports: sys::napi_value) -> sys::napi_value {
println!("In init! exports = {:?}", exports);
let mut ret: sys::napi_value = ptr::null_mut();
sys::napi_create_object(env, &mut ret);
let mut s = ptr::null_mut();
let s_src = "Just yanking yer chain";
sys::napi_create_string_utf8(env, s_src.as_ptr() as *const i8, s_src.len(), &mut s);
s
}
#[used]
#[cfg_attr(target_os = "linux", link_section = ".ctors")]
#[cfg_attr(target_os = "macos", link_section = "__DATA,__mod_init_func")]
#[cfg_attr(target_os = "windows", link_section = ".CRT$XCU")]
pub static CTOR_ENTRY: extern "C" fn() = {
extern "C" fn ctor_thunk() {
ctor();
};
ctor_thunk
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.