text
stringlengths
8
4.13M
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::any::Any; use std::sync::Arc; use common_catalog::plan::DataSourcePlan; use common_catalog::plan::PartStatistics; use common_catalog::plan::Partitions; use common_catalog::plan::PushDownInfo; use common_catalog::table::Table; use common_catalog::table_args::TableArgs; use common_exception::ErrorCode; use common_exception::Result; use common_expression::types::BooleanType; use common_expression::types::NumberDataType; use common_expression::types::StringType; use common_expression::types::UInt64Type; use common_expression::DataBlock; use common_expression::FromData; use common_expression::TableDataType; use common_expression::TableField; use common_expression::TableSchema; use common_expression::TableSchemaRefExt; use common_meta_app::principal::StageFileFormatType; use common_meta_app::schema::TableIdent; use common_meta_app::schema::TableInfo; use common_meta_app::schema::TableMeta; use common_pipeline_core::processors::processor::ProcessorPtr; use common_pipeline_sources::AsyncSource; use common_pipeline_sources::AsyncSourcer; use common_sql::binder::parse_stage_location; use common_storage::init_stage_operator; use common_storage::read_parquet_schema_async; use common_storage::StageFilesInfo; use crate::pipelines::processors::port::OutputPort; use crate::pipelines::Pipeline; use crate::sessions::TableContext; use crate::table_functions::infer_schema::table_args::InferSchemaArgsParsed; use crate::table_functions::TableFunction; const INFER_SCHEMA: &str = "infer_schema"; pub struct InferSchemaTable { table_info: TableInfo, args_parsed: InferSchemaArgsParsed, table_args: TableArgs, } impl InferSchemaTable { pub fn create( database_name: &str, table_func_name: &str, table_id: u64, table_args: TableArgs, ) -> Result<Arc<dyn TableFunction>> { let args_parsed = InferSchemaArgsParsed::parse(&table_args)?; let table_info = TableInfo { ident: TableIdent::new(table_id, 0), desc: format!("'{}'.'{}'", database_name, table_func_name), name: table_func_name.to_string(), meta: TableMeta { schema: Self::schema(), engine: INFER_SCHEMA.to_owned(), ..Default::default() }, ..Default::default() }; Ok(Arc::new(Self { table_info, args_parsed, table_args, })) } pub fn schema() -> Arc<TableSchema> { TableSchemaRefExt::create(vec![ TableField::new("column_name", TableDataType::String), TableField::new("type", TableDataType::String), TableField::new("nullable", TableDataType::Boolean), TableField::new("order_id", TableDataType::Number(NumberDataType::UInt64)), ]) } } #[async_trait::async_trait] impl Table for InferSchemaTable { fn as_any(&self) -> &dyn Any { self } fn get_table_info(&self) -> &TableInfo { &self.table_info } async fn read_partitions( &self, _ctx: Arc<dyn TableContext>, _push_downs: Option<PushDownInfo>, ) -> Result<(PartStatistics, Partitions)> { Ok((PartStatistics::default(), Partitions::default())) } fn table_args(&self) -> Option<TableArgs> { Some(self.table_args.clone()) } fn read_data( &self, ctx: Arc<dyn TableContext>, _plan: &DataSourcePlan, pipeline: &mut Pipeline, ) -> Result<()> { pipeline.add_source( |output| InferSchemaSource::create(ctx.clone(), output, self.args_parsed.clone()), 1, )?; Ok(()) } } impl TableFunction for InferSchemaTable { fn function_name(&self) -> &str { self.name() } fn as_table<'a>(self: Arc<Self>) -> Arc<dyn Table + 'a> where Self: 'a { self } } struct InferSchemaSource { is_finished: bool, ctx: Arc<dyn TableContext>, args_parsed: InferSchemaArgsParsed, } impl InferSchemaSource { pub fn create( ctx: Arc<dyn TableContext>, output: Arc<OutputPort>, args_parsed: InferSchemaArgsParsed, ) -> Result<ProcessorPtr> { AsyncSourcer::create(ctx.clone(), output, InferSchemaSource { is_finished: false, ctx, args_parsed, }) } } #[async_trait::async_trait] impl AsyncSource for InferSchemaSource { const NAME: &'static str = INFER_SCHEMA; #[async_trait::unboxed_simple] async fn generate(&mut self) -> Result<Option<DataBlock>> { if self.is_finished { return Ok(None); } self.is_finished = true; let (stage_info, path) = parse_stage_location(&self.ctx, &self.args_parsed.location).await?; let files_info = StageFilesInfo { path, ..self.args_parsed.files_info.clone() }; let operator = init_stage_operator(&stage_info)?; let first_file = files_info.first_file(&operator).await?; let file_format_options = match &self.args_parsed.file_format { Some(f) => self.ctx.get_file_format(f).await?, None => stage_info.file_format_options.clone(), }; let schema = match file_format_options.format { StageFileFormatType::Parquet => { let arrow_schema = read_parquet_schema_async(&operator, &first_file.path).await?; TableSchema::from(&arrow_schema) } _ => { return Err(ErrorCode::BadArguments( "infer_schema is currently limited to format Parquet", )); } }; let mut names: Vec<Vec<u8>> = vec![]; let mut types: Vec<Vec<u8>> = vec![]; let mut nulls: Vec<bool> = vec![]; for field in schema.fields().iter() { names.push(field.name().to_string().as_bytes().to_vec()); let non_null_type = field.data_type().remove_recursive_nullable(); types.push(non_null_type.sql_name().as_bytes().to_vec()); nulls.push(field.is_nullable()); } let order_ids = (0..schema.fields().len() as u64).collect::<Vec<_>>(); let block = DataBlock::new_from_columns(vec![ StringType::from_data(names), StringType::from_data(types), BooleanType::from_data(nulls), UInt64Type::from_data(order_ids), ]); Ok(Some(block)) } }
extern crate clap; extern crate num_cpus; use clap::{App, Arg}; use std::collections::HashSet; use std::mem::swap; use std::net::{IpAddr, SocketAddr, TcpStream}; use std::process::exit; use std::time::Duration; fn main() { let matches = App::new("Ports Open") .version("1.0") .author("Langston Graham <langstongraham@gmail.com>") .about("Check the status of open ports at given ip for given range") .arg(Arg::with_name("ip") .help("The ip for port scan") .required(true) .index(1)) .arg(Arg::with_name("port_min") .help("The start port for the scan") .required(true) .index(2)) .arg(Arg::with_name("port_max") .help("The end port for the scan") .required(true) .index(3)) .get_matches(); let ip: IpAddr = matches.value_of("ip") .expect("Unable to gather ip") .parse::<IpAddr>() .expect("Unable to convert to IP address"); let mut port_min: u16 = matches.value_of("port_min") .expect("Unable to gather minimum port") .parse() .expect("Unable to interpret minimum port"); let mut port_max: u16 = matches.value_of("port_max") .expect("Unable to gather maximum port") .parse() .expect("Unable to interpert maximum port"); // Verify min and max in appropriate order for range if port_min > port_max { swap(&mut port_min, &mut port_max); } // Verify port values not too high let max_port_value: u16 = 65535; if port_min > max_port_value || port_max > max_port_value { eprintln!("Port min and max must be less than or equal to {}", max_port_value); exit(1); } println!("IP: {} Ports: {} - {}", ip, port_min, port_max); // Check number of threads available let total_threads = num_cpus::get(); println!("{} threads available", total_threads); // Set port check timeout let timeout = Duration::from_secs(1); let mut open_ports: HashSet<u16> = HashSet::new(); let mut closed_ports: HashSet<u16> = HashSet::new(); // Check each port in range for port in port_min..port_max { let addr = SocketAddr::from((ip, port)); // Attempt connection... if TcpStream::connect_timeout(&addr, timeout).is_ok() { // Connection succeeded, port is open open_ports.insert(port); } else { // Connection failed, port is closed closed_ports.insert(port); } } println!("Open Ports: {}", open_ports.len()); for port in open_ports { println!("\t{}", port); } println!("Closed Ports: {}", closed_ports.len()); }
#![no_main] #![feature(start)] extern crate olin; use log::info; use olin::entrypoint; entrypoint!(); fn fib(n: u64) -> u64 { if n <= 1 { return 1; } fib(n - 1) + fib(n - 2) } fn main() -> Result<(), std::io::Error> { info!("starting"); fib(30); info!("done"); Ok(()) }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq, Copy, Clone)] pub enum Status { // Created indicates "the runtime has finished the create operation and // the container process has neither exited nor executed the // user-specified program". Created = 0, // Creating indicates "the container is being created". Creating = 1, // Paused indicates that the process within the container has been // suspended. Paused = 2, // Running indicates "the container process has executed the // user-specified program but has not exited". Running = 3, // Stopped indicates "the container process has exited". Stopped = 4, } impl Default for Status { fn default() -> Status { Status::Created } } impl Status { pub fn String(&self) -> String { match self { Self::Created => "created".to_string(), Self::Creating => "creating".to_string(), Self::Paused => "pause".to_string(), Self::Running => "running".to_string(), Self::Stopped => "stopped".to_string(), } } }
use std::{collections::HashMap, convert::Infallible, sync::{Arc, Mutex}, thread}; use chrono::Utc; use tokio::{sync::mpsc}; use warp::{Filter, Rejection, Reply, fs::{ File, dir }, http::HeaderValue, hyper::{Body, HeaderMap, Response}, ws::{ Message, WebSocket }}; use futures::{FutureExt, StreamExt}; fn add_headers(reply: File)->Response<Body> { let mut res = reply.into_response(); let headers = res.headers_mut(); let header_map = create_headers(); headers.extend(header_map); res } fn create_headers() -> HeaderMap { let mut header_map = HeaderMap::new(); let now = Utc::now(); let now_str = now.format("%a, %d %h %Y %T GMT").to_string(); header_map.insert("Expires", HeaderValue::from_str(now_str.as_str()).unwrap()); header_map.insert("Server", HeaderValue::from_str("webview-app").unwrap()); header_map } type Result<T> = std::result::Result<T, Rejection>; type Session = mpsc::UnboundedSender<std::result::Result<Message, warp::Error>>; type Sessions = Arc<Mutex<HashMap<String, Session>>>; async fn client_connection(ws: WebSocket, id: String, sessions: Sessions) { let (client_ws_sender, _) = ws.split(); let (client_sender, client_rcv) = mpsc::unbounded_channel(); let client_rcv = tokio_stream::wrappers::UnboundedReceiverStream::new(client_rcv); tokio::task::spawn(client_rcv.forward(client_ws_sender).map(|result| { if let Err(e) = result { eprintln!("error sending websocket msg: {}", e); } })); sessions.lock().unwrap().insert(id.clone(), client_sender); println!("{} connected", id); } async fn on_connect(ws: warp::ws::Ws, id: String, sessions: Sessions) -> Result<impl Reply> { println!("on_connect: {}", id); Ok(ws.on_upgrade(move |socket| client_connection(socket, id, sessions))) // None => Err(warp::reject::not_found()), //} } #[tokio::main] async fn main() { let sessions: Sessions = Arc::new(Mutex::new(HashMap::new())); fn with_sessions(sessions: Sessions) -> impl Filter<Extract = (Sessions,), Error = Infallible> + Clone { warp::any().map(move || sessions.clone()) } let route_static = dir(".") .map(add_headers); async fn bm_test(sessions: Sessions)->std::result::Result<impl warp::Reply, warp::Rejection> { thread::spawn( move|| { std::thread::sleep(core::time::Duration::from_millis(5000)); println!("Sending to left ws"); if let Some(session) = sessions.lock().unwrap().get("left").cloned() { //tokio::time::sleep(core::time::Duration::from_millis(5000)).await; let _ = session.send(Ok(Message::text("Guten Abend"))); } }); Ok("passed".to_string()) } let route_test = warp::path("test") .and(warp::path::end()) .and(with_sessions(sessions.clone())) .and_then(bm_test); let route_ws = warp::path("ws") .and(warp::ws()) .and(warp::path::param()) .and(with_sessions(sessions.clone())) .and_then(on_connect); let routes = route_test .or(route_ws) .or(route_static); let port = 8080; println!("Warp started: https://localhost:{}", 8080); warp::serve(routes) .tls() .cert_path("src/cert.pem") .key_path("src/key.rsa") .run(([127,0,0,1], port)) .await; }
use shrev::{EventChannel, ReaderId}; use specs::prelude::{Read, Resources, System, Write}; use crate::app::viewport::Viewport; use crate::event::WindowEvent; pub struct ViewportSystem { reader: Option<ReaderId<WindowEvent>>, } impl ViewportSystem { pub fn new() -> Self { ViewportSystem { reader: None, } } } impl<'a> System<'a> for ViewportSystem { type SystemData = ( Read<'a, EventChannel<WindowEvent>>, Write<'a, Viewport>, ); fn run(&mut self, (events, mut viewport): Self::SystemData) { for event in events.read(&mut self.reader.as_mut().unwrap()) { match *event { WindowEvent::WindowResize(width, height) => { viewport.resize(width, height); }, } } } fn setup(&mut self, res: &mut Resources) { use specs::prelude::SystemData; Self::SystemData::setup(res); self.reader = Some(res.fetch_mut::<EventChannel<WindowEvent>>().register_reader()); info!("Setting up ViewportSystem"); } }
use std::convert::TryInto; use proptest::strategy::Just; use proptest::{prop_assert, prop_assert_eq}; use liblumen_alloc::erts::term::prelude::*; use crate::erlang::iolist_to_iovec_1::result; use crate::test::strategy::term::is_iolist_or_binary; use crate::test::with_process; #[test] fn with_iolist_or_binary_returns_iovec() { run!( |arc_process| { (Just(arc_process.clone()), is_iolist_or_binary(arc_process)) }, |(arc_process, iolist_or_binary)| { let result = result(&arc_process, iolist_or_binary); prop_assert!( result.is_ok(), "{} cannot be converted to a binary", iolist_or_binary ); let iovec = result.unwrap(); prop_assert!(iovec.is_list()); let iovec_cons: Boxed<Cons> = iovec.try_into().unwrap(); for iovec_result in iovec_cons.into_iter() { prop_assert!(iovec_result.is_ok()); let iovec_element = iovec_result.unwrap(); prop_assert!(iovec_element.is_binary()); } Ok(()) } ) } // See https://github.com/erlang/otp/blob/cf6cf5e5f82e348ecb9bb02d70027fc4961aee3d/erts/emulator/test/iovec_SUITE.erl#L106-L115 #[test] fn is_idempotent() { run!( |arc_process| { (Just(arc_process.clone()), is_iolist_or_binary(arc_process)) }, |(arc_process, iolist_or_binary)| { let first_result = result(&arc_process, iolist_or_binary); prop_assert!( first_result.is_ok(), "{} cannot be converted to a binary", iolist_or_binary ); let first = first_result.unwrap(); prop_assert_eq!(result(&arc_process, first), Ok(first)); Ok(()) } ) } #[test] fn with_binary_returns_binary_in_list() { with_process(|process| { let bin = process.binary_from_bytes(&[1, 2, 3]); assert_eq!( result(process, bin), Ok(process.list_from_slice(&[process.binary_from_bytes(&[1, 2, 3])])) ) }); } #[test] fn with_procbin_in_list_returns_list() { with_process(|process| { let bytes = [7; 65]; let procbin = process.binary_from_bytes(&bytes); // We expect this to be a procbin, since it's > 64 bytes. Make sure it is. assert!(procbin.is_boxed_procbin()); let iolist = process.list_from_slice(&[procbin]); assert_eq!( result(process, iolist), Ok(process.list_from_slice(&[process.binary_from_bytes(&bytes)])) ) }); } #[test] fn with_subbinary_in_list_returns_list() { with_process(|process| { let iolist = process.list_from_slice(&[process.subbinary_from_original( process.binary_from_bytes(&[1, 2, 3, 4, 5]), 1, 0, 3, 0, )]); assert_eq!( result(process, iolist), Ok(process.list_from_slice(&[process.binary_from_bytes(&[2, 3, 4])])) ) }); } #[test] fn with_subbinary_returns_list() { with_process(|process| { let iolist = process.subbinary_from_original( process.binary_from_bytes(&[1, 2, 3, 4, 5]), 1, 0, 3, 0, ); assert_eq!( result(process, iolist), Ok(process.list_from_slice(&[process.binary_from_bytes(&[2, 3, 4])])) ) }); } #[test] fn with_improper_list_smallint_tail_errors_badarg() { with_process(|process| { let tail = process.integer(42); let iolist_or_binary = process.improper_list_from_slice(&[process.binary_from_bytes(&[1, 2, 3])], tail); assert_badarg!( result(process, iolist_or_binary), format!( "iolist_or_binary ({}) tail ({}) cannot be a byte", iolist_or_binary, tail ) ) }); } // List elements must be smallint, binary, or lists thereof #[test] fn with_atom_in_iolist_errors_badarg() { with_process(|process| { let element = Atom::str_to_term("foo"); let iolist_or_binary = process.list_from_slice(&[element]); assert_badarg!( result(process, iolist_or_binary), format!( "iolist_or_binary ({}) element ({}) is not a byte, binary, or nested iolist", iolist_or_binary, element ) ) }); }
use anyhow::Result; use qapi::qga; use log::warn; use tokio::time::{timeout, Duration}; use clap::{Parser, ValueEnum}; use super::{GlobalArgs, QgaStream}; #[derive(Parser, Debug)] /// Tells the guest to initiate a system shutdown pub(crate) struct Shutdown { #[clap(short, long, value_enum, default_value_t = Mode::Powerdown)] mode: Mode, } impl Shutdown { pub async fn run(self, qga: QgaStream, _args: GlobalArgs) -> Result<i32> { let cmd = qga.execute(qga::guest_shutdown { mode: Some(self.mode.into()), }); match timeout(Duration::from_secs(1), cmd).await { Ok(res) => res.map(drop)?, Err(_) => warn!("Shutdown response timed out"), } Ok(0) } } #[derive(ValueEnum, Copy, Clone, Debug)] pub enum Mode { Powerdown, /// halt immediately Halt, Reboot, } impl Into<qga::GuestShutdownMode> for Mode { fn into(self) -> qga::GuestShutdownMode { match self { Mode::Reboot => qga::GuestShutdownMode::Reboot, Mode::Powerdown => qga::GuestShutdownMode::Powerdown, Mode::Halt => qga::GuestShutdownMode::Halt, } } }
use super::*; use proptest::strategy::Strategy; #[test] fn without_big_integer_returns_false() { run!( |arc_process| { ( strategy::term::integer::big(arc_process.clone()), strategy::term(arc_process.clone()) .prop_filter("Right must not be a big integer", |v| !v.is_boxed_bigint()), ) }, |(left, right)| { prop_assert_eq!(result(left, right), false.into()); Ok(()) }, ); } #[test] fn with_same_big_integer_returns_true() { run!( |arc_process| strategy::term::integer::big(arc_process.clone()), |operand| { prop_assert_eq!(result(operand, operand), true.into()); Ok(()) }, ); } #[test] fn with_different_big_integer_right_returns_false() { run!( |arc_process| { ( strategy::term::integer::big(arc_process.clone()), strategy::term::integer::big(arc_process.clone()), ) .prop_filter("Right and left must be different", |(left, right)| { left != right }) }, |(left, right)| { prop_assert_eq!(result(left, right), false.into()); Ok(()) }, ); }
use std::process::Command; pub static HALS: &[(&str, &str)] = &[ ("nrf51-hal", "thumbv6m-none-eabi"), ("nrf9160-hal", "thumbv8m.main-none-eabihf"), ("nrf52810-hal", "thumbv7em-none-eabi"), ("nrf52832-hal", "thumbv7em-none-eabihf"), ("nrf52833-hal", "thumbv7em-none-eabihf"), ("nrf52840-hal", "thumbv7em-none-eabihf"), ]; pub static EXAMPLES: &[(&str, &[&str])] = &[ ("ccm-demo", &["52810", "52832", "52833", "52840"]), ("comp-demo", &[]), ("ecb-demo", &["51", "52810", "52832", "52833", "52840"]), ("gpiote-demo", &[]), ("i2s-controller-demo", &[]), ("i2s-peripheral-demo", &[]), ("lpcomp-demo", &[]), ("ppi-demo", &["51", "52810", "52832", "52833", "52840"]), ("pwm-demo", &[]), ("qdec-demo", &[]), ("rtic-demo", &["51", "52810", "52832", "52840"]), ("spi-demo", &[]), ("twi-ssd1306", &["52832", "52840"]), ("twim-demo", &[]), ("twis-demo", &[]), ("wdt-demo", &[]), ]; pub fn feature_to_target(feat: &str) -> &str { match feat { "51" => "thumbv6m-none-eabi", "52810" => "thumbv7em-none-eabi", _ if feat.starts_with("52") => "thumbv7em-none-eabihf", _ => panic!("unknown Cargo feature `{}`", feat), } } pub fn install_targets() { let mut targets = HALS .iter() .map(|(_, target)| *target) .chain( EXAMPLES .iter() .flat_map(|(_, features)| features.iter().map(|feat| feature_to_target(feat))), ) .collect::<Vec<_>>(); targets.sort(); targets.dedup(); let mut cmd = Command::new("rustup"); cmd.args(&["target", "add"]).args(&targets); let status = cmd .status() .map_err(|e| format!("couldn't execute {:?}: {}", cmd, e)) .unwrap(); assert!( status.success(), "failed to install targets with rustup: {:?}", cmd ); }
use std::io; fn main() { loop { let mut items: Vec<i32> = Vec::new(); let c = get_items(&mut items); if c == 0 { break; } let max: i32 = items.iter().cloned().fold(0, i32::max); eprintln!("E: Max Val={}", max); let mut occs: Vec<u32> = vec![0; max as usize + 1]; eprintln!("E: Occs={:?}", occs); count_into(items, &mut occs); let max_index = get_max_index(&occs); let mut output: Vec<Vec<u32>> = Vec::new(); let total_rows = occs[max_index]; println!("{}", total_rows); for _ in 0..total_rows { output.push(Vec::new()); } let mut r: u32 = 0; let mut item_index: u32 = 1; for _ in 0..c { while occs[item_index as usize] == 0 { item_index += 1; } output[r as usize].push(item_index); occs[item_index as usize] -= 1; r = (r + 1) % total_rows; } print_output(output); } } fn print_output(output: Vec<Vec<u32>>) { eprintln!("E: Printing output={:?}", output); for v in output { print!("{}", v[0]); for i in 1..v.len() { print!(" {}", v[i]); } print!("\n"); } } fn count_into(items: Vec<i32>, occs: &mut Vec<u32>) { for x in items { occs[x as usize] += 1; } } fn get_max_index(occs: &Vec<u32>) -> usize { let mut max_index: usize = 0; for i in 1..occs.len() as usize { if occs[i] > occs[max_index] { max_index = i; } } max_index } fn get_items(items: &mut Vec<i32>) -> u32 { let mut buf = String::new(); let stdin = io::stdin(); stdin .read_line(&mut buf) .expect("Failed to read item count."); let count: u32 = buf.trim().to_string().parse().unwrap(); if count == 0 { return count; } while count as usize > items.len() { buf.clear(); stdin .read_line(&mut buf) .expect("Failed to read item list."); let mut line_items: Vec<i32> = buf .split_whitespace() .map(|num| num.parse().unwrap()) .collect(); items.append(&mut line_items); } count }
use std::fs; fn main() -> Result<(), Box<dyn std::error::Error>> { let config = tonic_build::configure().out_dir("src/proto"); let mut src = Vec::<&str>::new(); src.push("proto/cosmos/auth/v1beta1/auth.proto"); src.push("proto/cosmos/auth/v1beta1/genesis.proto"); src.push("proto/cosmos/auth/v1beta1/query.proto"); src.push("proto/cosmos/staking/v1beta1/staking.proto"); src.push("proto/cosmos/staking/v1beta1/genesis.proto"); src.push("proto/cosmos/staking/v1beta1/query.proto"); src.push("proto/cosmos/staking/v1beta1/tx.proto"); src.push("proto/cosmos/bank/v1beta1/bank.proto"); src.push("proto/cosmos/bank/v1beta1/genesis.proto"); src.push("proto/cosmos/bank/v1beta1/query.proto"); src.push("proto/cosmos/bank/v1beta1/tx.proto"); src.push("proto/cosmos/vesting/v1beta1/vesting.proto"); src.push("proto/cosmos/vesting/v1beta1/tx.proto"); src.push("proto/cosmos/tx/signing/v1beta1/signing.proto"); //src.push("proto/cosmos/tx/v1beta1/service.proto"); src.push("proto/cosmos/tx/v1beta1/tx.proto"); src.push("proto/cosmos/base/reflection/v1beta1/reflection.proto"); src.push("proto/cosmos/slashing/v1beta1/slashing.proto"); src.push("proto/cosmos/slashing/v1beta1/genesis.proto"); src.push("proto/cosmos/slashing/v1beta1/query.proto"); src.push("proto/cosmos/slashing/v1beta1/tx.proto"); src.push("proto/cosmos/distribution/v1beta1/distribution.proto"); src.push("proto/cosmos/distribution/v1beta1/genesis.proto"); src.push("proto/cosmos/distribution/v1beta1/query.proto"); src.push("proto/cosmos/distribution/v1beta1/tx.proto"); src.push("proto/cosmos/mint/v1beta1/genesis.proto"); src.push("proto/cosmos/mint/v1beta1/mint.proto"); src.push("proto/cosmos/mint/v1beta1/query.proto"); src.push("proto/cosmos/gov/v1beta1/gov.proto"); src.push("proto/cosmos/gov/v1beta1/genesis.proto"); src.push("proto/cosmos/gov/v1beta1/query.proto"); src.push("proto/cosmos/gov/v1beta1/tx.proto"); src.push("proto/cosmos/upgrade/v1beta1/upgrade.proto"); src.push("proto/cosmos/upgrade/v1beta1/query.proto"); src.push("proto/tendermint/types/types.proto"); src.push("proto/tendermint/types/validator.proto"); src.push("proto/tendermint/types/evidence.proto"); src.push("proto/tendermint/types/params.proto"); src.push("proto/tendermint/types/block.proto"); src.push("proto/tendermint/types/events.proto"); src.push("proto/tendermint/blockchain/types.proto"); src.push("proto/cosmos/mainservice.proto"); config.compile(&src[..],&["proto/"])?; /* fs::rename("src/proto/tendermint.types.rs", "src/proto/tendermint_types.rs"); fs::rename("src/proto/tendermint.version.rs", "src/proto/tendermint_version.rs"); fs::rename("src/proto/tendermint.blockchain.rs", "src/proto/tendermint_blockchain.rs"); fs::rename("src/proto/tendermint.crypto.rs", "src/proto/tendermint_crypto.rs"); fs::rename("src/proto/tendermint.abci.rs", "src/proto/tendermint_abci.rs"); fs::rename("src/proto/cosmos.bank.v1beta1.rs", "src/proto/cosmos_bank_v1beta1.rs"); fs::rename("src/proto/cosmos.auth.v1beta1.rs", "src/proto/cosmos_auth_v1beta1.rs"); fs::rename("src/proto/cosmos.staking.v1beta1.rs", "src/proto/cosmos_staking_v1beta1.rs"); fs::rename("src/proto/cosmos.slashing.v1beta1.rs", "src/proto/cosmos_slashing_v1beta1.rs"); fs::rename("src/proto/cosmos.tx.v1beta1.rs", "src/proto/cosmos_tx_v1beta1.rs"); fs::rename("src/proto/cosmos.tx.signing.v1beta1.rs", "src/proto/cosmos_tx_signing_v1beta1.rs"); fs::rename("src/proto/cosmos.gov.v1beta1.rs", "src/proto/cosmos_gov_v1beta1.rs"); fs::rename("src/proto/cosmos.mint.v1beta1.rs", "src/proto/cosmos_mint_v1beta1.rs"); fs::rename("src/proto/cosmos.upgrade.v1beta1.rs", "src/proto/cosmos_upgrade_v1beta1.rs"); fs::rename("src/proto/cosmos.vesting.v1beta1.rs", "src/proto/cosmos_vesting_v1beta1.rs"); fs::rename("src/proto/cosmos.distribution.v1beta1.rs", "src/proto/cosmos_distribution_v1beta1.rs"); */ Ok(()) }
use super::util; use super::writer::Writer; use crate::MkvId; #[derive(Debug, Copy, Clone)] pub enum ProjectionType { kTypeNotPresent = -1, kRectangular = 0, kEquirectangular = 1, kCubeMap = 2, kMesh = 3, } pub struct Projection { type_: ProjectionType, pose_yaw_: f32, pose_pitch_: f32, pose_roll_: f32, private_data_: Vec<u8>, } impl Projection { const kValueNotPresent: u64 = std::u64::MAX; pub fn new() -> Projection { Projection { type_: ProjectionType::kRectangular, pose_yaw_: 0.0, pose_pitch_: 0.0, pose_roll_: 0.0, private_data_: Vec::new(), } } pub fn project_type(&self) -> ProjectionType { self.type_ } pub fn set_type(&mut self, t: ProjectionType) { self.type_ = t; } pub fn pose_yaw(&self) -> f32 { self.pose_yaw_ } pub fn set_pose_yaw(&mut self, pose_yaw: f32) { self.pose_yaw_ = pose_yaw; } pub fn pose_pitch(&self) -> f32 { self.pose_pitch_ } pub fn set_pose_pitch(&mut self, pose_pitch: f32) { self.pose_pitch_ = pose_pitch; } pub fn pose_roll(&self) -> f32 { self.pose_roll_ } pub fn set_pose_roll(&mut self, pose_roll: f32) { self.pose_roll_ = pose_roll; } pub fn private_data(&self) -> &[u8] { &self.private_data_ } pub fn set_private_data(&mut self, data: &[u8]) { self.private_data_ = data.to_vec(); } pub fn Size(&self) -> u64 { let mut size = self.PayloadSize(); if size > 0 { size += util::EbmlMasterElementSize(MkvId::MkvProjection, size); } size } pub fn PayloadSize(&self) -> u64 { let mut size = util::EbmlElementSizeArgU64(MkvId::MkvProjection, self.type_ as u64); if self.private_data_.len() > 0 { size += util::EbmlElementSizeArgSlice(MkvId::MkvProjectionPrivate, &self.private_data_); } size += util::EbmlElementSizeArgF32(MkvId::MkvProjectionPoseYaw, self.pose_yaw_); size += util::EbmlElementSizeArgF32(MkvId::MkvProjectionPosePitch, self.pose_pitch_); size += util::EbmlElementSizeArgF32(MkvId::MkvProjectionPoseRoll, self.pose_roll_); size } pub fn Write(&self, writer: &mut dyn Writer) -> bool { let size = self.PayloadSize(); // Don't write an empty element. if size == 0 { return true; } if !util::WriteEbmlMasterElement(writer, MkvId::MkvProjection, size) { return false; } if !util::WriteEbmlElementArgU64(writer, MkvId::MkvProjectionType, self.type_ as u64) { return false; } if self.private_data_.len() > 0 && !util::WriteEbmlElementArgSlice( writer, MkvId::MkvProjectionPrivate, &self.private_data_, ) { return false; } if !util::WriteEbmlElementArgF32(writer, MkvId::MkvProjectionPoseYaw, self.pose_yaw_) { return false; } if !util::WriteEbmlElementArgF32(writer, MkvId::MkvProjectionPosePitch, self.pose_pitch_) { return false; } if !util::WriteEbmlElementArgF32(writer, MkvId::MkvProjectionPoseRoll, self.pose_roll_) { return false; } true } }
use actix_web::actix::Message; use chrono::{NaiveDateTime, Utc}; use crate::model::member::Member; use crate::model::response::MyError; use crate::model::user::User; use crate::share::schema::projects; use diesel::{Identifiable, Insertable, Queryable}; use serde_derive::{Deserialize, Serialize}; use uuid::Uuid; #[derive(Serialize, Deserialize, Queryable, Identifiable, Clone, Debug)] pub struct Project { pub id: Uuid, pub name: String, pub archived: bool, pub created_at: NaiveDateTime, } #[derive(Serialize, Deserialize, Debug, Clone, Insertable)] #[table_name = "projects"] pub struct NewProject<'a> { pub id: Uuid, pub name: &'a str, pub archived: bool, pub created_at: NaiveDateTime, } #[derive(Serialize, Deserialize, Debug)] pub struct CreateProject { pub name: String, pub user: User, } impl Message for CreateProject { type Result = Result<Project, MyError>; } #[derive(Debug, Serialize, Deserialize)] pub struct ProjectById { pub project_id: String, } impl Message for ProjectById { type Result = Result<Project, MyError>; } #[derive(Debug, Serialize, Deserialize)] pub struct ProjectMembers { pub project: Project, } impl Message for ProjectMembers { type Result = Result<Vec<Member>, MyError>; } impl Project { pub fn new() -> Project { Project { id: Uuid::new_v4(), name: "".to_string(), archived: false, created_at: Utc::now().naive_utc(), } } }
extern crate serde_json; use std::any::Any; use std::iter::Map; use std::time::SystemTime; use chrono::Local; use serde::{Deserialize, Serialize}; use serde_json::json; use serde_json::Value; use crate::utils::time_util; pub fn eval(left: &Value, right: &Value, op: &str) -> Result<Value, rbatis_core::Error> { if op == "&&" { return Result::Ok(Value::Bool(left.as_bool().unwrap() && right.as_bool().unwrap())); } if op == "||" { return Result::Ok(Value::Bool(left.as_bool().unwrap() || right.as_bool().unwrap())); } if op == "==" { return Result::Ok(Value::Bool(eq(left, right))); } if op == "!=" { return Result::Ok(Value::Bool(!eq(left, right))); } if op == ">=" { let booll = left.is_number(); let boolr = right.is_number(); if booll && boolr { return Result::Ok(Value::Bool(left.as_f64() >= right.as_f64())); } } if op == "<=" { let booll = left.is_number(); let boolr = right.is_number(); if booll && boolr { return Result::Ok(Value::Bool(left.as_f64() <= right.as_f64())); } } if op == ">" { let booll = left.is_number(); let boolr = right.is_number(); if booll && boolr { return Result::Ok(Value::Bool(left.as_f64() > right.as_f64())); } } if op == "<" { let booll = left.is_number(); let boolr = right.is_number(); if booll && boolr { return Result::Ok(Value::Bool(left.as_f64() < right.as_f64())); } } if op == "+" { if left.is_number() && right.is_number() { return Result::Ok(Value::Number(serde_json::Number::from_f64(left.as_f64().unwrap() + right.as_f64().unwrap()).unwrap())); } else if left.is_string() && right.is_string() { return Result::Ok(Value::from(left.as_str().unwrap().to_owned() + right.as_str().unwrap())); } else { return Result::Err(rbatis_core::Error::from("[rbatis] un support diffrent type '+' opt")); } } if op == "-" { let booll = left.is_number(); let boolr = right.is_number(); if booll && boolr { return Result::Ok(Value::Number(serde_json::Number::from_f64(left.as_f64().unwrap() - right.as_f64().unwrap()).unwrap())); } } if op == "*" { let booll = left.is_number(); let boolr = right.is_number(); if booll && boolr { return Result::Ok(Value::Number(serde_json::Number::from_f64(left.as_f64().unwrap() * right.as_f64().unwrap()).unwrap())); } } if op == "/" { let booll = left.is_number(); let boolr = right.is_number(); if booll && boolr { return Result::Ok(Value::Number(serde_json::Number::from_f64(left.as_f64().unwrap() / right.as_f64().unwrap()).unwrap())); } } return Result::Err(rbatis_core::Error::from("[rbatis] un support opt = ".to_owned() + op)); } fn eq(left: &Value, right: &Value) -> bool { if left.is_null() && right.is_null() {// all null return true; } else if left.is_null() || right.is_null() {// on null return false; } else if left.is_number() && right.is_number() { return left.as_f64() == right.as_f64(); } else if left.is_string() && right.is_string() { return left.as_str().unwrap().eq(right.as_str().unwrap()); } else if left.is_boolean() && right.is_boolean() { return left.as_bool() == right.as_bool(); } else { return false; } } #[test] fn test_parser() { let john = json!({ "name": "John Doe", "age": Value::Null, "phones": [ "+44 1234567", "+44 2345678" ] }); let age = &john["age"]; println!("{}", *age); } #[derive(Serialize, Deserialize, Debug)] struct Point { x: i32, y: i32, } #[test] fn test_take_value() { let point = Point { x: 1, y: 2 }; let serialized = serde_json::to_string(&point).unwrap(); println!("serialized = {}", serialized); //create serde_json::Value let john = json!(point); println!("{}", john["x"]); let deserialized: Point = serde_json::from_str(&serialized).unwrap(); println!("deserialized = {:?}", deserialized); } #[test] fn benchmark_fromstr() { let point = Point { x: 1, y: 2 }; let serialized = serde_json::to_string(&point).unwrap(); println!("serialized = {}", serialized); let total = 100000; let now = SystemTime::now(); for i in 0..total { let deserialized: Point = serde_json::from_str(&serialized).unwrap(); // println!("deserialized = {:?}", deserialized); } time_util::count_time_qps("benchmark_fromstr", total, now); } #[test] fn benchmark_to_string() { let point = Point { x: 1, y: 2 }; let total = 100000; let now = SystemTime::now(); for i in 0..total { let serialized = serde_json::to_string(&point).unwrap(); let deserialized: Value = serde_json::from_str(&serialized).unwrap(); } time_util::count_time_qps("benchmark_to_string", total, now); }
use nvml_wrapper::NVML; use procinfo::pid; use std::env; use std::process; use std::sync::atomic; use std::sync::Arc; use std::sync::Mutex; use std::thread; use std::time; fn get_parents(pid: u32) -> Vec<u32> { let stat = pid::stat(pid as i32); match stat { Ok(s) => match s.ppid { 0 => vec![], 1 => vec![], p => { if p == pid as i32 { vec![] } else { let mut result = vec![s.ppid as u32]; result.extend_from_slice(&get_parents(s.ppid as u32)); result } } }, _ => vec![], } } fn main() { let args: Vec<String> = env::args().collect(); eprintln!("GPULoad monitoring, revision {}", env!("VERGEN_SHA_SHORT")); if args.len() < 2 { eprintln!("Syntax : {} child_process child_args...", args[0]); std::process::exit(1); } let nvml = NVML::init().unwrap(); let dc = nvml.device_count().unwrap(); eprintln!("{} gpus found", dc); let pid = process::id(); let stats2 = Arc::new(Mutex::new(vec![0.0; 2 * dc as usize])); let nbsamples2 = Arc::new(Mutex::new(vec![0.0; 2 * dc as usize])); let mut process = subprocess::Exec::cmd(args[1].clone()) .args(&args[2..]) .popen() .unwrap(); let process_id = process.pid().unwrap(); let started2 = Arc::new(atomic::AtomicBool::new(false)); let finished2 = Arc::new(atomic::AtomicBool::new(false)); let started = Arc::clone(&started2); let finished = Arc::clone(&finished2); let stats = Arc::clone(&stats2); let nbsamples = Arc::clone(&nbsamples2); let t = thread::spawn(move || { while !finished.load(atomic::Ordering::Relaxed) { let mut found = false; for gpu_id in 0..dc { let device = nvml.device_by_index(gpu_id).unwrap(); let mut acc_mem_used: u64 = 0; let processes = device.running_compute_processes().unwrap(); let urate = device.utilization_rates().unwrap(); let mut old = stats.lock().unwrap(); let mut nbs = nbsamples.lock().unwrap(); for p in processes { let parents = get_parents(p.pid); if parents.contains(&pid) { let already_started = started.swap(true, atomic::Ordering::Relaxed); if !already_started { eprintln!("GPULoad started"); } } if started.load(atomic::Ordering::Relaxed) && parents.contains(&pid) { found = true; acc_mem_used += match p.used_gpu_memory { nvml_wrapper::enums::device::UsedGpuMemory::Used(t) => t, _ => 0, }; old[gpu_id as usize] += urate.gpu as f32; nbs[gpu_id as usize] += 1.0; } } old[dc as usize + gpu_id as usize] += acc_mem_used as f32; drop(old); } if started.load(atomic::Ordering::Relaxed) && !found { finished.swap(true, atomic::Ordering::Relaxed); } else { thread::sleep(time::Duration::from_millis(1000)); } } eprintln!("GPULoad finished"); }); ctrlc::set_handler(move || { unsafe { libc::kill(process_id as i32, libc::SIGINT) }; }) .expect("Cannot set SIGINT handler"); process.wait().unwrap(); finished2.swap(true, atomic::Ordering::Relaxed); t.join().unwrap(); for gpu_id in 0..dc { let s = stats2.lock().unwrap(); let nbs = nbsamples2.lock().unwrap(); let mut nbs = nbs[gpu_id as usize]; if nbs == 0.0 { nbs = 1.0 }; eprintln!( "GPULoad gpu {} kernel time use {:.2} % memory used {:.0} bytes", gpu_id, s[gpu_id as usize] / nbs, s[gpu_id as usize + dc as usize] / nbs ); } }
#![deny(missing_docs)] //! //! Bitcoind //! //! Utility to run a regtest bitcoind process, useful in integration testing environment //! //! ```no_run //! use bitcoincore_rpc::RpcApi; //! let bitcoind = bitcoind::BitcoinD::new("/usr/local/bin/bitcoind").unwrap(); //! assert_eq!(0, bitcoind.client.get_blockchain_info().unwrap().blocks); //! ``` use crate::bitcoincore_rpc::jsonrpc::serde_json::Value; use bitcoincore_rpc::{Auth, Client, RpcApi}; use log::debug; use std::ffi::OsStr; use std::net::{Ipv4Addr, SocketAddrV4, TcpListener}; use std::path::PathBuf; use std::process::{Child, Command, ExitStatus, Stdio}; use std::thread; use std::time::Duration; use tempfile::TempDir; pub extern crate bitcoincore_rpc; pub extern crate tempfile; /// Struct representing the bitcoind process with related information pub struct BitcoinD { /// Process child handle, used to terminate the process when this struct is dropped process: Child, /// Rpc client linked to this bitcoind process pub client: Client, /// Work directory, where the node store blocks and other stuff. It is kept in the struct so that /// directory is deleted only when this struct is dropped _work_dir: TempDir, /// Contains information to connect to this node pub params: ConnectParams, } #[derive(Debug, Clone)] /// Contains all the information to connect to this node pub struct ConnectParams { /// Path to the node datadir pub datadir: PathBuf, /// Path to the node cookie file, useful for other client to connect to the node pub cookie_file: PathBuf, /// Url of the rpc of the node, useful for other client to connect to the node pub rpc_socket: SocketAddrV4, /// p2p connection url, is some if the node started with p2p enabled pub p2p_socket: Option<SocketAddrV4>, } /// Enum to specify p2p settings pub enum P2P { /// the node doesn't open a p2p port and work in standalone mode No, /// the node open a p2p port Yes, /// The node open a p2p port and also connects to the url given as parameter, it's handy to /// initialize this with [BitcoinD::p2p_connect] of another node. Connect(SocketAddrV4), } /// All the possible error in this crate #[derive(Debug)] pub enum Error { /// Wrapper of io Error Io(std::io::Error), /// Wrapper of bitcoincore_rpc Error Rpc(bitcoincore_rpc::Error), } const LOCAL_IP: Ipv4Addr = Ipv4Addr::new(127, 0, 0, 1); /// The node configuration parameters, implements a convenient [Default] for most common use. /// /// Default values: /// ```no_run /// bitcoind::Conf { /// args: vec!["-regtest", "-fallbackfee=0.0001"], /// view_stdout: false, /// p2p: bitcoind::P2P::No, /// network: "regtest", /// }; /// ``` pub struct Conf<'a> { /// Bitcoind command line arguments containing no spaces like `vec!["-dbcache=300", "-regtest"]` /// note that `port`, `rpcport`, `connect`, `datadir`, `listen` cannot be used cause they are /// automatically initialized. pub args: Vec<&'a str>, /// if `true` bitcoind log output will not be suppressed pub view_stdout: bool, /// Allows to specify options to open p2p port or connect to the another node pub p2p: P2P, /// Must match what specified in args without dashes, needed to locate the cookie file /// directory with different/esoteric networks pub network: &'a str, } impl Default for Conf<'_> { fn default() -> Self { Conf { args: vec!["-regtest", "-fallbackfee=0.0001"], view_stdout: false, p2p: P2P::No, network: "regtest", } } } impl BitcoinD { /// Launch the bitcoind process from the given `exe` executable with default args. /// /// Waits for the node to be ready to accept connections before returning pub fn new<S: AsRef<OsStr>>(exe: S) -> Result<BitcoinD, Error> { BitcoinD::with_conf(exe, &Conf::default()) } /// Launch the bitcoind process from the given `exe` executable with given [Conf] param pub fn with_conf<S: AsRef<OsStr>>(exe: S, conf: &Conf) -> Result<BitcoinD, Error> { let _work_dir = TempDir::new()?; let datadir = _work_dir.path().to_path_buf(); let cookie_file = datadir.join(conf.network).join(".cookie"); let rpc_port = get_available_port()?; let rpc_socket = SocketAddrV4::new(LOCAL_IP, rpc_port); let rpc_url = format!("http://{}", rpc_socket); let (p2p_args, p2p_socket) = match conf.p2p { P2P::No => (vec!["-listen=0".to_string()], None), P2P::Yes => { let p2p_port = get_available_port()?; let p2p_socket = SocketAddrV4::new(LOCAL_IP, p2p_port); let p2p_arg = format!("-port={}", p2p_port); let args = vec![p2p_arg]; (args, Some(p2p_socket)) } P2P::Connect(other_node_url) => { let p2p_port = get_available_port()?; let p2p_socket = SocketAddrV4::new(LOCAL_IP, p2p_port); let p2p_arg = format!("-port={}", p2p_port); let connect = format!("-connect={}", other_node_url); let args = vec![p2p_arg, connect]; (args, Some(p2p_socket)) } }; let stdout = if conf.view_stdout { Stdio::inherit() } else { Stdio::null() }; let datadir_arg = format!("-datadir={}", datadir.display()); let rpc_arg = format!("-rpcport={}", rpc_port); let default_args = [&datadir_arg, &rpc_arg]; debug!( "launching {:?} with args: {:?} {:?} AND custom args", exe.as_ref(), default_args, p2p_args ); let process = Command::new(exe) .args(&default_args) .args(&p2p_args) .args(&conf.args) .stdout(stdout) .spawn()?; let node_url_default = format!("{}/wallet/default", rpc_url); // wait bitcoind is ready, use default wallet let client = loop { thread::sleep(Duration::from_millis(500)); assert!(process.stderr.is_none()); let client_result = Client::new(rpc_url.clone(), Auth::CookieFile(cookie_file.clone())); if let Ok(client_base) = client_result { // RpcApi has get_blockchain_info method, however being generic with `Value` allows // to be compatible with different version, in the end we are only interested if // the call is succesfull not in the returned value. if client_base.call::<Value>("getblockchaininfo", &[]).is_ok() { client_base .create_wallet("default", None, None, None, None) .unwrap(); break Client::new(node_url_default, Auth::CookieFile(cookie_file.clone())) .unwrap(); } } }; Ok(BitcoinD { process, client, _work_dir, params: ConnectParams { datadir, cookie_file, rpc_socket, p2p_socket, }, }) } /// Returns the rpc URL including the schema eg. http://127.0.0.1:44842 pub fn rpc_url(&self) -> String { format!("http://{}", self.params.rpc_socket) } /// Returns the [P2P] enum to connect to this node p2p port pub fn p2p_connect(&self) -> Option<P2P> { self.params.p2p_socket.map(P2P::Connect) } /// Stop the node, waiting correct process termination pub fn stop(&mut self) -> Result<ExitStatus, Error> { self.client.stop()?; Ok(self.process.wait()?) } } impl Drop for BitcoinD { fn drop(&mut self) { let _ = self.process.kill(); } } /// Returns a non-used local port if available. /// /// Note there is a race condition during the time the method check availability and the caller pub fn get_available_port() -> Result<u16, Error> { // using 0 as port let the system assign a port available let t = TcpListener::bind(("127.0.0.1", 0))?; // 0 means the OS choose a free port Ok(t.local_addr().map(|s| s.port())?) } impl From<std::io::Error> for Error { fn from(e: std::io::Error) -> Self { Error::Io(e) } } impl From<bitcoincore_rpc::Error> for Error { fn from(e: bitcoincore_rpc::Error) -> Self { Error::Rpc(e) } } #[cfg(test)] mod test { use crate::{get_available_port, BitcoinD, Conf, LOCAL_IP, P2P}; use bitcoincore_rpc::jsonrpc::serde_json::Value; use bitcoincore_rpc::RpcApi; use std::collections::HashMap; use std::env; use std::net::SocketAddrV4; #[test] fn test_local_ip() { assert_eq!("127.0.0.1", format!("{}", LOCAL_IP)); let port = get_available_port().unwrap(); let socket = SocketAddrV4::new(LOCAL_IP, port); assert_eq!(format!("127.0.0.1:{}", port), format!("{}", socket)); } #[test] fn test_default() { let conf = Conf { p2p: P2P::Yes, ..Default::default() }; assert_eq!("regtest", conf.network); } #[test] fn test_bitcoind() { let exe = init(); let bitcoind = BitcoinD::new(exe).unwrap(); let info = bitcoind.client.get_blockchain_info().unwrap(); assert_eq!(0, info.blocks); let address = bitcoind.client.get_new_address(None, None).unwrap(); let _ = bitcoind.client.generate_to_address(1, &address).unwrap(); let info = bitcoind.client.get_blockchain_info().unwrap(); assert_eq!(1, info.blocks); } #[test] fn test_getindexinfo() { let exe = init(); let mut conf = Conf::default(); conf.args.push("-txindex"); let bitcoind = BitcoinD::with_conf(&exe, &conf).unwrap(); assert!( bitcoind.client.version().unwrap() >= 210_000, "getindexinfo requires bitcoin >0.21" ); let info: HashMap<String, Value> = bitcoind.client.call("getindexinfo", &[]).unwrap(); assert!(info.contains_key("txindex")); assert_eq!(bitcoind.client.version().unwrap(), 210_000); } #[test] fn test_p2p() { let exe = init(); let conf = Conf { p2p: P2P::Yes, ..Default::default() }; let bitcoind = BitcoinD::with_conf(&exe, &conf).unwrap(); assert_eq!(bitcoind.client.get_peer_info().unwrap().len(), 0); let other_conf = Conf { p2p: bitcoind.p2p_connect().unwrap(), ..Default::default() }; let other_bitcoind = BitcoinD::with_conf(&exe, &other_conf).unwrap(); assert_eq!(bitcoind.client.get_peer_info().unwrap().len(), 1); assert_eq!(other_bitcoind.client.get_peer_info().unwrap().len(), 1); } fn init() -> String { let _ = env_logger::try_init(); env::var("BITCOIND_EXE").expect("BITCOIND_EXE env var must be set") } }
use serde::{Serialize, Deserialize}; #[derive(Serialize, Deserialize, Debug)] pub struct MeshData { pub mesh_name: String, pub texture: String, pub vertices: Vec<Vertex>, #[serde(default)] lines: Vec<Line>, #[serde(default)] pub triangles: Vec<Triangle>, #[serde(default)] quads: Vec<Quad>, } #[repr(C)] #[derive(Serialize, Deserialize, Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct Vertex { pub x: f32, pub y: f32, pub u: f32, pub v: f32, } #[derive(Serialize, Deserialize, Debug)] pub struct Line { v1: u32, v2: u32, } #[repr(C)] #[derive(Serialize, Deserialize, Copy, Clone, Debug, bytemuck::Pod, bytemuck::Zeroable)] pub struct Triangle { v1: u32, v2: u32, v3: u32, } #[derive(Serialize, Deserialize, Debug)] pub struct Quad { v1: u32, v2: u32, v3: u32, v4: u32, }
pub struct Solution; impl Solution { pub fn min_cut(s: String) -> i32 { let bytes = s.as_bytes(); let n = bytes.len(); let mut ends = vec![Vec::new(); n]; for i in 0..2 * n - 1 { let mut j = (i + 1) / 2; while j <= i && j < n && bytes[i - j] == bytes[j] { ends[i - j].push(j + 1); j += 1; } } let mut d = vec![std::i32::MAX; n + 1]; d[0] = 0; for i in 0..n { for &j in &ends[i] { d[j] = d[j].min(d[i] + 1); } } d[n] - 1 } } #[test] fn test0132() { assert_eq!(Solution::min_cut("aab".to_string()), 1); }
#[doc = "Reader of register DSI_VHBPCCR"] pub type R = crate::R<u32, super::DSI_VHBPCCR>; #[doc = "Reader of field `HBP`"] pub type HBP_R = crate::R<u16, u16>; impl R { #[doc = "Bits 0:11 - Horizontal Back-Porch duration"] #[inline(always)] pub fn hbp(&self) -> HBP_R { HBP_R::new((self.bits & 0x0fff) as u16) } }
use std::env; use std::ffi::OsStr; use std::path::Path; use std::process::exit; use colored::*; use log::*; use pretty_env_logger; use ext::rust::PathExt; mod app; mod ext; mod localstack; mod stack; #[tokio::main] pub async fn main() { pretty_env_logger::init(); env::set_var("AWS_PAGER", ""); env::set_var("RUST_LOG", "info"); let stackfile: String; let args = app::match_args(); match args.value_of("stackfile") { Some(f) => { if Path::new(&f).does_not_exist() { error!("stackfile '{}' does not exit", f.yellow()); exit(1) } stackfile = String::from(f); } None => { let mut stackfiles_found = stack::find("", "."); if stackfiles_found.len() > 1 { error!( "{}", "more than one stackfile was found in the current directory".red() ); for file in stackfiles_found.iter() { info!("found {}", file.yellow()); } exit(1); } stackfile = match stackfiles_found.pop() { Some(f) => f, _ => { error!( "{}", "stackfile does not exist in the current working directory".red() ); exit(1) } }; } }; let stack_format = match Path::new(&stackfile).extension().and_then(OsStr::to_str) { Some(ext) => ext, _ => "", }; let stack = match stack::parser::parse(&stackfile, &stack_format) { Some(stack) => stack, None => exit(1), }; match stack::up(stack).await { Ok(_) => {} Err(err) => error!("{}", err), } }
use bitcoin::BitcoinHash; use bitcoin::util::hash::Sha256dHash; use c_bitcoin::CRgbOutPoint; use contract::CRgbContract; use CRgbNeededTx; use generics::WrapperOf; use rgb::contract::Contract; use rgb::proof::OutputEntry; use rgb::proof::Proof; use rgb::traits::Verify; use std::mem; use std::os::raw::c_uchar; use std::ptr; use std::slice; #[derive(Debug)] #[repr(C)] pub struct CRgbOutputEntry { pub asset_id: Sha256dHash, pub amount: u32, pub vout: u32, } impl WrapperOf<OutputEntry> for CRgbOutputEntry { fn decode(&self) -> OutputEntry { OutputEntry::new(self.asset_id.clone(), self.amount, self.vout) } fn encode(native: &OutputEntry) -> Self { CRgbOutputEntry { asset_id: native.get_asset_id(), amount: native.get_amount(), vout: native.get_vout(), } } } #[derive(Debug)] #[repr(C)] pub struct CRgbProof { pub bind_to_count: u32, pub bind_to: *mut CRgbOutPoint, pub input_count: u32, pub input: *mut CRgbProof, pub output_count: u32, pub output: *mut CRgbOutputEntry, pub contract: *mut CRgbContract, } impl WrapperOf<Proof> for CRgbProof { fn decode(&self) -> Proof { let bind_to_vec = unsafe { slice::from_raw_parts(self.bind_to, self.bind_to_count as usize) .iter() .map(|ref x| x.decode()) .collect() }; let input_vec = unsafe { slice::from_raw_parts(self.input, self.input_count as usize) .iter() .map(|ref x| x.decode()) .collect() }; let output_vec = unsafe { slice::from_raw_parts(self.output, self.output_count as usize) .iter() .map(|ref x| x.decode()) .collect() }; let contract: Option<Box<Contract>> = match self.contract as usize { 0 => None, _ => unsafe { Some(Box::new((*self.contract).decode())) } }; Proof { bind_to: bind_to_vec, input: input_vec, output: output_vec, contract, } } fn encode(native: &Proof) -> Self { // bind_to let mut bind_to_vec: Vec<CRgbOutPoint> = native.bind_to .iter() .map(|ref x| CRgbOutPoint::encode(x)) .collect(); bind_to_vec.shrink_to_fit(); let bind_to_count = bind_to_vec.len(); let bind_to = bind_to_vec.as_mut_ptr(); mem::forget(bind_to_vec); // input let mut input_vec: Vec<CRgbProof> = native.input .iter() .map(|ref x| CRgbProof::encode(x)) .collect(); input_vec.shrink_to_fit(); let input_count = input_vec.len(); let input = input_vec.as_mut_ptr(); mem::forget(input_vec); // output let mut output_vec: Vec<CRgbOutputEntry> = native.output .iter() .map(|ref x| CRgbOutputEntry::encode(x)) .collect(); output_vec.shrink_to_fit(); let output_count = output_vec.len(); let output = output_vec.as_mut_ptr(); mem::forget(output_vec); // contract let contract = match native.contract { None => ptr::null_mut(), Some(ref f) => Box::into_raw(Box::new(CRgbContract::encode(f))) }; CRgbProof { bind_to_count: bind_to_count as u32, bind_to, input_count: input_count as u32, input, output_count: output_count as u32, output, contract, } } } #[no_mangle] pub extern "C" fn rgb_proof_is_root_proof(proof: &CRgbProof) -> u8 { match proof.decode().is_root_proof() { true => 1, false => 0 } } #[no_mangle] pub extern "C" fn rgb_proof_get_needed_txs(proof: &CRgbProof, needed_txs: &mut Box<[CRgbNeededTx]>) -> u32 { let needed_txs_native = proof.decode().get_needed_txs(); let needed_txs_vec: Vec<CRgbNeededTx> = needed_txs_native .iter() .map(|ref x| CRgbNeededTx::encode(x)) .collect(); /* A little recap of what's going on here: * * The reason why we can't directly assign *needed_txs = vec.into_boxed_slice() is that * Rust would first try to de-allocate what's inside needed_txs by calling drop() on it. * Since we have no control over what's coming from the C side, and it's very likely that * needed_txs is an uninitialized variable, this would make Rust panic. * * The solution here is to use mem::swap, which does not call drop on either of the elements * being swapped. Then we mem::forget the uninitialized pointer, so that Rust will not try to * drop it once it gets out of scope. * * So we create a "dummy" object (which actually contains our data). We swap the pointer coming * from the C side with our dummy array (so now the uninitialized pointer is in `dummy`) and * finally we forget dummy. */ let mut dummy = needed_txs_vec.into_boxed_slice(); mem::swap(&mut dummy, &mut *needed_txs); mem::forget(dummy); needed_txs_native.len() as u32 } #[no_mangle] pub extern "C" fn rgb_proof_get_expected_script(proof: &CRgbProof, buffer: &mut Box<[u8]>) -> u32 { use bitcoin::network::serialize::serialize; let script = proof.decode().get_expected_script(); let mut encoded: Vec<u8> = serialize(&script).unwrap(); /* std::vec::Vec is encoded as <size>[...data...] by the consensus_encoding functions. This will result in invalid bitcoin scripts since the size would be interpreted as a first op_code. Theoretically this is a VarInt, but since commitment scripts are always much shorter than 256 bytes, we can safely simply remove the first element, knowing that no other bytes from this field will remain */ encoded.remove(0); let size = encoded.len(); // Same swap trick described above in `rgb_proof_get_needed_txs` let mut dummy = encoded.into_boxed_slice(); mem::swap(&mut dummy, &mut *buffer); mem::forget(dummy); size as u32 } #[no_mangle] pub extern "C" fn rgb_proof_get_serialized_size(proof: &CRgbProof) -> u32 { use bitcoin::network::serialize::serialize; let encoded: Vec<u8> = serialize(&proof.decode()).unwrap(); encoded.len() as u32 } #[no_mangle] pub extern "C" fn rgb_proof_serialize(proof: &CRgbProof, buffer: &mut Box<[u8]>) -> u32 { use bitcoin::network::serialize::serialize; let encoded: Vec<u8> = serialize(&proof.decode()).unwrap(); let size = encoded.len(); // Same swap trick described above in `rgb_proof_get_needed_txs` let mut dummy = encoded.into_boxed_slice(); mem::swap(&mut dummy, &mut *buffer); mem::forget(dummy); size as u32 } #[no_mangle] pub extern "C" fn rgb_proof_deserialize(buffer: *const c_uchar, len: u32, proof: &mut CRgbProof) { use bitcoin::network::serialize::deserialize; let sized_slice = unsafe { slice::from_raw_parts(buffer, len as usize) }; let encoded: Vec<u8> = sized_slice.to_vec(); let native_proof = deserialize(&encoded).unwrap(); // Same swap trick described above in `rgb_proof_get_needed_txs` let mut dummy = CRgbProof::encode(&native_proof); mem::swap(&mut dummy, &mut *proof); mem::forget(dummy); }
fn main() { spawn child("Hello"); } fn child(s: str) { }
use crate::libbb::ptr_to_globals::bb_errno; use libc; use libc::off64_t; use libc::off_t; extern "C" { #[no_mangle] fn lseek(__fd: libc::c_int, __offset: off64_t, __whence: libc::c_int) -> off64_t; } pub unsafe fn seek_by_jump(mut fd: libc::c_int, mut amount: off_t) { if amount != 0 && lseek(fd, amount, 1i32) == -1i32 as off_t { if *bb_errno == 29i32 { crate::archival::libarchive::seek_by_read::seek_by_read(fd, amount); } else { crate::libbb::perror_msg::bb_simple_perror_msg_and_die( b"seek failure\x00" as *const u8 as *const libc::c_char, ); } }; }
use actix_web::{self, middleware::Started, HttpMessage, HttpRequest}; use crate::share::common::Claims; use crate::share::state::AppState; use dotenv::dotenv; use jsonwebtoken::{decode, Validation}; use std::env; pub struct Authenticator; struct ClaimsBox(Box<Claims>); pub trait RequestJWTAuth { fn claims(&self) -> Option<Claims>; } impl<S> RequestJWTAuth for HttpRequest<S> { fn claims(&self) -> Option<Claims> { if let Some(claims) = self.extensions().get::<ClaimsBox>() { return Some((*claims.0).clone()); } None } } pub fn secret() -> String { dotenv().ok(); env::var("SECRET").expect("SECRET must be set") } impl actix_web::middleware::Middleware<AppState> for Authenticator { fn start(&self, req: &HttpRequest<AppState>) -> actix_web::Result<Started> { match req.headers().get("Authorization") { Some(token) => { let token: Vec<&str> = token.to_str().unwrap().split(' ').collect(); if token.len() != 2 { return Err(actix_web::error::ErrorInternalServerError( "Error parsing Authorization token", )); } if token[0] != "Bearer" { return Err(actix_web::error::ErrorInternalServerError( "Error parsing Authorization token", )); } let token = token[1]; let token = decode::<Claims>(&token, secret().as_str().as_bytes(), &Validation::default()); if let Err(_e) = token { return Err(actix_web::error::ErrorInternalServerError( "Error decoding Authorization token", )); } let token = token.unwrap(); req.extensions_mut() .insert(ClaimsBox(Box::new(token.claims))); Ok(Started::Done) } None => Ok(Started::Done), } } }
#[doc = "Reader of register TISEL"] pub type R = crate::R<u32, super::TISEL>; #[doc = "Writer for register TISEL"] pub type W = crate::W<u32, super::TISEL>; #[doc = "Register TISEL `reset()`'s with value 0"] impl crate::ResetValue for super::TISEL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `TI1SEL3_0`"] pub type TI1SEL3_0_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TI1SEL3_0`"] pub struct TI1SEL3_0_W<'a> { w: &'a mut W, } impl<'a> TI1SEL3_0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0x0f) | ((value as u32) & 0x0f); self.w } } #[doc = "Reader of field `TI2SEL3_0`"] pub type TI2SEL3_0_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TI2SEL3_0`"] pub struct TI2SEL3_0_W<'a> { w: &'a mut W, } impl<'a> TI2SEL3_0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 8)) | (((value as u32) & 0x0f) << 8); self.w } } #[doc = "Reader of field `TI3SEL3_0`"] pub type TI3SEL3_0_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TI3SEL3_0`"] pub struct TI3SEL3_0_W<'a> { w: &'a mut W, } impl<'a> TI3SEL3_0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 16)) | (((value as u32) & 0x0f) << 16); self.w } } #[doc = "Reader of field `TI4SEL3_0`"] pub type TI4SEL3_0_R = crate::R<u8, u8>; #[doc = "Write proxy for field `TI4SEL3_0`"] pub struct TI4SEL3_0_W<'a> { w: &'a mut W, } impl<'a> TI4SEL3_0_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x0f << 24)) | (((value as u32) & 0x0f) << 24); self.w } } impl R { #[doc = "Bits 0:3 - selects TI1\\[0\\] to TI1\\[15\\] input"] #[inline(always)] pub fn ti1sel3_0(&self) -> TI1SEL3_0_R { TI1SEL3_0_R::new((self.bits & 0x0f) as u8) } #[doc = "Bits 8:11 - selects TI2\\[0\\] to TI2\\[15\\] input"] #[inline(always)] pub fn ti2sel3_0(&self) -> TI2SEL3_0_R { TI2SEL3_0_R::new(((self.bits >> 8) & 0x0f) as u8) } #[doc = "Bits 16:19 - selects TI3\\[0\\] to TI3\\[15\\] input"] #[inline(always)] pub fn ti3sel3_0(&self) -> TI3SEL3_0_R { TI3SEL3_0_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 24:27 - selects TI4\\[0\\] to TI4\\[15\\] input"] #[inline(always)] pub fn ti4sel3_0(&self) -> TI4SEL3_0_R { TI4SEL3_0_R::new(((self.bits >> 24) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:3 - selects TI1\\[0\\] to TI1\\[15\\] input"] #[inline(always)] pub fn ti1sel3_0(&mut self) -> TI1SEL3_0_W { TI1SEL3_0_W { w: self } } #[doc = "Bits 8:11 - selects TI2\\[0\\] to TI2\\[15\\] input"] #[inline(always)] pub fn ti2sel3_0(&mut self) -> TI2SEL3_0_W { TI2SEL3_0_W { w: self } } #[doc = "Bits 16:19 - selects TI3\\[0\\] to TI3\\[15\\] input"] #[inline(always)] pub fn ti3sel3_0(&mut self) -> TI3SEL3_0_W { TI3SEL3_0_W { w: self } } #[doc = "Bits 24:27 - selects TI4\\[0\\] to TI4\\[15\\] input"] #[inline(always)] pub fn ti4sel3_0(&mut self) -> TI4SEL3_0_W { TI4SEL3_0_W { w: self } } }
use app::database::create_connection_pool; use app::usecase::*; use app::web::Context; use chrono::prelude::Utc; use std::collections::HashMap; use std::time::{Instant}; #[tokio::main] async fn main() { let pool = create_connection_pool().unwrap(); let db = pool.get().await.unwrap(); let ctx = Context { storage: db }; for _i in 0..100 { let now = Instant::now(); let values: HashMap<String, f64> = vec![ ("trace0".to_owned(), 1.0), ("trace1".to_owned(), 2.0), ("trace2".to_owned(), 3.0), ("trace3".to_owned(), 4.0), ("trace4".to_owned(), 5.0), ] .into_iter() .collect(); ctx.add_scalars(&values, &Utc::now()).await.unwrap(); println!("{}", now.elapsed().as_millis()); } }
use std::cmp::min; use std::ffi::CString; use std::hash::Hash; use std::marker::PhantomData; use std::sync::Arc; use ash::vk; use crossbeam_channel::{ unbounded, Receiver, Sender, }; use smallvec::SmallVec; use sourcerenderer_core::graphics::{ AccelerationStructureInstance, Barrier, BarrierAccess, BarrierSync, BindingFrequency, BottomLevelAccelerationStructureInfo, Buffer, BufferInfo, BufferUsage, CommandBuffer, CommandBufferType, IndexFormat, LoadOp, MemoryUsage, PipelineBinding, RenderPassBeginInfo, RenderpassRecordingMode, Resettable, Scissor, ShaderType, StoreOp, Texture, TextureLayout, Viewport, WHOLE_BUFFER, }; use crate::bindless::BINDLESS_TEXTURE_SET_INDEX; use crate::buffer::{ BufferAllocator, VkBufferSlice, }; use crate::descriptor::{ VkBindingManager, VkBoundResourceRef, VkBufferBindingInfoRef, PER_SET_BINDINGS, }; use crate::lifetime_tracker::VkLifetimeTrackers; use crate::pipeline::{ shader_type_to_vk, VkPipelineType, }; use crate::query::{ VkQueryAllocator, VkQueryRange, }; use crate::raw::{ RawVkDevice, *, }; use crate::renderpass::{ VkAttachmentInfo, VkRenderPassInfo, VkSubpassInfo, }; use crate::rt::VkAccelerationStructure; use crate::texture::{ VkSampler, VkTextureView, }; use crate::{ VkBackend, VkFrameBuffer, VkPipeline, VkRenderPass, VkShared, VkTexture, }; #[allow(clippy::vec_box)] pub struct VkCommandPool { raw: Arc<RawVkCommandPool>, primary_buffers: Vec<Box<VkCommandBuffer>>, secondary_buffers: Vec<Box<VkCommandBuffer>>, receiver: Receiver<Box<VkCommandBuffer>>, sender: Sender<Box<VkCommandBuffer>>, shared: Arc<VkShared>, queue_family_index: u32, buffer_allocator: Arc<BufferAllocator>, query_allocator: Arc<VkQueryAllocator>, } impl VkCommandPool { pub fn new( device: &Arc<RawVkDevice>, queue_family_index: u32, shared: &Arc<VkShared>, buffer_allocator: &Arc<BufferAllocator>, query_allocator: &Arc<VkQueryAllocator>, ) -> Self { let create_info = vk::CommandPoolCreateInfo { queue_family_index, flags: vk::CommandPoolCreateFlags::empty(), ..Default::default() }; let (sender, receiver) = unbounded(); Self { raw: Arc::new(RawVkCommandPool::new(device, &create_info).unwrap()), primary_buffers: Vec::new(), secondary_buffers: Vec::new(), receiver, sender, shared: shared.clone(), queue_family_index, buffer_allocator: buffer_allocator.clone(), query_allocator: query_allocator.clone(), } } pub fn get_command_buffer(&mut self, frame: u64) -> VkCommandBufferRecorder { let mut buffer = self.primary_buffers.pop().unwrap_or_else(|| { Box::new(VkCommandBuffer::new( &self.raw.device, &self.raw, CommandBufferType::Primary, self.queue_family_index, &self.shared, &self.buffer_allocator, &self.query_allocator, )) }); buffer.begin(frame, None); VkCommandBufferRecorder::new(buffer, self.sender.clone()) } pub fn get_inner_command_buffer( &mut self, frame: u64, inner_info: Option<&VkInnerCommandBufferInfo>, ) -> VkCommandBufferRecorder { let mut buffer = self.secondary_buffers.pop().unwrap_or_else(|| { Box::new(VkCommandBuffer::new( &self.raw.device, &self.raw, CommandBufferType::Secondary, self.queue_family_index, &self.shared, &self.buffer_allocator, &self.query_allocator, )) }); buffer.begin(frame, inner_info); VkCommandBufferRecorder::new(buffer, self.sender.clone()) } } impl Resettable for VkCommandPool { fn reset(&mut self) { unsafe { self.raw .device .reset_command_pool(**self.raw, vk::CommandPoolResetFlags::empty()) .unwrap(); } for mut cmd_buf in self.receiver.try_iter() { cmd_buf.reset(); let buffers = if cmd_buf.command_buffer_type == CommandBufferType::Primary { &mut self.primary_buffers } else { &mut self.secondary_buffers }; buffers.push(cmd_buf); } } } #[derive(PartialEq, Eq, Hash, Clone, Copy, Debug)] pub enum VkCommandBufferState { Ready, Recording, Finished, Submitted, } pub struct VkInnerCommandBufferInfo { pub render_pass: Arc<VkRenderPass>, pub sub_pass: u32, pub frame_buffer: Arc<VkFrameBuffer>, } pub struct VkCommandBuffer { buffer: vk::CommandBuffer, pool: Arc<RawVkCommandPool>, device: Arc<RawVkDevice>, state: VkCommandBufferState, command_buffer_type: CommandBufferType, shared: Arc<VkShared>, render_pass: Option<Arc<VkRenderPass>>, pipeline: Option<Arc<VkPipeline>>, sub_pass: u32, trackers: VkLifetimeTrackers, queue_family_index: u32, descriptor_manager: VkBindingManager, buffer_allocator: Arc<BufferAllocator>, pending_memory_barriers: [vk::MemoryBarrier2; 2], pending_image_barriers: Vec<vk::ImageMemoryBarrier2>, pending_buffer_barriers: Vec<vk::BufferMemoryBarrier2>, frame: u64, inheritance: Option<VkInnerCommandBufferInfo>, query_allocator: Arc<VkQueryAllocator>, } impl VkCommandBuffer { pub(crate) fn new( device: &Arc<RawVkDevice>, pool: &Arc<RawVkCommandPool>, command_buffer_type: CommandBufferType, queue_family_index: u32, shared: &Arc<VkShared>, buffer_allocator: &Arc<BufferAllocator>, query_allocator: &Arc<VkQueryAllocator>, ) -> Self { let buffers_create_info = vk::CommandBufferAllocateInfo { command_pool: ***pool, level: if command_buffer_type == CommandBufferType::Primary { vk::CommandBufferLevel::PRIMARY } else { vk::CommandBufferLevel::SECONDARY }, // TODO: support secondary command buffers / bundles command_buffer_count: 1, // TODO: figure out how many buffers per pool (maybe create a new pool once we've run out?) ..Default::default() }; let mut buffers = unsafe { device.allocate_command_buffers(&buffers_create_info) }.unwrap(); VkCommandBuffer { buffer: buffers.pop().unwrap(), pool: pool.clone(), device: device.clone(), command_buffer_type, render_pass: None, pipeline: None, sub_pass: 0u32, shared: shared.clone(), state: VkCommandBufferState::Ready, trackers: VkLifetimeTrackers::new(), queue_family_index, descriptor_manager: VkBindingManager::new(device), buffer_allocator: buffer_allocator.clone(), pending_buffer_barriers: Vec::with_capacity(4), pending_image_barriers: Vec::with_capacity(4), pending_memory_barriers: [vk::MemoryBarrier2::default(); 2], frame: 0, inheritance: None, query_allocator: query_allocator.clone(), } } pub fn handle(&self) -> &vk::CommandBuffer { &self.buffer } pub fn cmd_buffer_type(&self) -> CommandBufferType { self.command_buffer_type } pub(crate) fn reset(&mut self) { self.state = VkCommandBufferState::Ready; self.trackers.reset(); self.descriptor_manager.reset(self.frame); } pub(crate) fn begin(&mut self, frame: u64, inner_info: Option<&VkInnerCommandBufferInfo>) { assert_eq!(self.state, VkCommandBufferState::Ready); debug_assert!(frame >= self.frame); self.state = VkCommandBufferState::Recording; self.frame = frame; let (flags, inhertiance_info) = if let Some(inner_info) = inner_info { ( vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT | vk::CommandBufferUsageFlags::RENDER_PASS_CONTINUE, vk::CommandBufferInheritanceInfo { render_pass: *inner_info.render_pass.handle(), subpass: inner_info.sub_pass, framebuffer: *inner_info.frame_buffer.handle(), ..Default::default() }, ) } else { ( vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT, Default::default(), ) }; unsafe { self.device .begin_command_buffer( self.buffer, &vk::CommandBufferBeginInfo { flags, p_inheritance_info: &inhertiance_info as *const vk::CommandBufferInheritanceInfo, ..Default::default() }, ) .unwrap(); } } pub(crate) fn end(&mut self) { assert_eq!(self.state, VkCommandBufferState::Recording); if self.render_pass.is_some() { self.end_render_pass(); } self.flush_barriers(); self.state = VkCommandBufferState::Finished; unsafe { self.device.end_command_buffer(self.buffer).unwrap(); } } pub(crate) fn set_pipeline(&mut self, pipeline: PipelineBinding<VkBackend>) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); match &pipeline { PipelineBinding::Graphics(graphics_pipeline) => { let vk_pipeline = graphics_pipeline.handle(); unsafe { self.device.cmd_bind_pipeline( self.buffer, vk::PipelineBindPoint::GRAPHICS, *vk_pipeline, ); } self.trackers.track_pipeline(*graphics_pipeline); if graphics_pipeline.uses_bindless_texture_set() && !self .device .features .contains(VkFeatures::DESCRIPTOR_INDEXING) { panic!("Tried to use pipeline which uses bindless texture descriptor set. The current Vulkan device does not support this."); } self.pipeline = Some((*graphics_pipeline).clone()) } PipelineBinding::Compute(compute_pipeline) => { let vk_pipeline = compute_pipeline.handle(); unsafe { self.device.cmd_bind_pipeline( self.buffer, vk::PipelineBindPoint::COMPUTE, *vk_pipeline, ); } self.trackers.track_pipeline(*compute_pipeline); if compute_pipeline.uses_bindless_texture_set() && !self .device .features .contains(VkFeatures::DESCRIPTOR_INDEXING) { panic!("Tried to use pipeline which uses bindless texture descriptor set. The current Vulkan device does not support this."); } self.pipeline = Some((*compute_pipeline).clone()) } PipelineBinding::RayTracing(rt_pipeline) => { let vk_pipeline = rt_pipeline.handle(); unsafe { self.device.cmd_bind_pipeline( self.buffer, vk::PipelineBindPoint::RAY_TRACING_KHR, *vk_pipeline, ); } self.trackers.track_pipeline(*rt_pipeline); if rt_pipeline.uses_bindless_texture_set() && !self .device .features .contains(VkFeatures::DESCRIPTOR_INDEXING) { panic!("Tried to use pipeline which uses bindless texture descriptor set. The current Vulkan device does not support this."); } self.pipeline = Some((*rt_pipeline).clone()) } }; self.descriptor_manager.mark_all_dirty(); } pub(crate) fn end_render_pass(&mut self) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!( self.render_pass.is_some() || self.command_buffer_type == CommandBufferType::Secondary ); unsafe { self.device.cmd_end_render_pass(self.buffer); } self.render_pass = None; } pub(crate) fn advance_subpass(&mut self) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!( self.render_pass.is_some() || self.command_buffer_type == CommandBufferType::Secondary ); unsafe { self.device .cmd_next_subpass(self.buffer, vk::SubpassContents::INLINE); } self.sub_pass += 1; } pub(crate) fn set_vertex_buffer(&mut self, vertex_buffer: &Arc<VkBufferSlice>, offset: usize) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); self.trackers.track_buffer(vertex_buffer); unsafe { self.device.cmd_bind_vertex_buffers( self.buffer, 0, &[*vertex_buffer.buffer().handle()], &[(vertex_buffer.offset() + offset) as u64], ); } } pub(crate) fn set_index_buffer( &mut self, index_buffer: &Arc<VkBufferSlice>, offset: usize, format: IndexFormat, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); self.trackers.track_buffer(index_buffer); unsafe { self.device.cmd_bind_index_buffer( self.buffer, *index_buffer.buffer().handle(), (index_buffer.offset() + offset) as u64, index_format_to_vk(format), ); } } pub(crate) fn set_viewports(&mut self, viewports: &[Viewport]) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); unsafe { for (i, viewport) in viewports.iter().enumerate() { self.device.cmd_set_viewport( self.buffer, i as u32, &[vk::Viewport { x: viewport.position.x, y: viewport.extent.y - viewport.position.y, width: viewport.extent.x, height: -viewport.extent.y, min_depth: viewport.min_depth, max_depth: viewport.max_depth, }], ); } } } pub(crate) fn set_scissors(&mut self, scissors: &[Scissor]) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); unsafe { let vk_scissors: Vec<vk::Rect2D> = scissors .iter() .map(|scissor| vk::Rect2D { offset: vk::Offset2D { x: scissor.position.x, y: scissor.position.y, }, extent: vk::Extent2D { width: scissor.extent.x, height: scissor.extent.y, }, }) .collect(); self.device.cmd_set_scissor(self.buffer, 0, &vk_scissors); } } fn has_pending_barrier(&self) -> bool { !self.pending_image_barriers.is_empty() || !self.pending_buffer_barriers.is_empty() || !self.pending_memory_barriers[0].src_stage_mask.is_empty() || !self.pending_memory_barriers[0].dst_stage_mask.is_empty() || !self.pending_memory_barriers[1].src_stage_mask.is_empty() || !self.pending_memory_barriers[1].dst_stage_mask.is_empty() } pub(crate) fn draw(&mut self, vertices: u32, offset: u32) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.pipeline.is_some()); debug_assert!(self.pipeline.as_ref().unwrap().pipeline_type() == VkPipelineType::Graphics); debug_assert!(!self.has_pending_barrier()); debug_assert!( self.render_pass.is_some() || self.command_buffer_type == CommandBufferType::Secondary ); unsafe { self.device.cmd_draw(self.buffer, vertices, 1, offset, 0); } } pub(crate) fn draw_indexed( &mut self, instances: u32, first_instance: u32, indices: u32, first_index: u32, vertex_offset: i32, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.pipeline.is_some()); debug_assert!(self.pipeline.as_ref().unwrap().pipeline_type() == VkPipelineType::Graphics); debug_assert!(!self.has_pending_barrier()); debug_assert!( self.render_pass.is_some() || self.command_buffer_type == CommandBufferType::Secondary ); unsafe { self.device.cmd_draw_indexed( self.buffer, indices, instances, first_index, vertex_offset, first_instance, ); } } pub(crate) fn bind_sampling_view( &mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<VkTextureView>, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); self.descriptor_manager.bind( frequency, binding, VkBoundResourceRef::SampledTexture(texture), ); self.trackers.track_texture_view(texture); } pub(crate) fn bind_sampling_view_and_sampler( &mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<VkTextureView>, sampler: &Arc<VkSampler>, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); self.descriptor_manager.bind( frequency, binding, VkBoundResourceRef::SampledTextureAndSampler(texture, sampler), ); self.trackers.track_texture_view(texture); self.trackers.track_sampler(sampler); } pub(crate) fn bind_uniform_buffer( &mut self, frequency: BindingFrequency, binding: u32, buffer: &Arc<VkBufferSlice>, offset: usize, length: usize, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert_ne!(length, 0); self.descriptor_manager.bind( frequency, binding, VkBoundResourceRef::UniformBuffer(VkBufferBindingInfoRef { buffer, offset, length: if length == WHOLE_BUFFER { buffer.length() - offset } else { length }, }), ); self.trackers.track_buffer(buffer); } pub(crate) fn bind_storage_buffer( &mut self, frequency: BindingFrequency, binding: u32, buffer: &Arc<VkBufferSlice>, offset: usize, length: usize, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert_ne!(length, 0); self.descriptor_manager.bind( frequency, binding, VkBoundResourceRef::StorageBuffer(VkBufferBindingInfoRef { buffer, offset, length: if length == WHOLE_BUFFER { buffer.length() - offset } else { length }, }), ); self.trackers.track_buffer(buffer); } pub(crate) fn bind_storage_texture( &mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<VkTextureView>, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); self.descriptor_manager.bind( frequency, binding, VkBoundResourceRef::StorageTexture(texture), ); self.trackers.track_texture_view(texture); } pub(crate) fn bind_sampler( &mut self, frequency: BindingFrequency, binding: u32, sampler: &Arc<VkSampler>, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); self.descriptor_manager .bind(frequency, binding, VkBoundResourceRef::Sampler(sampler)); self.trackers.track_sampler(sampler); } pub(crate) fn finish_binding(&mut self) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.pipeline.is_some()); self.flush_barriers(); let mut offsets = SmallVec::<[u32; PER_SET_BINDINGS]>::new(); let mut descriptor_sets = SmallVec::<[vk::DescriptorSet; (BINDLESS_TEXTURE_SET_INDEX + 1) as usize]>::new(); let mut base_index = 0; let pipeline = self.pipeline.as_ref().expect("No pipeline bound"); let pipeline_layout = pipeline.layout(); let finished_sets = self.descriptor_manager.finish(self.frame, pipeline_layout); for (index, set_option) in finished_sets.iter().enumerate() { match set_option { None => { if !descriptor_sets.is_empty() { unsafe { self.device.cmd_bind_descriptor_sets( self.buffer, match pipeline.pipeline_type() { VkPipelineType::Graphics => vk::PipelineBindPoint::GRAPHICS, VkPipelineType::Compute => vk::PipelineBindPoint::COMPUTE, VkPipelineType::RayTracing => { vk::PipelineBindPoint::RAY_TRACING_KHR } }, *pipeline_layout.handle(), base_index, &descriptor_sets, &offsets, ); offsets.clear(); descriptor_sets.clear(); } } base_index = index as u32 + 1; } Some(set_binding) => { descriptor_sets.push(*set_binding.set.handle()); for i in 0..set_binding.dynamic_offset_count as usize { offsets.push(set_binding.dynamic_offsets[i] as u32); } } } } if !descriptor_sets.is_empty() && base_index + descriptor_sets.len() as u32 != BINDLESS_TEXTURE_SET_INDEX { unsafe { self.device.cmd_bind_descriptor_sets( self.buffer, match pipeline.pipeline_type() { VkPipelineType::Graphics => vk::PipelineBindPoint::GRAPHICS, VkPipelineType::Compute => vk::PipelineBindPoint::COMPUTE, VkPipelineType::RayTracing => vk::PipelineBindPoint::RAY_TRACING_KHR, }, *pipeline_layout.handle(), base_index, &descriptor_sets, &offsets, ); } offsets.clear(); descriptor_sets.clear(); base_index = BINDLESS_TEXTURE_SET_INDEX; } if pipeline.uses_bindless_texture_set() { let bindless_texture_descriptor_set = self.shared.bindless_texture_descriptor_set().unwrap(); descriptor_sets.push(bindless_texture_descriptor_set.descriptor_set_handle()); } if !descriptor_sets.is_empty() { unsafe { self.device.cmd_bind_descriptor_sets( self.buffer, match pipeline.pipeline_type() { VkPipelineType::Graphics => vk::PipelineBindPoint::GRAPHICS, VkPipelineType::Compute => vk::PipelineBindPoint::COMPUTE, VkPipelineType::RayTracing => vk::PipelineBindPoint::RAY_TRACING_KHR, }, *pipeline_layout.handle(), base_index, &descriptor_sets, &offsets, ); } } } pub(crate) fn upload_dynamic_data<T>( &self, data: &[T], usage: BufferUsage, ) -> Arc<VkBufferSlice> where T: 'static + Send + Sync + Sized + Clone, { let slice = self.buffer_allocator.get_slice( &BufferInfo { size: std::mem::size_of_val(data), usage, }, MemoryUsage::UncachedRAM, None, ); unsafe { let ptr = slice.map_unsafe(false).expect("Failed to map buffer"); std::ptr::copy(data.as_ptr(), ptr as *mut T, data.len()); slice.unmap_unsafe(true); } slice } pub(crate) fn upload_dynamic_data_inline<T>( &self, data: &[T], visible_for_shader_type: ShaderType, ) where T: 'static + Send + Sync + Sized + Clone, { debug_assert_eq!(self.state, VkCommandBufferState::Recording); let pipeline = self.pipeline.as_ref().expect("No pipeline bound"); let pipeline_layout = pipeline.layout(); let range = pipeline_layout .push_constant_range(visible_for_shader_type) .expect("No push constants set up for shader"); let size = std::mem::size_of_val(data); unsafe { self.device.cmd_push_constants( self.buffer, *pipeline_layout.handle(), shader_type_to_vk(visible_for_shader_type), range.offset, std::slice::from_raw_parts( data.as_ptr() as *const u8, min(size, range.size as usize), ), ); } } pub(crate) fn allocate_scratch_buffer( &self, info: &BufferInfo, memory_usage: MemoryUsage, ) -> Arc<VkBufferSlice> { self.buffer_allocator.get_slice( &BufferInfo { size: info.size as usize, usage: info.usage, }, memory_usage, None, ) } pub(crate) fn begin_label(&self, label: &str) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); let label_cstring = CString::new(label).unwrap(); if let Some(debug_utils) = self.device.instance.debug_utils.as_ref() { unsafe { debug_utils.debug_utils_loader.cmd_begin_debug_utils_label( self.buffer, &vk::DebugUtilsLabelEXT { p_label_name: label_cstring.as_ptr(), color: [0.0f32; 4], ..Default::default() }, ); } } } pub(crate) fn end_label(&self) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); if let Some(debug_utils) = self.device.instance.debug_utils.as_ref() { unsafe { debug_utils .debug_utils_loader .cmd_end_debug_utils_label(self.buffer); } } } pub(crate) fn execute_inner(&mut self, mut submissions: Vec<VkCommandBufferSubmission>) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); if submissions.is_empty() { return; } for submission in &submissions { assert_eq!( submission.command_buffer_type(), CommandBufferType::Secondary ); } let submission_handles: SmallVec<[vk::CommandBuffer; 16]> = submissions.iter().map(|s| *s.handle()).collect(); unsafe { self.device .cmd_execute_commands(self.buffer, &submission_handles); } for mut submission in submissions.drain(..) { submission.mark_submitted(); self.trackers.track_inner_command_buffer(submission); } } pub(crate) fn dispatch(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.render_pass.is_none()); debug_assert!(self.pipeline.is_some()); debug_assert!(self.pipeline.as_ref().unwrap().pipeline_type() == VkPipelineType::Compute); debug_assert!(!self.has_pending_barrier()); unsafe { self.device .cmd_dispatch(self.buffer, group_count_x, group_count_y, group_count_z); } } pub(crate) fn blit( &mut self, src_texture: &Arc<VkTexture>, src_array_layer: u32, src_mip_level: u32, dst_texture: &Arc<VkTexture>, dst_array_layer: u32, dst_mip_level: u32, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.render_pass.is_none()); debug_assert!(!self.has_pending_barrier()); let src_info = src_texture.info(); let dst_info = dst_texture.info(); let mut src_aspect = vk::ImageAspectFlags::empty(); if src_info.format.is_stencil() { src_aspect |= vk::ImageAspectFlags::STENCIL; } if src_info.format.is_depth() { src_aspect |= vk::ImageAspectFlags::DEPTH; } if src_aspect.is_empty() { src_aspect = vk::ImageAspectFlags::COLOR; } let mut dst_aspect = vk::ImageAspectFlags::empty(); if dst_info.format.is_stencil() { dst_aspect |= vk::ImageAspectFlags::STENCIL; } if dst_info.format.is_depth() { dst_aspect |= vk::ImageAspectFlags::DEPTH; } if dst_aspect.is_empty() { dst_aspect = vk::ImageAspectFlags::COLOR; } unsafe { self.device.cmd_blit_image( self.buffer, *src_texture.handle(), vk::ImageLayout::TRANSFER_SRC_OPTIMAL, *dst_texture.handle(), vk::ImageLayout::TRANSFER_DST_OPTIMAL, &[vk::ImageBlit { src_subresource: vk::ImageSubresourceLayers { aspect_mask: src_aspect, mip_level: src_mip_level, base_array_layer: src_array_layer, layer_count: 1, }, src_offsets: [ vk::Offset3D { x: 0, y: 0, z: 0 }, vk::Offset3D { x: src_info.width as i32, y: src_info.height as i32, z: src_info.depth as i32, }, ], dst_subresource: vk::ImageSubresourceLayers { aspect_mask: dst_aspect, mip_level: dst_mip_level, base_array_layer: dst_array_layer, layer_count: 1, }, dst_offsets: [ vk::Offset3D { x: 0, y: 0, z: 0 }, vk::Offset3D { x: dst_info.width as i32, y: dst_info.height as i32, z: dst_info.depth as i32, }, ], }], vk::Filter::LINEAR, ); } self.trackers.track_texture(src_texture); self.trackers.track_texture(dst_texture); } pub(crate) fn barrier(&mut self, barriers: &[Barrier<VkBackend>]) { for barrier in barriers { match barrier { Barrier::TextureBarrier { old_sync, new_sync, old_layout, new_layout, old_access, new_access, texture, range, } => { let info = texture.info(); let mut aspect_mask = vk::ImageAspectFlags::empty(); if info.format.is_depth() { aspect_mask |= vk::ImageAspectFlags::DEPTH; } if info.format.is_stencil() { aspect_mask |= vk::ImageAspectFlags::STENCIL; } if aspect_mask.is_empty() { aspect_mask |= vk::ImageAspectFlags::COLOR; } let dst_stages = barrier_sync_to_stage(*new_sync); let src_stages = barrier_sync_to_stage(*old_sync); self.pending_image_barriers.push(vk::ImageMemoryBarrier2 { src_stage_mask: src_stages, dst_stage_mask: dst_stages, src_access_mask: barrier_access_to_access(*old_access), dst_access_mask: barrier_access_to_access(*new_access), old_layout: texture_layout_to_image_layout(*old_layout), new_layout: texture_layout_to_image_layout(*new_layout), src_queue_family_index: vk::QUEUE_FAMILY_IGNORED, dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED, image: *texture.handle(), subresource_range: vk::ImageSubresourceRange { aspect_mask, base_array_layer: range.base_array_layer, base_mip_level: range.base_mip_level, level_count: range.mip_level_length, layer_count: range.array_layer_length, }, ..Default::default() }); self.trackers.track_texture(texture); } Barrier::BufferBarrier { old_sync, new_sync, old_access, new_access, buffer, } => { let dst_stages = barrier_sync_to_stage(*new_sync); let src_stages = barrier_sync_to_stage(*old_sync); self.pending_buffer_barriers.push(vk::BufferMemoryBarrier2 { src_stage_mask: src_stages, dst_stage_mask: dst_stages, src_access_mask: barrier_access_to_access(*old_access), dst_access_mask: barrier_access_to_access(*new_access), src_queue_family_index: vk::QUEUE_FAMILY_IGNORED, dst_queue_family_index: vk::QUEUE_FAMILY_IGNORED, buffer: *buffer.buffer().handle(), offset: buffer.offset() as u64, size: buffer.length() as u64, ..Default::default() }); self.trackers.track_buffer(buffer); } Barrier::GlobalBarrier { old_sync, new_sync, old_access, new_access, } => { let dst_stages = barrier_sync_to_stage(*new_sync); let src_stages = barrier_sync_to_stage(*old_sync); let src_access = barrier_access_to_access(*old_access); let dst_access = barrier_access_to_access(*new_access); self.pending_memory_barriers[0].dst_stage_mask |= dst_stages & !(vk::PipelineStageFlags2::ACCELERATION_STRUCTURE_BUILD_KHR | vk::PipelineStageFlags2::ACCELERATION_STRUCTURE_COPY_KHR); self.pending_memory_barriers[0].src_stage_mask |= src_stages & !(vk::PipelineStageFlags2::ACCELERATION_STRUCTURE_BUILD_KHR | vk::PipelineStageFlags2::ACCELERATION_STRUCTURE_COPY_KHR); self.pending_memory_barriers[0].src_access_mask |= barrier_access_to_access(*old_access) & !(vk::AccessFlags2::ACCELERATION_STRUCTURE_WRITE_KHR); self.pending_memory_barriers[0].dst_access_mask |= dst_access & !(vk::AccessFlags2::ACCELERATION_STRUCTURE_READ_KHR | vk::AccessFlags2::ACCELERATION_STRUCTURE_WRITE_KHR); self.pending_memory_barriers[1].dst_access_mask |= dst_access & (vk::AccessFlags2::ACCELERATION_STRUCTURE_READ_KHR | vk::AccessFlags2::ACCELERATION_STRUCTURE_WRITE_KHR); if !self.pending_memory_barriers[1].dst_access_mask.is_empty() { /* VUID-VkMemoryBarrier2-dstAccessMask-06256 If the rayQuery feature is not enabled and dstAccessMask includes VK_ACCESS_2_ACCELERATION_STRUCTURE_READ_BIT_KHR, dstStageMask must not include any of the VK_PIPELINESTAGE*_SHADER_BIT stages except VK_PIPELINE_STAGE_2_RAY_TRACING_SHADER_BIT_KHR So we need to handle RT barriers separately. */ self.pending_memory_barriers[1].src_stage_mask = src_stages & (vk::PipelineStageFlags2::ACCELERATION_STRUCTURE_BUILD_KHR | vk::PipelineStageFlags2::ACCELERATION_STRUCTURE_COPY_KHR); self.pending_memory_barriers[1].src_access_mask = src_access & (vk::AccessFlags2::ACCELERATION_STRUCTURE_WRITE_KHR); self.pending_memory_barriers[1].dst_stage_mask = dst_stages & (vk::PipelineStageFlags2::RAY_TRACING_SHADER_KHR | vk::PipelineStageFlags2::ACCELERATION_STRUCTURE_BUILD_KHR | vk::PipelineStageFlags2::ACCELERATION_STRUCTURE_COPY_KHR); } } } } } pub(crate) fn flush_barriers(&mut self) { const FULL_BARRIER: bool = false; // IN CASE OF EMERGENCY, SET TO TRUE if FULL_BARRIER { let full_memory_barrier = vk::MemoryBarrier2 { src_stage_mask: vk::PipelineStageFlags2::ALL_COMMANDS, dst_stage_mask: vk::PipelineStageFlags2::ALL_COMMANDS, src_access_mask: vk::AccessFlags2::MEMORY_WRITE, dst_access_mask: vk::AccessFlags2::MEMORY_READ | vk::AccessFlags2::MEMORY_WRITE, ..Default::default() }; let dependency_info = vk::DependencyInfo { image_memory_barrier_count: 0, p_image_memory_barriers: std::ptr::null(), buffer_memory_barrier_count: 0, p_buffer_memory_barriers: std::ptr::null(), memory_barrier_count: 1, p_memory_barriers: &full_memory_barrier as *const vk::MemoryBarrier2, ..Default::default() }; unsafe { self.device .synchronization2 .cmd_pipeline_barrier2(self.buffer, &dependency_info); } self.pending_memory_barriers[0].src_stage_mask = vk::PipelineStageFlags2::empty(); self.pending_memory_barriers[0].dst_stage_mask = vk::PipelineStageFlags2::empty(); self.pending_memory_barriers[0].src_access_mask = vk::AccessFlags2::empty(); self.pending_memory_barriers[0].dst_access_mask = vk::AccessFlags2::empty(); self.pending_memory_barriers[1].src_stage_mask = vk::PipelineStageFlags2::empty(); self.pending_memory_barriers[1].dst_stage_mask = vk::PipelineStageFlags2::empty(); self.pending_memory_barriers[1].src_access_mask = vk::AccessFlags2::empty(); self.pending_memory_barriers[1].dst_access_mask = vk::AccessFlags2::empty(); self.pending_image_barriers.clear(); self.pending_buffer_barriers.clear(); return; } if !self.has_pending_barrier() { return; } let dependency_info = vk::DependencyInfo { image_memory_barrier_count: self.pending_image_barriers.len() as u32, p_image_memory_barriers: self.pending_image_barriers.as_ptr(), buffer_memory_barrier_count: self.pending_buffer_barriers.len() as u32, p_buffer_memory_barriers: self.pending_buffer_barriers.as_ptr(), memory_barrier_count: if self.pending_memory_barriers[0].src_stage_mask.is_empty() && self.pending_memory_barriers[0].dst_stage_mask.is_empty() && self.pending_memory_barriers[1].src_stage_mask.is_empty() && self.pending_memory_barriers[1].dst_stage_mask.is_empty() { 0 } else if self.pending_memory_barriers[1].src_stage_mask.is_empty() && self.pending_memory_barriers[1].dst_stage_mask.is_empty() { 1 } else { 2 }, p_memory_barriers: &self.pending_memory_barriers as *const vk::MemoryBarrier2, ..Default::default() }; unsafe { self.device .synchronization2 .cmd_pipeline_barrier2(self.buffer, &dependency_info); } self.pending_memory_barriers[0].src_stage_mask = vk::PipelineStageFlags2::empty(); self.pending_memory_barriers[0].dst_stage_mask = vk::PipelineStageFlags2::empty(); self.pending_memory_barriers[0].src_access_mask = vk::AccessFlags2::empty(); self.pending_memory_barriers[0].dst_access_mask = vk::AccessFlags2::empty(); self.pending_memory_barriers[1].src_stage_mask = vk::PipelineStageFlags2::empty(); self.pending_memory_barriers[1].dst_stage_mask = vk::PipelineStageFlags2::empty(); self.pending_memory_barriers[1].src_access_mask = vk::AccessFlags2::empty(); self.pending_memory_barriers[1].dst_access_mask = vk::AccessFlags2::empty(); self.pending_image_barriers.clear(); self.pending_buffer_barriers.clear(); } pub(crate) fn begin_render_pass( &mut self, renderpass_begin_info: &RenderPassBeginInfo<VkBackend>, recording_mode: RenderpassRecordingMode, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.render_pass.is_none()); self.flush_barriers(); let mut attachment_infos = SmallVec::<[VkAttachmentInfo; 16]>::with_capacity( renderpass_begin_info.attachments.len(), ); let mut width = 0u32; let mut height = 0u32; let mut attachment_views = SmallVec::<[&Arc<VkTextureView>; 8]>::with_capacity( renderpass_begin_info.attachments.len(), ); let mut clear_values = SmallVec::<[vk::ClearValue; 8]>::with_capacity(renderpass_begin_info.attachments.len()); for attachment in renderpass_begin_info.attachments { let view = match &attachment.view { sourcerenderer_core::graphics::RenderPassAttachmentView::RenderTarget(view) => { *view } sourcerenderer_core::graphics::RenderPassAttachmentView::DepthStencil(view) => { *view } }; let info = view.texture().info(); attachment_infos.push(VkAttachmentInfo { format: info.format, samples: info.samples, load_op: attachment.load_op, store_op: attachment.store_op, stencil_load_op: LoadOp::DontCare, stencil_store_op: StoreOp::DontCare, }); width = width.max(info.width); height = height.max(info.height); attachment_views.push(view); clear_values.push(if info.format.is_depth() || info.format.is_stencil() { vk::ClearValue { depth_stencil: vk::ClearDepthStencilValue { depth: 1f32, stencil: 0u32, }, } } else { vk::ClearValue { color: vk::ClearColorValue { float32: [0f32; 4] }, } }); } let renderpass_info = VkRenderPassInfo { attachments: attachment_infos, subpasses: renderpass_begin_info .subpasses .iter() .map(|sp| VkSubpassInfo { input_attachments: sp.input_attachments.iter().cloned().collect(), output_color_attachments: sp.output_color_attachments.iter().cloned().collect(), depth_stencil_attachment: sp.depth_stencil_attachment.clone(), }) .collect(), }; let renderpass = self.shared.get_render_pass(renderpass_info); let framebuffer = self.shared.get_framebuffer(&renderpass, &attachment_views); // TODO: begin info fields unsafe { let begin_info = vk::RenderPassBeginInfo { framebuffer: *framebuffer.handle(), render_pass: *renderpass.handle(), render_area: vk::Rect2D { offset: vk::Offset2D { x: 0i32, y: 0i32 }, extent: vk::Extent2D { width, height }, }, clear_value_count: clear_values.len() as u32, p_clear_values: clear_values.as_ptr(), ..Default::default() }; self.device.cmd_begin_render_pass( self.buffer, &begin_info, if recording_mode == RenderpassRecordingMode::Commands { vk::SubpassContents::INLINE } else { vk::SubpassContents::SECONDARY_COMMAND_BUFFERS }, ); } self.sub_pass = 0; self.trackers.track_frame_buffer(&framebuffer); self.trackers.track_render_pass(&renderpass); self.render_pass = Some(renderpass.clone()); self.inheritance = Some(VkInnerCommandBufferInfo { render_pass: renderpass, sub_pass: 0, frame_buffer: framebuffer, }); } pub fn inheritance(&self) -> &VkInnerCommandBufferInfo { self.inheritance.as_ref().unwrap() } pub fn wait_events( &mut self, events: &[vk::Event], src_stage_mask: vk::PipelineStageFlags, dst_stage_mask: vk::PipelineStageFlags, memory_barriers: &[vk::MemoryBarrier], buffer_memory_barriers: &[vk::BufferMemoryBarrier], image_memory_barriers: &[vk::ImageMemoryBarrier], ) { unsafe { self.device.cmd_wait_events( self.buffer, events, src_stage_mask, dst_stage_mask, memory_barriers, buffer_memory_barriers, image_memory_barriers, ); } } pub fn signal_event(&mut self, event: vk::Event, stage_mask: vk::PipelineStageFlags) { unsafe { self.device.cmd_set_event(self.buffer, event, stage_mask); } } pub fn create_query_range(&mut self, count: u32) -> Arc<VkQueryRange> { let query_range = Arc::new(self.query_allocator.get(vk::QueryType::OCCLUSION, count)); if !query_range.pool.is_reset() { unsafe { self.device.cmd_reset_query_pool( self.buffer, *query_range.pool.handle(), 0, query_range.pool.query_count(), ); } query_range.pool.mark_reset(); } query_range } pub fn begin_query(&mut self, query_range: &Arc<VkQueryRange>, index: u32) { unsafe { self.device.cmd_begin_query( self.buffer, *query_range.pool.handle(), query_range.index + index, vk::QueryControlFlags::empty(), ); } } pub fn end_query(&mut self, query_range: &Arc<VkQueryRange>, index: u32) { unsafe { self.device.cmd_end_query( self.buffer, *query_range.pool.handle(), query_range.index + index, ); } } pub fn copy_query_results_to_buffer( &mut self, query_range: &Arc<VkQueryRange>, buffer: &Arc<VkBufferSlice>, start_index: u32, count: u32, ) { let vk_start = query_range.index + start_index; let vk_count = query_range.count.min(count); unsafe { self.device.cmd_copy_query_pool_results( self.buffer, *query_range.pool.handle(), vk_start, vk_count, *buffer.buffer().handle(), buffer.offset() as u64, std::mem::size_of::<u32>() as u64, vk::QueryResultFlags::WAIT, ) } self.trackers.track_buffer(buffer); } pub fn create_bottom_level_acceleration_structure( &mut self, info: &BottomLevelAccelerationStructureInfo<VkBackend>, size: usize, target_buffer: &Arc<VkBufferSlice>, scratch_buffer: &Arc<VkBufferSlice>, ) -> Arc<VkAccelerationStructure> { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.render_pass.is_none()); self.trackers.track_buffer(scratch_buffer); self.trackers.track_buffer(target_buffer); self.trackers.track_buffer(info.vertex_buffer); self.trackers.track_buffer(info.index_buffer); let acceleration_structure = Arc::new(VkAccelerationStructure::new_bottom_level( &self.device, info, size, target_buffer, scratch_buffer, self.handle(), )); self.trackers .track_acceleration_structure(&acceleration_structure); acceleration_structure } fn upload_top_level_instances( &mut self, instances: &[AccelerationStructureInstance<VkBackend>], ) -> Arc<VkBufferSlice> { for instance in instances { self.trackers .track_acceleration_structure(instance.acceleration_structure); } VkAccelerationStructure::upload_top_level_instances(self, instances) } fn create_top_level_acceleration_structure( &mut self, info: &sourcerenderer_core::graphics::TopLevelAccelerationStructureInfo<VkBackend>, size: usize, target_buffer: &Arc<VkBufferSlice>, scratch_buffer: &Arc<VkBufferSlice>, ) -> Arc<VkAccelerationStructure> { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.render_pass.is_none()); self.trackers.track_buffer(scratch_buffer); self.trackers.track_buffer(target_buffer); self.trackers.track_buffer(info.instances_buffer); for instance in info.instances { self.trackers .track_acceleration_structure(instance.acceleration_structure); } let acceleration_structure = Arc::new(VkAccelerationStructure::new_top_level( &self.device, info, size, target_buffer, scratch_buffer, self.handle(), )); self.trackers .track_acceleration_structure(&acceleration_structure); acceleration_structure } fn trace_ray(&mut self, width: u32, height: u32, depth: u32) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.render_pass.is_none()); debug_assert!( self.pipeline.as_ref().unwrap().pipeline_type() == VkPipelineType::RayTracing ); let rt = self.device.rt.as_ref().unwrap(); let rt_pipeline = self.pipeline.as_ref().unwrap(); unsafe { rt.rt_pipelines.cmd_trace_rays( self.buffer, rt_pipeline.raygen_sbt_region(), rt_pipeline.miss_sbt_region(), rt_pipeline.closest_hit_sbt_region(), &vk::StridedDeviceAddressRegionKHR::default(), width, height, depth, ); } } fn bind_acceleration_structure( &mut self, frequency: BindingFrequency, binding: u32, acceleration_structure: &Arc<VkAccelerationStructure>, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); self.descriptor_manager.bind( frequency, binding, VkBoundResourceRef::AccelerationStructure(acceleration_structure), ); self.trackers .track_acceleration_structure(acceleration_structure); } fn bind_sampling_view_and_sampler_array( &mut self, frequency: BindingFrequency, binding: u32, textures_and_samplers: &[(&Arc<VkTextureView>, &Arc<VkSampler>)], ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); self.descriptor_manager.bind( frequency, binding, VkBoundResourceRef::SampledTextureAndSamplerArray(textures_and_samplers), ); for (texture, samplers) in textures_and_samplers { self.trackers.track_texture_view(*texture); self.trackers.track_sampler(*samplers); } } fn bind_storage_view_array( &mut self, frequency: BindingFrequency, binding: u32, textures: &[&Arc<VkTextureView>], ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); self.descriptor_manager.bind( frequency, binding, VkBoundResourceRef::StorageTextureArray(textures), ); for texture in textures { self.trackers.track_texture_view(*texture); } } fn track_texture_view(&mut self, texture_view: &Arc<VkTextureView>) { self.trackers.track_texture_view(texture_view); } fn draw_indexed_indirect( &mut self, draw_buffer: &Arc<VkBufferSlice>, draw_buffer_offset: u32, count_buffer: &Arc<VkBufferSlice>, count_buffer_offset: u32, max_draw_count: u32, stride: u32, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.pipeline.is_some()); debug_assert!(self.pipeline.as_ref().unwrap().pipeline_type() == VkPipelineType::Graphics); debug_assert!(!self.has_pending_barrier()); debug_assert!( self.render_pass.is_some() || self.command_buffer_type == CommandBufferType::Secondary ); self.trackers.track_buffer(draw_buffer); self.trackers.track_buffer(count_buffer); unsafe { self.device .indirect_count .as_ref() .unwrap() .cmd_draw_indexed_indirect_count( self.buffer, *draw_buffer.buffer().handle(), draw_buffer.offset() as u64 + draw_buffer_offset as u64, *count_buffer.buffer().handle(), count_buffer.offset() as u64 + count_buffer_offset as u64, max_draw_count, stride, ); } } fn draw_indirect( &mut self, draw_buffer: &Arc<VkBufferSlice>, draw_buffer_offset: u32, count_buffer: &Arc<VkBufferSlice>, count_buffer_offset: u32, max_draw_count: u32, stride: u32, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(self.pipeline.is_some()); debug_assert!(self.pipeline.as_ref().unwrap().pipeline_type() == VkPipelineType::Graphics); debug_assert!(!self.has_pending_barrier()); debug_assert!( self.render_pass.is_some() || self.command_buffer_type == CommandBufferType::Secondary ); self.trackers.track_buffer(draw_buffer); self.trackers.track_buffer(count_buffer); unsafe { self.device .indirect_count .as_ref() .unwrap() .cmd_draw_indirect_count( self.buffer, *draw_buffer.buffer().handle(), draw_buffer.offset() as u64 + draw_buffer_offset as u64, *count_buffer.buffer().handle(), count_buffer.offset() as u64 + count_buffer_offset as u64, max_draw_count, stride, ); } } fn clear_storage_texture( &mut self, texture: &Arc<VkTexture>, array_layer: u32, mip_level: u32, values: [u32; 4], ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(!self.has_pending_barrier()); debug_assert!(self.render_pass.is_none()); let format = texture.info().format; let mut aspect_mask = vk::ImageAspectFlags::empty(); if format.is_depth() { aspect_mask |= vk::ImageAspectFlags::DEPTH; } if format.is_stencil() { aspect_mask |= vk::ImageAspectFlags::STENCIL; } if aspect_mask.is_empty() { aspect_mask = vk::ImageAspectFlags::COLOR; } let range = vk::ImageSubresourceRange { aspect_mask: aspect_mask, base_mip_level: mip_level, level_count: 1, base_array_layer: array_layer, layer_count: 1, }; unsafe { if aspect_mask.intersects(vk::ImageAspectFlags::DEPTH) || aspect_mask.intersects(vk::ImageAspectFlags::STENCIL) { self.device.cmd_clear_depth_stencil_image( self.buffer, *texture.handle(), vk::ImageLayout::GENERAL, &vk::ClearDepthStencilValue { depth: values[0] as f32, stencil: values[1], }, &[range], ); } else { self.device.cmd_clear_color_image( self.buffer, *texture.handle(), vk::ImageLayout::GENERAL, &vk::ClearColorValue { uint32: values }, &[range], ); } } } fn clear_storage_buffer( &mut self, buffer: &Arc<VkBufferSlice>, offset: usize, length_in_u32s: usize, value: u32, ) { debug_assert_eq!(self.state, VkCommandBufferState::Recording); debug_assert!(!self.has_pending_barrier()); debug_assert!(self.render_pass.is_none()); let actual_length_in_u32s = if length_in_u32s == WHOLE_BUFFER { debug_assert_eq!((buffer.length() - offset) % 4, 0); (buffer.length() - offset) / 4 } else { length_in_u32s }; let length_in_bytes = actual_length_in_u32s * 4; debug_assert!(buffer.length() - offset >= length_in_bytes); #[repr(packed)] struct MetaClearShaderData { length: u32, value: u32, } let push_data = MetaClearShaderData { length: length_in_bytes as u32, value: value, }; let meta_pipeline = self.shared.get_clear_buffer_meta_pipeline().clone(); let mut bindings = <[VkBoundResourceRef; PER_SET_BINDINGS]>::default(); let binding_offsets = [(buffer.offset() + offset) as u32]; let is_dynamic_binding = meta_pipeline .layout() .descriptor_set_layout(0) .unwrap() .is_dynamic_binding(0); bindings[0] = VkBoundResourceRef::StorageBuffer(VkBufferBindingInfoRef { buffer, offset, length: length_in_bytes, }); let descriptor_set = self .descriptor_manager .get_or_create_set( self.frame, meta_pipeline .layout() .descriptor_set_layout(0) .as_ref() .unwrap(), &bindings, ) .unwrap(); unsafe { self.device.cmd_bind_pipeline( self.buffer, vk::PipelineBindPoint::COMPUTE, *meta_pipeline.handle(), ); self.device.cmd_push_constants( self.buffer, *meta_pipeline.layout().handle(), vk::ShaderStageFlags::COMPUTE, 0, std::slice::from_raw_parts( std::mem::transmute(&push_data as *const MetaClearShaderData), std::mem::size_of::<MetaClearShaderData>(), ), ); self.device.cmd_bind_descriptor_sets( self.buffer, vk::PipelineBindPoint::COMPUTE, *meta_pipeline.layout().handle(), 0, &[*descriptor_set.handle()], if is_dynamic_binding { &binding_offsets } else { &[] }, ); self.device .cmd_dispatch(self.buffer, (actual_length_in_u32s as u32 + 63) / 64, 1, 1); } self.descriptor_manager.mark_all_dirty(); } } impl Drop for VkCommandBuffer { fn drop(&mut self) { if self.state == VkCommandBufferState::Submitted { self.device.wait_for_idle(); } } } // Small wrapper around VkCommandBuffer to // disable Send + Sync because sending VkCommandBuffers across threads // is only safe after recording is done pub struct VkCommandBufferRecorder { item: Option<Box<VkCommandBuffer>>, sender: Sender<Box<VkCommandBuffer>>, phantom: PhantomData<*const u8>, } impl Drop for VkCommandBufferRecorder { fn drop(&mut self) { if self.item.is_none() { return; } let item = std::mem::replace(&mut self.item, Option::None).unwrap(); self.sender.send(item).unwrap(); } } impl VkCommandBufferRecorder { fn new(item: Box<VkCommandBuffer>, sender: Sender<Box<VkCommandBuffer>>) -> Self { Self { item: Some(item), sender, phantom: PhantomData, } } #[inline(always)] pub fn end_render_pass(&mut self) { self.item.as_mut().unwrap().end_render_pass(); } pub fn advance_subpass(&mut self) { self.item.as_mut().unwrap().advance_subpass(); } pub fn wait_events( &mut self, events: &[vk::Event], src_stage_mask: vk::PipelineStageFlags, dst_stage_mask: vk::PipelineStageFlags, memory_barriers: &[vk::MemoryBarrier], buffer_memory_barriers: &[vk::BufferMemoryBarrier], image_memory_barriers: &[vk::ImageMemoryBarrier], ) { self.item.as_mut().unwrap().wait_events( events, src_stage_mask, dst_stage_mask, memory_barriers, buffer_memory_barriers, image_memory_barriers, ); } pub fn signal_event(&mut self, event: vk::Event, stage_mask: vk::PipelineStageFlags) { self.item.as_mut().unwrap().signal_event(event, stage_mask); } pub(crate) fn allocate_scratch_buffer( &mut self, info: &BufferInfo, memory_usage: MemoryUsage, ) -> Arc<VkBufferSlice> { self.item .as_mut() .unwrap() .allocate_scratch_buffer(info, memory_usage) } } impl CommandBuffer<VkBackend> for VkCommandBufferRecorder { #[inline(always)] fn set_pipeline(&mut self, pipeline: PipelineBinding<VkBackend>) { self.item.as_mut().unwrap().set_pipeline(pipeline); } #[inline(always)] fn set_vertex_buffer(&mut self, vertex_buffer: &Arc<VkBufferSlice>, offset: usize) { self.item .as_mut() .unwrap() .set_vertex_buffer(vertex_buffer, offset) } #[inline(always)] fn set_index_buffer( &mut self, index_buffer: &Arc<VkBufferSlice>, offset: usize, format: IndexFormat, ) { self.item .as_mut() .unwrap() .set_index_buffer(index_buffer, offset, format) } #[inline(always)] fn set_viewports(&mut self, viewports: &[Viewport]) { self.item.as_mut().unwrap().set_viewports(viewports); } #[inline(always)] fn set_scissors(&mut self, scissors: &[Scissor]) { self.item.as_mut().unwrap().set_scissors(scissors); } #[inline(always)] fn upload_dynamic_data<T>(&mut self, data: &[T], usage: BufferUsage) -> Arc<VkBufferSlice> where T: 'static + Send + Sync + Sized + Clone, { self.item.as_mut().unwrap().upload_dynamic_data(data, usage) } #[inline(always)] fn upload_dynamic_data_inline<T>(&mut self, data: &[T], visible_for_shader_type: ShaderType) where T: 'static + Send + Sync + Sized + Clone, { self.item .as_mut() .unwrap() .upload_dynamic_data_inline(data, visible_for_shader_type); } #[inline(always)] fn draw(&mut self, vertices: u32, offset: u32) { self.item.as_mut().unwrap().draw(vertices, offset); } #[inline(always)] fn draw_indexed( &mut self, instances: u32, first_instance: u32, indices: u32, first_index: u32, vertex_offset: i32, ) { self.item.as_mut().unwrap().draw_indexed( instances, first_instance, indices, first_index, vertex_offset, ); } #[inline(always)] fn bind_sampling_view( &mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<VkTextureView>, ) { self.item .as_mut() .unwrap() .bind_sampling_view(frequency, binding, texture); } #[inline(always)] fn bind_sampling_view_and_sampler( &mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<VkTextureView>, sampler: &Arc<VkSampler>, ) { self.item .as_mut() .unwrap() .bind_sampling_view_and_sampler(frequency, binding, texture, sampler); } #[inline(always)] fn bind_uniform_buffer( &mut self, frequency: BindingFrequency, binding: u32, buffer: &Arc<VkBufferSlice>, offset: usize, length: usize, ) { self.item .as_mut() .unwrap() .bind_uniform_buffer(frequency, binding, buffer, offset, length); } #[inline(always)] fn bind_storage_buffer( &mut self, frequency: BindingFrequency, binding: u32, buffer: &Arc<VkBufferSlice>, offset: usize, length: usize, ) { self.item .as_mut() .unwrap() .bind_storage_buffer(frequency, binding, buffer, offset, length); } #[inline(always)] fn bind_storage_texture( &mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<VkTextureView>, ) { self.item .as_mut() .unwrap() .bind_storage_texture(frequency, binding, texture); } #[inline(always)] fn bind_sampler( &mut self, frequency: BindingFrequency, binding: u32, sampler: &Arc<VkSampler>, ) { self.item .as_mut() .unwrap() .bind_sampler(frequency, binding, sampler); } #[inline(always)] fn finish_binding(&mut self) { self.item.as_mut().unwrap().finish_binding(); } #[inline(always)] fn begin_label(&mut self, label: &str) { self.item.as_mut().unwrap().begin_label(label); } #[inline(always)] fn end_label(&mut self) { self.item.as_mut().unwrap().end_label(); } #[inline(always)] fn dispatch(&mut self, group_count_x: u32, group_count_y: u32, group_count_z: u32) { self.item .as_mut() .unwrap() .dispatch(group_count_x, group_count_y, group_count_z); } #[inline(always)] fn blit( &mut self, src_texture: &Arc<VkTexture>, src_array_layer: u32, src_mip_level: u32, dst_texture: &Arc<VkTexture>, dst_array_layer: u32, dst_mip_level: u32, ) { self.item.as_mut().unwrap().blit( src_texture, src_array_layer, src_mip_level, dst_texture, dst_array_layer, dst_mip_level, ); } fn finish(self) -> VkCommandBufferSubmission { assert_eq!( self.item.as_ref().unwrap().state, VkCommandBufferState::Recording ); let mut mut_self = self; let mut item = std::mem::replace(&mut mut_self.item, None).unwrap(); item.end(); VkCommandBufferSubmission::new(item, mut_self.sender.clone()) } #[inline(always)] fn barrier<'a>(&mut self, barriers: &[Barrier<VkBackend>]) { self.item.as_mut().unwrap().barrier(barriers); } #[inline(always)] fn flush_barriers(&mut self) { self.item.as_mut().unwrap().flush_barriers(); } #[inline(always)] fn begin_render_pass( &mut self, renderpass_info: &RenderPassBeginInfo<VkBackend>, recording_mode: RenderpassRecordingMode, ) { self.item .as_mut() .unwrap() .begin_render_pass(renderpass_info, recording_mode); } #[inline(always)] fn advance_subpass(&mut self) { self.item.as_mut().unwrap().advance_subpass(); } #[inline(always)] fn end_render_pass(&mut self) { self.item.as_mut().unwrap().end_render_pass(); } type CommandBufferInheritance = VkInnerCommandBufferInfo; #[inline(always)] fn inheritance(&self) -> &VkInnerCommandBufferInfo { self.item.as_ref().unwrap().inheritance() } #[inline(always)] fn execute_inner(&mut self, submission: Vec<VkCommandBufferSubmission>) { self.item.as_mut().unwrap().execute_inner(submission); } #[inline(always)] fn begin_query(&mut self, query_range: &Arc<VkQueryRange>, query_index: u32) { self.item .as_mut() .unwrap() .begin_query(query_range, query_index); } #[inline(always)] fn end_query(&mut self, query_range: &Arc<VkQueryRange>, query_index: u32) { self.item .as_mut() .unwrap() .end_query(query_range, query_index); } #[inline(always)] fn create_query_range(&mut self, count: u32) -> Arc<VkQueryRange> { self.item.as_mut().unwrap().create_query_range(count) } #[inline(always)] fn copy_query_results_to_buffer( &mut self, query_range: &Arc<VkQueryRange>, buffer: &Arc<VkBufferSlice>, start_index: u32, count: u32, ) { self.item.as_mut().unwrap().copy_query_results_to_buffer( query_range, buffer, start_index, count, ); } #[inline(always)] fn create_bottom_level_acceleration_structure( &mut self, info: &BottomLevelAccelerationStructureInfo<VkBackend>, size: usize, target_buffer: &Arc<VkBufferSlice>, scratch_buffer: &Arc<VkBufferSlice>, ) -> Arc<VkAccelerationStructure> { self.item .as_mut() .unwrap() .create_bottom_level_acceleration_structure(info, size, target_buffer, scratch_buffer) } #[inline(always)] fn upload_top_level_instances( &mut self, instances: &[AccelerationStructureInstance<VkBackend>], ) -> Arc<VkBufferSlice> { self.item .as_mut() .unwrap() .upload_top_level_instances(instances) } #[inline(always)] fn create_top_level_acceleration_structure( &mut self, info: &sourcerenderer_core::graphics::TopLevelAccelerationStructureInfo<VkBackend>, size: usize, target_buffer: &Arc<VkBufferSlice>, scratch_buffer: &Arc<VkBufferSlice>, ) -> Arc<VkAccelerationStructure> { self.item .as_mut() .unwrap() .create_top_level_acceleration_structure(info, size, target_buffer, scratch_buffer) } #[inline(always)] fn create_temporary_buffer( &mut self, info: &BufferInfo, memory_usage: MemoryUsage, ) -> Arc<VkBufferSlice> { self.item .as_mut() .unwrap() .allocate_scratch_buffer(info, memory_usage) } #[inline(always)] fn trace_ray(&mut self, width: u32, height: u32, depth: u32) { self.item.as_mut().unwrap().trace_ray(width, height, depth); } #[inline(always)] fn bind_acceleration_structure( &mut self, frequency: BindingFrequency, binding: u32, acceleration_structure: &Arc<VkAccelerationStructure>, ) { self.item.as_mut().unwrap().bind_acceleration_structure( frequency, binding, acceleration_structure, ); } #[inline(always)] fn track_texture_view(&mut self, texture_view: &Arc<VkTextureView>) { self.item.as_mut().unwrap().track_texture_view(texture_view); } #[inline(always)] fn draw_indexed_indirect( &mut self, draw_buffer: &Arc<VkBufferSlice>, draw_buffer_offset: u32, count_buffer: &Arc<VkBufferSlice>, count_buffer_offset: u32, max_draw_count: u32, stride: u32, ) { self.item.as_mut().unwrap().draw_indexed_indirect( draw_buffer, draw_buffer_offset, count_buffer, count_buffer_offset, max_draw_count, stride, ); } #[inline(always)] fn draw_indirect( &mut self, draw_buffer: &Arc<VkBufferSlice>, draw_buffer_offset: u32, count_buffer: &Arc<VkBufferSlice>, count_buffer_offset: u32, max_draw_count: u32, stride: u32, ) { self.item.as_mut().unwrap().draw_indexed_indirect( draw_buffer, draw_buffer_offset, count_buffer, count_buffer_offset, max_draw_count, stride, ); } #[inline(always)] fn clear_storage_texture( &mut self, texture: &Arc<VkTexture>, array_layer: u32, mip_level: u32, values: [u32; 4], ) { self.item .as_mut() .unwrap() .clear_storage_texture(texture, array_layer, mip_level, values); } #[inline(always)] fn clear_storage_buffer( &mut self, buffer: &Arc<VkBufferSlice>, offset: usize, length_in_u32s: usize, value: u32, ) { self.item .as_mut() .unwrap() .clear_storage_buffer(buffer, offset, length_in_u32s, value); } #[inline(always)] fn bind_sampling_view_and_sampler_array( &mut self, frequency: BindingFrequency, binding: u32, textures_and_samplers: &[(&Arc<VkTextureView>, &Arc<VkSampler>)], ) { self.item .as_mut() .unwrap() .bind_sampling_view_and_sampler_array(frequency, binding, textures_and_samplers) } #[inline(always)] fn bind_storage_view_array( &mut self, frequency: BindingFrequency, binding: u32, textures: &[&Arc<VkTextureView>], ) { self.item .as_mut() .unwrap() .bind_storage_view_array(frequency, binding, textures) } } pub struct VkCommandBufferSubmission { item: Option<Box<VkCommandBuffer>>, sender: Sender<Box<VkCommandBuffer>>, } unsafe impl Send for VkCommandBufferSubmission {} impl VkCommandBufferSubmission { fn new(item: Box<VkCommandBuffer>, sender: Sender<Box<VkCommandBuffer>>) -> Self { Self { item: Some(item), sender, } } pub(crate) fn mark_submitted(&mut self) { let item = self.item.as_mut().unwrap(); assert_eq!(item.state, VkCommandBufferState::Finished); item.state = VkCommandBufferState::Submitted; } pub(crate) fn handle(&self) -> &vk::CommandBuffer { self.item.as_ref().unwrap().handle() } pub(crate) fn command_buffer_type(&self) -> CommandBufferType { self.item.as_ref().unwrap().command_buffer_type } pub(crate) fn queue_family_index(&self) -> u32 { self.item.as_ref().unwrap().queue_family_index } } impl Drop for VkCommandBufferSubmission { fn drop(&mut self) { let item = std::mem::replace(&mut self.item, None).unwrap(); let _ = self.sender.send(item); } } fn barrier_sync_to_stage(sync: BarrierSync) -> vk::PipelineStageFlags2 { let mut stages = vk::PipelineStageFlags2::NONE; if sync.contains(BarrierSync::COMPUTE_SHADER) { stages |= vk::PipelineStageFlags2::COMPUTE_SHADER; } if sync.contains(BarrierSync::COPY) { stages |= vk::PipelineStageFlags2::TRANSFER; } if sync.contains(BarrierSync::EARLY_DEPTH) { stages |= vk::PipelineStageFlags2::EARLY_FRAGMENT_TESTS; } if sync.contains(BarrierSync::FRAGMENT_SHADER) { stages |= vk::PipelineStageFlags2::FRAGMENT_SHADER; } if sync.contains(BarrierSync::INDIRECT) { stages |= vk::PipelineStageFlags2::DRAW_INDIRECT; } if sync.contains(BarrierSync::LATE_DEPTH) { stages |= vk::PipelineStageFlags2::LATE_FRAGMENT_TESTS; } if sync.contains(BarrierSync::RENDER_TARGET) { stages |= vk::PipelineStageFlags2::COLOR_ATTACHMENT_OUTPUT; } if sync.contains(BarrierSync::RESOLVE) { stages |= vk::PipelineStageFlags2::RESOLVE; } if sync.contains(BarrierSync::VERTEX_INPUT) { stages |= vk::PipelineStageFlags2::VERTEX_ATTRIBUTE_INPUT; } if sync.contains(BarrierSync::INDEX_INPUT) { stages |= vk::PipelineStageFlags2::INDEX_INPUT; } if sync.contains(BarrierSync::VERTEX_SHADER) { stages |= vk::PipelineStageFlags2::VERTEX_SHADER; } if sync.contains(BarrierSync::HOST) { stages |= vk::PipelineStageFlags2::HOST; } if sync.contains(BarrierSync::ACCELERATION_STRUCTURE_BUILD) { stages |= vk::PipelineStageFlags2::ACCELERATION_STRUCTURE_BUILD_KHR; } if sync.contains(BarrierSync::RAY_TRACING) { stages |= vk::PipelineStageFlags2::RAY_TRACING_SHADER_KHR; } stages } fn barrier_access_to_access(access: BarrierAccess) -> vk::AccessFlags2 { let mut vk_access = vk::AccessFlags2::empty(); if access.contains(BarrierAccess::INDEX_READ) { vk_access |= vk::AccessFlags2::INDEX_READ; } if access.contains(BarrierAccess::INDIRECT_READ) { vk_access |= vk::AccessFlags2::INDIRECT_COMMAND_READ; } if access.contains(BarrierAccess::VERTEX_INPUT_READ) { vk_access |= vk::AccessFlags2::VERTEX_ATTRIBUTE_READ; } if access.contains(BarrierAccess::CONSTANT_READ) { vk_access |= vk::AccessFlags2::UNIFORM_READ; } if access.intersects(BarrierAccess::SAMPLING_READ) { vk_access |= vk::AccessFlags2::SHADER_SAMPLED_READ; } if access.intersects(BarrierAccess::STORAGE_READ) { vk_access |= vk::AccessFlags2::SHADER_STORAGE_READ; } if access.contains(BarrierAccess::STORAGE_WRITE) { vk_access |= vk::AccessFlags2::SHADER_STORAGE_WRITE; } if access.contains(BarrierAccess::COPY_READ) { vk_access |= vk::AccessFlags2::TRANSFER_READ; } if access.contains(BarrierAccess::COPY_WRITE) { vk_access |= vk::AccessFlags2::TRANSFER_WRITE; } if access.contains(BarrierAccess::RESOLVE_READ) { vk_access |= vk::AccessFlags2::TRANSFER_READ; // TODO: sync2 } if access.contains(BarrierAccess::RESOLVE_WRITE) { vk_access |= vk::AccessFlags2::TRANSFER_WRITE; } if access.contains(BarrierAccess::DEPTH_STENCIL_READ) { vk_access |= vk::AccessFlags2::DEPTH_STENCIL_ATTACHMENT_READ; } if access.contains(BarrierAccess::DEPTH_STENCIL_WRITE) { vk_access |= vk::AccessFlags2::DEPTH_STENCIL_ATTACHMENT_WRITE; } if access.contains(BarrierAccess::RENDER_TARGET_READ) { vk_access |= vk::AccessFlags2::COLOR_ATTACHMENT_READ; } if access.contains(BarrierAccess::RENDER_TARGET_WRITE) { vk_access |= vk::AccessFlags2::COLOR_ATTACHMENT_WRITE; } if access.contains(BarrierAccess::SHADER_READ) { vk_access |= vk::AccessFlags2::SHADER_READ; } if access.contains(BarrierAccess::SHADER_WRITE) { vk_access |= vk::AccessFlags2::SHADER_WRITE; } if access.contains(BarrierAccess::MEMORY_READ) { vk_access |= vk::AccessFlags2::MEMORY_READ; } if access.contains(BarrierAccess::MEMORY_WRITE) { vk_access |= vk::AccessFlags2::MEMORY_WRITE; } if access.contains(BarrierAccess::HOST_READ) { vk_access |= vk::AccessFlags2::HOST_READ; } if access.contains(BarrierAccess::HOST_WRITE) { vk_access |= vk::AccessFlags2::HOST_WRITE; } if access.contains(BarrierAccess::ACCELERATION_STRUCTURE_READ) { vk_access |= vk::AccessFlags2::ACCELERATION_STRUCTURE_READ_KHR; } if access.contains(BarrierAccess::ACCELERATION_STRUCTURE_WRITE) { vk_access |= vk::AccessFlags2::ACCELERATION_STRUCTURE_WRITE_KHR; } vk_access } fn texture_layout_to_image_layout(layout: TextureLayout) -> vk::ImageLayout { match layout { TextureLayout::CopyDst => vk::ImageLayout::TRANSFER_DST_OPTIMAL, TextureLayout::CopySrc => vk::ImageLayout::TRANSFER_SRC_OPTIMAL, TextureLayout::DepthStencilRead => vk::ImageLayout::DEPTH_STENCIL_READ_ONLY_OPTIMAL, TextureLayout::DepthStencilReadWrite => vk::ImageLayout::DEPTH_STENCIL_ATTACHMENT_OPTIMAL, TextureLayout::General => vk::ImageLayout::GENERAL, TextureLayout::Sampled => vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL, TextureLayout::Storage => vk::ImageLayout::GENERAL, TextureLayout::RenderTarget => vk::ImageLayout::COLOR_ATTACHMENT_OPTIMAL, TextureLayout::ResolveSrc => vk::ImageLayout::TRANSFER_SRC_OPTIMAL, TextureLayout::ResolveDst => vk::ImageLayout::TRANSFER_DST_OPTIMAL, TextureLayout::Undefined => vk::ImageLayout::UNDEFINED, TextureLayout::Present => vk::ImageLayout::PRESENT_SRC_KHR, } } pub(crate) fn index_format_to_vk(format: IndexFormat) -> vk::IndexType { match format { IndexFormat::U16 => vk::IndexType::UINT16, IndexFormat::U32 => vk::IndexType::UINT32, } } const WRITE_ACCESS_MASK: vk::AccessFlags2 = vk::AccessFlags2::from_raw( vk::AccessFlags2::HOST_WRITE.as_raw() | vk::AccessFlags2::MEMORY_WRITE.as_raw() | vk::AccessFlags2::SHADER_WRITE.as_raw() | vk::AccessFlags2::TRANSFER_WRITE.as_raw() | vk::AccessFlags2::COLOR_ATTACHMENT_WRITE.as_raw() | vk::AccessFlags2::DEPTH_STENCIL_ATTACHMENT_WRITE.as_raw(), );
#![ allow( non_snake_case ) ] use serde_derive::*; use std::collections::HashMap; use lt_blockchain::blockchain::{ digest, transaction }; // #[ test ] fn new() { println!( "check constructor" ); let got = digest::Digest::new(); assert_eq!( got.len(), 0 ); let exp : Vec<u8> = vec![]; assert_eq!( got.to_vec(), exp ); } // #[ test ] fn from() { println!( "from Vec<u8>" ); let src = Vec::from( "abc".as_bytes() ); let got = digest::Digest::from( src ); assert_eq!( got.len(), 3 ); assert_eq!( got.to_vec(), vec![ 97, 98, 99 ] ); } // #[ test ] #[ ignore ] fn hash_single() { /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/5 To run test enter : cargo test digest_test::hash_single -- --ignored When test will pass, comment out directive `#[ ignore ]`. */ #[ derive( Clone, Serialize, Deserialize ) ] struct A { f1 : u8, f2 : u8, } #[ derive( Clone, Serialize, Deserialize ) ] struct B { a : u8, b : u8, c : String, } /* */ println!( "hash serializable struct" ); let src = A { f1 : 1, f2 : 2 }; let got = digest::hash_single( &src ); assert_eq!( got.len(), 32 ); assert_eq!( digest::bytes_to_string_hex( &got ), "9131e60c31533f813d5edff6ebb75c2ebba0f130e121e5aa63e6f7db2be5adfe" ); println!( "hash struct twice" ); let src = A { f1 : 1, f2 : 2 }; let got = digest::hash_single( &src ); assert_eq!( got.len(), 32 ); assert_eq!( digest::bytes_to_string_hex( &got ), "9131e60c31533f813d5edff6ebb75c2ebba0f130e121e5aa63e6f7db2be5adfe" ); let got = digest::hash_single( &src ); assert_eq!( got.len(), 32 ); assert_eq!( digest::bytes_to_string_hex( &got ), "9131e60c31533f813d5edff6ebb75c2ebba0f130e121e5aa63e6f7db2be5adfe" ); println!( "check length of hashes from different structures" ); let src = A { f1 : 1, f2 : 2 }; let got = digest::hash_single( &src ); assert_eq!( got.len(), 32 ); let src = B { a : 1, b : 2, c : String::from( "abc" ) }; let got = digest::hash_single( &src ); assert_eq!( got.len(), 32 ); } // #[ test ] #[ ignore ] fn hash_every() { /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/8 To run test enter : cargo test digest_test::hash_every -- --ignored When test will pass, comment out directive `#[ ignore ]`. */ #[ derive( Debug, Clone, Serialize, Deserialize ) ] struct A { f1 : u8, f2 : u8, } /* */ println!( "hash single item, should be identical to hash_single" ); let src = A { f1 : 1, f2 : 2 }; let got = digest::hash_every( &vec![ src.clone() ] ); assert_eq!( got.len(), 32 ); let exp = digest::hash_single( &src.clone() ); assert_eq!( got, exp ); println!( "hash several items" ); let src = A { f1 : 1, f2 : 2 }; let got = digest::hash_every( &vec![ src.clone(), src.clone() ] ); assert_eq!( got.len(), 32 ); let exp = digest::hash_single( &src.clone() ); assert_ne!( &got, &exp ); assert_eq!( digest::bytes_to_string_hex( &got ), "bd6eb60738e54d64f94e07f0dd906a548daa7a00521afeff905fce49aede2d1b" ); } // #[ test ] #[ ignore ] fn bytes_to_string_hex() { /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/10 To run test enter : cargo test digest_test::bytes_to_string_hex -- --ignored When test will pass, comment out directive `#[ ignore ]`. */ println!( "convert vector of bytes to string" ); let src = vec![ 5, 23, 255, 143, 64, 128 ]; let got = digest::bytes_to_string_hex( &src ); assert_eq!( got, String::from( "0517ff8f4080" ) ); } // #[ test ] #[ ignore ] fn merkle_calc() { /* issue : https://github.com/Learn-Together-Pro/Blockchain/issues/6 To run test enter : cargo test digest_test::merkle_calc -- --ignored When test will pass, comment out directive `#[ ignore ]`. */ fn transaction_empty_create() -> transaction::Transaction { let transaction_header = transaction::TransactionHeader { sender : digest::Digest::new(), receiver : HashMap::new(), amount : 1.0, time : 100, body : () }; transaction_header.form() } /* */ println!( "calculate single hash" ); let transaction = transaction_empty_create(); let src = vec![ transaction.clone() ]; let got = digest::merkle_calc( &src ); assert_eq!( got.len(), 32 ); let exp = digest::hash_single( &transaction.body.hash.clone() ); assert_eq!( got, exp ); println!( "calculate several hashes" ); let transaction = transaction_empty_create(); let src = vec![ transaction.clone(), transaction.clone() ]; let got = digest::merkle_calc( &src ); assert_eq!( got.len(), 32 ); let exp = digest::hash_single( &transaction.body.hash.clone() ); assert_ne!( got, exp ); }
use super::*; impl<A: Array> Eq for StackVec<A> where A::Item : Eq, {} impl<A: Array> PartialEq for StackVec<A> where A::Item : PartialEq, { #[inline(always)] fn eq ( self: &Self, other: &Self, ) -> bool { self.as_slice().eq(other.as_slice()) } } impl<A: Array> hash::Hash for StackVec<A> where A::Item : hash::Hash, { fn hash<H: hash::Hasher> ( self: &Self, state: &mut H, ) { self.as_slice().hash(state) } } impl<A: Array> Clone for StackVec<A> where A::Item : Clone, { fn clone ( self: &Self, ) -> Self { self.iter().cloned().collect() } } mod from_iter; pub(in crate) mod into_iter; pub use self::array_into_iter::*; mod array_into_iter; pub use self::try_into::*; mod try_into; pub use self::try_from_iter::*; mod try_from_iter;
use std::cmp::max; /* The [vh]Rule[1-6]_Smush functions return the smushed character OR false if the two characters can't be smushed */ /// # Rule 1: EQUAL CHARACTER SMUSHING (code value 1) /// /// Two sub-characters are smushed into a single sub-character /// if they are the same. This rule does not smush /// hardblanks. (See rule 6 on hardblanks below) /// pub fn hrule1_smush(ch1: u8, ch2: u8, hardBlank: u8) -> Option<u8> { if ch1 == ch2 && ch1 != hardBlank { Some(ch1) } else { None } } /// # Rule 2: UNDERSCORE SMUSHING (code value 2) /// /// An underscore ("_") will be replaced by any of: "|", "/", /// "\", "[", "]", "{", "}", "(", ")", "<" or ">". pub fn hrule2_smush(ch1: u8, ch2: u8) -> Option<u8> { const RULE: &'static str = "|/\\[]{}()<>"; match (ch1, ch2) { (b'_', _) if RULE.find(ch2 as char).is_some() => Some(ch2), (_, b'_') if RULE.find(ch1 as char).is_some() => Some(ch1), _ => None, } } /// # Rule 3: HIERARCHY SMUSHING (code value 4) /// /// A hierarchy of six classes is used: "|", "/\", "[]", "{}", /// "()", and "<>". When two smushing sub-characters are /// from different classes, the one from the latter class /// will be used. pub fn hrule3_smush(ch1: u8, ch2: u8) -> Option<u8> { const RULE: &'static str = "|/\\[]{}()<>"; if let (Some(p1), Some(p2)) = find_indexes(RULE, ch1, ch2) { if p1 != p2 && (p1 as i32 - p2 as i32).abs() != 1 { return Some(RULE.as_bytes()[max(p1, p2)] as u8); } } None } /// # Rule 4: OPPOSITE PAIR SMUSHING (code value 8) /// /// Smushes opposing brackets ("[]" or "]["), braces ("{}" or /// "}{") and parentheses ("()" or ")(") together, replacing /// any such pair with a vertical bar ("|"). pub fn hrule4_smush(ch1: u8, ch2: u8) -> Option<u8> { const RULE: &'static str = "[] {} ()"; if let (Some(p1), Some(p2)) = find_indexes(RULE, ch1, ch2) { if (p1 as i32 - p2 as i32).abs() <= 1 { return Some(b'|'); } } None } /// # Rule 5: BIG X SMUSHING (code value 16) /// /// Smushes "/\" into "|", "\/" into "Y", and "><" into "X". /// Note that "<>" is not smushed in any way by this rule. /// The name "BIG X" is historical; originally all three pairs /// were smushed into "X". pub fn hrule5_smush(c1: u8, c2: u8) -> Option<u8> { match (c1, c2) { (b'/', b'\\') => Some(b'|'), (b'\\', b'/') => Some(b'Y'), (b'>', b'<') => Some(b'X'), _ => None, } } /// # Rule 6: HARDBLANK SMUSHING (code value 32) /// /// Smushes two hardblanks together, replacing them with a /// single hardblank. (See "Hardblanks" below.) pub fn hrule6_smush(c1: u8, c2: u8, hard_blank: u8) -> Option<u8> { if c1 == hard_blank && c2 == hard_blank { Some(hard_blank) } else { None } } /// # Rule 1: EQUAL CHARACTER SMUSHING (code value 256) /// /// Same as horizontal smushing rule 1. pub fn vrule1_smush(c1: u8, c2: u8) -> Option<u8> { if c1 == c2 { Some(c1) } else { None } } /// # Rule 2: UNDERSCORE SMUSHING (code value 512) /// Same as horizontal smushing rule 2. pub fn vrule2_smush(c1: u8, c2: u8) -> Option<u8> { hrule2_smush(c1, c2) } /// # Rule 3: HIERARCHY SMUSHING (code value 1024) /// Same as horizontal smushing rule 2. pub fn vrule3_smush(c1: u8, c2: u8) -> Option<u8> { hrule3_smush(c1, c2) } /// # Rule 4: HORIZONTAL LINE SMUSHING (code value 2048) /// /// Smushes stacked pairs of "-" and "_", replacing them with /// a single "=" sub-character. It does not matter which is /// found above the other. Note that vertical smushing rule 1 /// will smush IDENTICAL pairs of horizontal lines, while this /// rule smushes horizontal lines consisting of DIFFERENT /// sub-characters. pub fn vrule4_smush(c1: u8, c2: u8) -> Option<u8> { match (c1, c2) { (b'-', b'_') | (b'_', b'-') => Some(b'='), _ => None, } } /// # Rule 5: VERTICAL LINE SUPERSMUSHING (code value 4096) /// /// This one rule is different from all others, in that it /// "supersmushes" vertical lines consisting of several /// vertical bars ("|"). This creates the illusion that /// FIGcharacters have slid vertically against each other. /// Supersmushing continues until any sub-characters other /// than "|" would have to be smushed. Supersmushing can /// produce impressive results, but it is seldom possible, /// since other sub-characters would usually have to be /// considered for smushing as soon as any such stacked /// vertical lines are encountered. pub fn vrule5_smush(c1: u8, c2: u8) -> Option<u8> { if c1 == b'|' && c2 == b'|' { Some(b'|') } else { None } } /// Universal smushing simply overrides the sub-character from the /// earlier FIGcharacter with the sub-character from the later /// FIGcharacter. This produces an "overlapping" effect with some /// FIGfonts, wherin the latter FIGcharacter may appear to be "in /// front". pub fn uni_smush(c1: u8, c2: u8, hard_blank: u8) -> u8 { // TODO: Check if c2 is blank? if c2 == b' ' { c1 } else if c2 == hard_blank && c1 != b' ' { c1 } else { c2 } } pub fn find_indexes(string: &'static str, c1: u8, c2: u8) -> (Option<usize>, Option<usize>) { (string.find(c1 as char), string.find(c2 as char)) } #[cfg(test)] mod tests { use super::*; #[test] fn test_hrule3_smush() { assert_eq!(hrule3_smush(b'[', b')'), Some(b')')); assert_eq!(hrule3_smush(b'>', b')'), Some(b'>')); assert_eq!(hrule3_smush(b'>', b'_'), None); } #[test] fn test_hrule5_smush() { assert_eq!(hrule5_smush(b'/', b'\\'), Some(b'|')); assert_eq!(hrule5_smush(b'\\', b'/'), Some(b'Y')); assert_eq!(hrule5_smush(b'>', b'<'), Some(b'X')); assert_eq!(hrule5_smush(b'>', b'_'), None); } }
use regex::Regex; use std::collections::HashMap; use std::fs; use std::str; fn get_passport_hashmap(passport: &str) -> HashMap<&str, &str> { let mut passport_hashmap = HashMap::new(); let re = Regex::new("\n| ").unwrap(); let substrings: Vec<&str> = re.split(passport).collect(); for substring in substrings.iter() { let helper: Vec<&str> = substring.split(":").collect(); passport_hashmap.insert(helper[0], helper[1].trim()); } passport_hashmap } pub fn run() { let content = fs::read_to_string("src/day_4/input.txt").unwrap(); let delimiter = Regex::new("\n\\s+\n").unwrap(); let passports: Vec<&str> = delimiter.split(&content).collect(); let keys = [ ("byr", Regex::new("^19[2-9][0-9]|200[0-2]$").unwrap()), ("iyr", Regex::new("^201[0-9]|2020$").unwrap()), ("eyr", Regex::new("^202[0-9]|2030$").unwrap()), ( "hgt", Regex::new("^1([5-8][0-9]|9[0-3])cm|(59|6[0-9]|7[0-6])in$").unwrap(), ), ("hcl", Regex::new("^#[0-9a-f]{6}$").unwrap()), ("ecl", Regex::new("^amb|blu|brn|gry|grn|hzl|oth$").unwrap()), ("pid", Regex::new("^[0-9]{9}$").unwrap()), ]; let mut matches = 0; for passport in passports.iter() { let passport_hashmap = get_passport_hashmap(passport); if keys.iter().all(|(key, re)| { passport_hashmap.contains_key(key) && re.is_match(passport_hashmap.get(key).unwrap()) }) { matches = matches + 1; } } println!( "Out of {} passports, {} are valid.", passports.len(), matches ); }
use sea_schema::migration::prelude::*; pub struct Migration; impl MigrationName for Migration { fn name(&self) -> &str { "m20220421_000001_create_nodes_table" } } #[async_trait::async_trait] impl MigrationTrait for Migration { async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> { manager .create_table( Table::create() .table(Node::Table) .if_not_exists() .col(ColumnDef::new(Node::Id).string().not_null().primary_key()) .col(ColumnDef::new(Node::Role).small_integer().not_null()) .col( ColumnDef::new(Node::Username) .string() .unique_key() .not_null(), ) .col(ColumnDef::new(Node::Alias).string().not_null()) .col(ColumnDef::new(Node::Network).string().not_null()) .col(ColumnDef::new(Node::ListenAddr).string().not_null()) .col(ColumnDef::new(Node::ListenPort).integer().not_null()) .col(ColumnDef::new(Node::CreatedAt).big_integer().not_null()) .col(ColumnDef::new(Node::UpdatedAt).big_integer().not_null()) .col(ColumnDef::new(Node::Status).small_integer().not_null()) .to_owned(), ) .await } async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> { let mut stmt = Table::drop(); stmt.table(Node::Table); manager.drop_table(stmt).await } } #[derive(Iden)] enum Node { Id, Table, Role, Username, Alias, Network, ListenAddr, ListenPort, CreatedAt, UpdatedAt, Status, }
#[macro_use] extern crate log; #[macro_use] extern crate enum_primitive; extern crate num; use std::sync::{Once, ONCE_INIT}; #[macro_use] mod util; pub mod constants; pub mod native; pub mod ssh_key; pub mod ssh_session; pub mod ssh_bind; static SSH_INIT: Once = ONCE_INIT; pub fn ssh_init() { //check_ssh_ok!(1); SSH_INIT.call_once(|| { unsafe { native::libssh::ssh_init() }; }) } pub fn ssh_finalize() { debug!("calling ssh_finalize()."); unsafe { native::libssh::ssh_finalize() }; } pub struct SSHFinalizer; impl Drop for SSHFinalizer { fn drop(&mut self) { ssh_finalize(); } } pub fn with_ssh<F: Fn()>(func: F) { ssh_init(); let finalizer = SSHFinalizer; func(); drop(finalizer); }
use crate::gl_wrapper::*; use std::collections::{HashMap, VecDeque}; use std::path::Path; use crate::containers::CONTAINER; use std::ffi::c_void; use crate::shaders::voxel::VoxelShader; #[derive(Copy)] #[derive(Clone)] pub struct Block { pub id: &'static str } impl Block { fn air() -> Self { Block { id: "air" } } } pub struct BlockCatalog { pub blocks_texture_atlas: Texture2D, pub block_types: HashMap<String, (u32, u32)> } pub struct Chunk { blocks: [Block; 256], mesh: VAO, positions: VBO, tex_coords: VBO, indices: EBO, lightmap: Texture2D } impl Chunk { pub fn new() -> Self { let positions = VBO::new(vec![ VertexAttribute { index: 0, components: 2, }, ]); let tex_coords = VBO::new(vec![ VertexAttribute { index: 1, components: 2 }, ]); let indices = EBO::new(); Chunk { blocks: [Block::air(); 256], mesh: VAO::new(&[positions.clone(), tex_coords.clone()], Some(&indices)), positions, tex_coords, indices, // TODO Put length inside buffer lightmap: { let mut lightmap = Texture2D::new(); lightmap.allocate(TextureFormat::RGB, 16, 16, 1); lightmap } } } pub fn add_block(&mut self, x: u32, y: u32, block: Block) { self.blocks[(y * 16 + x) as usize] = block; // TODO Modify lightmap if it's a light source } pub fn remove_block(&mut self, x: u32, y: u32) { self.blocks[(y * 16 + x) as usize] = Block::air(); // TODO Regen lightmap if it's a light source } fn regen_mesh(&mut self) { let block_catalog = CONTAINER.get_local::<BlockCatalog>(); let mut vec_positions = Vec::<f32>::new(); let mut vec_tex_coords = Vec::<f32>::new(); let mut vec_indices = Vec::<u32>::new(); let mut i = 0; for y in 0..16 { for x in 0..16 { let block_id = self.blocks[16 * y + x].id; if block_id != "air" { let (tex_x, tex_y) = block_catalog.block_types.get(block_id).cloned().unwrap(); let (tex_x, tex_y) = (tex_x as f32 / 128.0, tex_y as f32 / 128.0); let (tex_w, tex_h) = (16.0 / 128.0, 16.0 / 128.0); println!("Regen i x y {} {} {}", i, x, y); let (tile, tex_coords, indices) = gen_tile( i as u32, x as f32, y as f32, 1.0, 1.0, tex_x, tex_y, tex_w, tex_h ); i += 1; vec_positions.extend_from_slice(&tile); vec_tex_coords.extend_from_slice(&tex_coords); vec_indices.extend_from_slice(&indices); } } } self.positions.with(&vec_positions, BufferUpdateFrequency::Never); self.tex_coords.with(&vec_tex_coords, BufferUpdateFrequency::Never); self.indices.with(&vec_indices, BufferUpdateFrequency::Never); // gl_call!(gl::NamedBufferData(self.positions.id, 4 * vec_positions.len() as isize, vec_positions.as_ptr() as *mut c_void, gl::STATIC_DRAW)); // gl_call!(gl::NamedBufferData(self.tex_coords.id, 4 * vec_tex_coords.len() as isize, vec_tex_coords.as_ptr() as *mut c_void, gl::STATIC_DRAW)); // gl_call!(gl::NamedBufferData(self.indices.id, 4 * vec_indices.len() as isize, vec_indices.as_ptr() as *mut c_void, gl::STATIC_DRAW)); } fn add_light_source(&mut self) { unimplemented!(); } fn remove_light_source(&mut self) { unimplemented!(); } } pub struct ResourceManager; impl ResourceManager { pub fn gen_blocks_texture_atlas(dir: &Path) -> BlockCatalog { let mut atlas = Texture2D::new(); let (atlas_width, atlas_height) = (128, 128); atlas.allocate(TextureFormat::RGBA, atlas_width, atlas_height, 1); let mut blocks = HashMap::new(); assert!(dir.is_dir()); println!("Entries:"); let mut x = 0; let mut y = 0; for entry in dir.read_dir().expect("Unable to read textures directory") { if let Ok(entry) = entry { if !entry.path().is_file() { continue; } assert!(y < atlas_height, "Texture atlas is full!"); // Update atlas let img = image::open(entry.path()); let img = match img { Ok(img) => img.flipv(), Err(err) => panic!("Could not open block texture image"), }; atlas.update(x, y, &img); // Save name and texture coordinates let block_name = entry.path().file_stem().unwrap().to_str().unwrap().to_owned(); blocks.insert(block_name, (x, y)); x += 16; if x / atlas_width > 0 { x %= atlas_width; y += 16 } } } for (key, value) in blocks.iter() { println!("Name: {}, tex: {},{}", key, value.0, value.1); } BlockCatalog { blocks_texture_atlas: atlas, block_types: blocks } } } pub struct VoxelWorld<'c> { chunk_size: (u32, u32), pub chunks: HashMap<(i32, i32), Chunk>, pub dirty_chunks: VecDeque<&'c mut Chunk> } impl<'c> VoxelWorld<'c> { pub fn new(chunk_size: (u32, u32)) -> Self { VoxelWorld { chunk_size, chunks: HashMap::new(), dirty_chunks: VecDeque::new() } } pub fn place_some_blocks(&mut self) { let blocks = CONTAINER.get_local::<BlockCatalog>(); let ids: Vec<&String> = blocks.block_types.keys().collect(); use rand::seq::SliceRandom; let mut rng = rand::thread_rng(); for xx in 0..7 { for yy in 0..7 { let mut chunk = Chunk::new(); for y in 0..self.chunk_size.1 { for x in 0..self.chunk_size.0 { chunk.add_block(x, y, Block { id: ids.choose(&mut rng).unwrap() }); } } chunk.remove_block(7, 7); chunk.remove_block(7, 8); chunk.remove_block(8, 8); chunk.regen_mesh(); self.chunks.insert((xx, yy), chunk); } } } fn get_chunk_and_block_coords(&self, x: i32, y: i32) -> (i32, i32, u32, u32) { ( x / self.chunk_size.0 as i32, y / self.chunk_size.1 as i32, (x % self.chunk_size.0 as i32) as u32, (y % self.chunk_size.1 as i32) as u32, ) } pub fn add_block(&'c mut self, x: i32, y: i32, block: Block) { let (x_chunk, y_chunk, x_block, y_block) = self.get_chunk_and_block_coords(x, y); let chunk = self.chunks.get_mut(&(x_chunk, y_chunk)); match chunk { Some(chunk) => { chunk.add_block(x_block, y_block, block); // Invalidate chunk // TODO check if the chunk is already in the list // maybe a hashset or hashmap? self.dirty_chunks.push_back(chunk); }, None => panic!("Inexistent chunk ({}, {})", x_chunk, y_chunk), } } pub fn remove_block(&'c mut self, x: i32, y: i32) { let (x_chunk, y_chunk, x_block, y_block) = self.get_chunk_and_block_coords(x, y); let chunk = self.chunks.get_mut(&(x_chunk, y_chunk)); match chunk { Some(chunk) => { chunk.remove_block(x_block, y_block); // Invalidate chunk self.dirty_chunks.push_back(chunk); }, None => panic!("Inexistent chunk ({}, {})", x_chunk, y_chunk), } } pub fn render(&mut self) { // Process invalidated chunks while let Some(chunk) = self.dirty_chunks.pop_front() { chunk.regen_mesh(); } let block_catalog = CONTAINER.get_local::<BlockCatalog>(); block_catalog.blocks_texture_atlas.activate(0); let shader = CONTAINER.get_local::<VoxelShader>(); shader.bind(); for (coords, chunk) in &self.chunks { chunk.mesh.bind(); shader.set_offset((coords.0 * 16, coords.1 * 16)); gl_call!(gl::DrawElements(gl::TRIANGLES, chunk.indices.len() as i32, gl::UNSIGNED_INT, std::ptr::null())); } // println!("LEN {}", self.chunk.indices_len); } } fn gen_tile( mut i: u32, x: f32, y: f32, width: f32, height: f32, tex_x: f32, tex_y: f32, tex_w: f32, tex_h: f32 ) -> ([f32; 8], [f32; 8], [u32; 6]) { let tile = [ x + width * 0.0f32, y + height * 0.0, x + width * 0.0, y + height * -1.0, x + width * 1.0, y + height * -1.0, x + width * 1.0, y + height * 0.0, ]; let tex_coords = [ tex_x, tex_y + tex_h, tex_x, tex_y, tex_x + tex_w, tex_y, tex_x + tex_w, tex_y + tex_h ]; i *= 4; let indices = [i + 0, i + 1, i + 2, i + 2, i + 3, i + 0]; (tile, tex_coords, indices) }
#[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::INTENCLR { #[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 = "Possible values of the field `USBRESET`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USBRESETR { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl USBRESETR { #[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 { USBRESETR::DISABLED => false, USBRESETR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> USBRESETR { match value { false => USBRESETR::DISABLED, true => USBRESETR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == USBRESETR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == USBRESETR::ENABLED } } #[doc = "Possible values of the field `STARTED`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum STARTEDR { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl STARTEDR { #[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 { STARTEDR::DISABLED => false, STARTEDR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> STARTEDR { match value { false => STARTEDR::DISABLED, true => STARTEDR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == STARTEDR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == STARTEDR::ENABLED } } #[doc = "Possible values of the field `ENDEPIN0`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPIN0R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPIN0R { #[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 { ENDEPIN0R::DISABLED => false, ENDEPIN0R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPIN0R { match value { false => ENDEPIN0R::DISABLED, true => ENDEPIN0R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPIN0R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPIN0R::ENABLED } } #[doc = "Possible values of the field `ENDEPIN1`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPIN1R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPIN1R { #[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 { ENDEPIN1R::DISABLED => false, ENDEPIN1R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPIN1R { match value { false => ENDEPIN1R::DISABLED, true => ENDEPIN1R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPIN1R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPIN1R::ENABLED } } #[doc = "Possible values of the field `ENDEPIN2`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPIN2R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPIN2R { #[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 { ENDEPIN2R::DISABLED => false, ENDEPIN2R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPIN2R { match value { false => ENDEPIN2R::DISABLED, true => ENDEPIN2R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPIN2R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPIN2R::ENABLED } } #[doc = "Possible values of the field `ENDEPIN3`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPIN3R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPIN3R { #[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 { ENDEPIN3R::DISABLED => false, ENDEPIN3R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPIN3R { match value { false => ENDEPIN3R::DISABLED, true => ENDEPIN3R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPIN3R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPIN3R::ENABLED } } #[doc = "Possible values of the field `ENDEPIN4`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPIN4R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPIN4R { #[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 { ENDEPIN4R::DISABLED => false, ENDEPIN4R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPIN4R { match value { false => ENDEPIN4R::DISABLED, true => ENDEPIN4R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPIN4R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPIN4R::ENABLED } } #[doc = "Possible values of the field `ENDEPIN5`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPIN5R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPIN5R { #[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 { ENDEPIN5R::DISABLED => false, ENDEPIN5R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPIN5R { match value { false => ENDEPIN5R::DISABLED, true => ENDEPIN5R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPIN5R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPIN5R::ENABLED } } #[doc = "Possible values of the field `ENDEPIN6`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPIN6R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPIN6R { #[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 { ENDEPIN6R::DISABLED => false, ENDEPIN6R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPIN6R { match value { false => ENDEPIN6R::DISABLED, true => ENDEPIN6R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPIN6R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPIN6R::ENABLED } } #[doc = "Possible values of the field `ENDEPIN7`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPIN7R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPIN7R { #[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 { ENDEPIN7R::DISABLED => false, ENDEPIN7R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPIN7R { match value { false => ENDEPIN7R::DISABLED, true => ENDEPIN7R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPIN7R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPIN7R::ENABLED } } #[doc = "Possible values of the field `EP0DATADONE`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EP0DATADONER { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl EP0DATADONER { #[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 { EP0DATADONER::DISABLED => false, EP0DATADONER::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> EP0DATADONER { match value { false => EP0DATADONER::DISABLED, true => EP0DATADONER::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == EP0DATADONER::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == EP0DATADONER::ENABLED } } #[doc = "Possible values of the field `ENDISOIN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDISOINR { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDISOINR { #[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 { ENDISOINR::DISABLED => false, ENDISOINR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDISOINR { match value { false => ENDISOINR::DISABLED, true => ENDISOINR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDISOINR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDISOINR::ENABLED } } #[doc = "Possible values of the field `ENDEPOUT0`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPOUT0R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPOUT0R { #[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 { ENDEPOUT0R::DISABLED => false, ENDEPOUT0R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPOUT0R { match value { false => ENDEPOUT0R::DISABLED, true => ENDEPOUT0R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPOUT0R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPOUT0R::ENABLED } } #[doc = "Possible values of the field `ENDEPOUT1`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPOUT1R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPOUT1R { #[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 { ENDEPOUT1R::DISABLED => false, ENDEPOUT1R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPOUT1R { match value { false => ENDEPOUT1R::DISABLED, true => ENDEPOUT1R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPOUT1R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPOUT1R::ENABLED } } #[doc = "Possible values of the field `ENDEPOUT2`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPOUT2R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPOUT2R { #[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 { ENDEPOUT2R::DISABLED => false, ENDEPOUT2R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPOUT2R { match value { false => ENDEPOUT2R::DISABLED, true => ENDEPOUT2R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPOUT2R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPOUT2R::ENABLED } } #[doc = "Possible values of the field `ENDEPOUT3`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPOUT3R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPOUT3R { #[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 { ENDEPOUT3R::DISABLED => false, ENDEPOUT3R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPOUT3R { match value { false => ENDEPOUT3R::DISABLED, true => ENDEPOUT3R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPOUT3R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPOUT3R::ENABLED } } #[doc = "Possible values of the field `ENDEPOUT4`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPOUT4R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPOUT4R { #[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 { ENDEPOUT4R::DISABLED => false, ENDEPOUT4R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPOUT4R { match value { false => ENDEPOUT4R::DISABLED, true => ENDEPOUT4R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPOUT4R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPOUT4R::ENABLED } } #[doc = "Possible values of the field `ENDEPOUT5`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPOUT5R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPOUT5R { #[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 { ENDEPOUT5R::DISABLED => false, ENDEPOUT5R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPOUT5R { match value { false => ENDEPOUT5R::DISABLED, true => ENDEPOUT5R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPOUT5R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPOUT5R::ENABLED } } #[doc = "Possible values of the field `ENDEPOUT6`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPOUT6R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPOUT6R { #[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 { ENDEPOUT6R::DISABLED => false, ENDEPOUT6R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPOUT6R { match value { false => ENDEPOUT6R::DISABLED, true => ENDEPOUT6R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPOUT6R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPOUT6R::ENABLED } } #[doc = "Possible values of the field `ENDEPOUT7`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDEPOUT7R { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDEPOUT7R { #[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 { ENDEPOUT7R::DISABLED => false, ENDEPOUT7R::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDEPOUT7R { match value { false => ENDEPOUT7R::DISABLED, true => ENDEPOUT7R::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDEPOUT7R::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDEPOUT7R::ENABLED } } #[doc = "Possible values of the field `ENDISOOUT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum ENDISOOUTR { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl ENDISOOUTR { #[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 { ENDISOOUTR::DISABLED => false, ENDISOOUTR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> ENDISOOUTR { match value { false => ENDISOOUTR::DISABLED, true => ENDISOOUTR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == ENDISOOUTR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == ENDISOOUTR::ENABLED } } #[doc = "Possible values of the field `SOF`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum SOFR { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl SOFR { #[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 { SOFR::DISABLED => false, SOFR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> SOFR { match value { false => SOFR::DISABLED, true => SOFR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == SOFR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == SOFR::ENABLED } } #[doc = "Possible values of the field `USBEVENT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum USBEVENTR { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl USBEVENTR { #[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 { USBEVENTR::DISABLED => false, USBEVENTR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> USBEVENTR { match value { false => USBEVENTR::DISABLED, true => USBEVENTR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == USBEVENTR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == USBEVENTR::ENABLED } } #[doc = "Possible values of the field `EP0SETUP`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EP0SETUPR { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl EP0SETUPR { #[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 { EP0SETUPR::DISABLED => false, EP0SETUPR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> EP0SETUPR { match value { false => EP0SETUPR::DISABLED, true => EP0SETUPR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == EP0SETUPR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == EP0SETUPR::ENABLED } } #[doc = "Possible values of the field `EPDATA`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum EPDATAR { #[doc = "Read: Disabled"] DISABLED, #[doc = "Read: Enabled"] ENABLED, } impl EPDATAR { #[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 { EPDATAR::DISABLED => false, EPDATAR::ENABLED => true, } } #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _from(value: bool) -> EPDATAR { match value { false => EPDATAR::DISABLED, true => EPDATAR::ENABLED, } } #[doc = "Checks if the value of the field is `DISABLED`"] #[inline] pub fn is_disabled(&self) -> bool { *self == EPDATAR::DISABLED } #[doc = "Checks if the value of the field is `ENABLED`"] #[inline] pub fn is_enabled(&self) -> bool { *self == EPDATAR::ENABLED } } #[doc = "Values that can be written to the field `USBRESET`"] pub enum USBRESETW { #[doc = "Disable"] CLEAR, } impl USBRESETW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { USBRESETW::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _USBRESETW<'a> { w: &'a mut W, } impl<'a> _USBRESETW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: USBRESETW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(USBRESETW::CLEAR) } #[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 = 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 `STARTED`"] pub enum STARTEDW { #[doc = "Disable"] CLEAR, } impl STARTEDW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { STARTEDW::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _STARTEDW<'a> { w: &'a mut W, } impl<'a> _STARTEDW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: STARTEDW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(STARTEDW::CLEAR) } #[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 = 1; 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 `ENDEPIN0`"] pub enum ENDEPIN0W { #[doc = "Disable"] CLEAR, } impl ENDEPIN0W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPIN0W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPIN0W<'a> { w: &'a mut W, } impl<'a> _ENDEPIN0W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPIN0W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPIN0W::CLEAR) } #[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 = 2; 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 `ENDEPIN1`"] pub enum ENDEPIN1W { #[doc = "Disable"] CLEAR, } impl ENDEPIN1W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPIN1W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPIN1W<'a> { w: &'a mut W, } impl<'a> _ENDEPIN1W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPIN1W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPIN1W::CLEAR) } #[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 = 3; 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 `ENDEPIN2`"] pub enum ENDEPIN2W { #[doc = "Disable"] CLEAR, } impl ENDEPIN2W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPIN2W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPIN2W<'a> { w: &'a mut W, } impl<'a> _ENDEPIN2W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPIN2W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPIN2W::CLEAR) } #[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 `ENDEPIN3`"] pub enum ENDEPIN3W { #[doc = "Disable"] CLEAR, } impl ENDEPIN3W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPIN3W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPIN3W<'a> { w: &'a mut W, } impl<'a> _ENDEPIN3W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPIN3W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPIN3W::CLEAR) } #[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 = "Values that can be written to the field `ENDEPIN4`"] pub enum ENDEPIN4W { #[doc = "Disable"] CLEAR, } impl ENDEPIN4W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPIN4W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPIN4W<'a> { w: &'a mut W, } impl<'a> _ENDEPIN4W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPIN4W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPIN4W::CLEAR) } #[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 = 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 `ENDEPIN5`"] pub enum ENDEPIN5W { #[doc = "Disable"] CLEAR, } impl ENDEPIN5W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPIN5W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPIN5W<'a> { w: &'a mut W, } impl<'a> _ENDEPIN5W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPIN5W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPIN5W::CLEAR) } #[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 = 7; 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 `ENDEPIN6`"] pub enum ENDEPIN6W { #[doc = "Disable"] CLEAR, } impl ENDEPIN6W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPIN6W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPIN6W<'a> { w: &'a mut W, } impl<'a> _ENDEPIN6W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPIN6W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPIN6W::CLEAR) } #[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 = 8; 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 `ENDEPIN7`"] pub enum ENDEPIN7W { #[doc = "Disable"] CLEAR, } impl ENDEPIN7W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPIN7W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPIN7W<'a> { w: &'a mut W, } impl<'a> _ENDEPIN7W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPIN7W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPIN7W::CLEAR) } #[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 = 9; 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 `EP0DATADONE`"] pub enum EP0DATADONEW { #[doc = "Disable"] CLEAR, } impl EP0DATADONEW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { EP0DATADONEW::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _EP0DATADONEW<'a> { w: &'a mut W, } impl<'a> _EP0DATADONEW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: EP0DATADONEW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(EP0DATADONEW::CLEAR) } #[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 = 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 `ENDISOIN`"] pub enum ENDISOINW { #[doc = "Disable"] CLEAR, } impl ENDISOINW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDISOINW::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDISOINW<'a> { w: &'a mut W, } impl<'a> _ENDISOINW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDISOINW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDISOINW::CLEAR) } #[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 = 11; 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 `ENDEPOUT0`"] pub enum ENDEPOUT0W { #[doc = "Disable"] CLEAR, } impl ENDEPOUT0W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPOUT0W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPOUT0W<'a> { w: &'a mut W, } impl<'a> _ENDEPOUT0W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPOUT0W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPOUT0W::CLEAR) } #[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 = 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 `ENDEPOUT1`"] pub enum ENDEPOUT1W { #[doc = "Disable"] CLEAR, } impl ENDEPOUT1W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPOUT1W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPOUT1W<'a> { w: &'a mut W, } impl<'a> _ENDEPOUT1W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPOUT1W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPOUT1W::CLEAR) } #[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 = 13; 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 `ENDEPOUT2`"] pub enum ENDEPOUT2W { #[doc = "Disable"] CLEAR, } impl ENDEPOUT2W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPOUT2W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPOUT2W<'a> { w: &'a mut W, } impl<'a> _ENDEPOUT2W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPOUT2W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPOUT2W::CLEAR) } #[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 = "Values that can be written to the field `ENDEPOUT3`"] pub enum ENDEPOUT3W { #[doc = "Disable"] CLEAR, } impl ENDEPOUT3W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPOUT3W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPOUT3W<'a> { w: &'a mut W, } impl<'a> _ENDEPOUT3W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPOUT3W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPOUT3W::CLEAR) } #[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 = 15; 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 `ENDEPOUT4`"] pub enum ENDEPOUT4W { #[doc = "Disable"] CLEAR, } impl ENDEPOUT4W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPOUT4W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPOUT4W<'a> { w: &'a mut W, } impl<'a> _ENDEPOUT4W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPOUT4W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPOUT4W::CLEAR) } #[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 = 16; 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 `ENDEPOUT5`"] pub enum ENDEPOUT5W { #[doc = "Disable"] CLEAR, } impl ENDEPOUT5W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPOUT5W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPOUT5W<'a> { w: &'a mut W, } impl<'a> _ENDEPOUT5W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPOUT5W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPOUT5W::CLEAR) } #[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 = 17; 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 `ENDEPOUT6`"] pub enum ENDEPOUT6W { #[doc = "Disable"] CLEAR, } impl ENDEPOUT6W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPOUT6W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPOUT6W<'a> { w: &'a mut W, } impl<'a> _ENDEPOUT6W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPOUT6W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPOUT6W::CLEAR) } #[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 = 18; 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 `ENDEPOUT7`"] pub enum ENDEPOUT7W { #[doc = "Disable"] CLEAR, } impl ENDEPOUT7W { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDEPOUT7W::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDEPOUT7W<'a> { w: &'a mut W, } impl<'a> _ENDEPOUT7W<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDEPOUT7W) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDEPOUT7W::CLEAR) } #[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 = 19; 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 `ENDISOOUT`"] pub enum ENDISOOUTW { #[doc = "Disable"] CLEAR, } impl ENDISOOUTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { ENDISOOUTW::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _ENDISOOUTW<'a> { w: &'a mut W, } impl<'a> _ENDISOOUTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: ENDISOOUTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(ENDISOOUTW::CLEAR) } #[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 `SOF`"] pub enum SOFW { #[doc = "Disable"] CLEAR, } impl SOFW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { SOFW::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _SOFW<'a> { w: &'a mut W, } impl<'a> _SOFW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: SOFW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(SOFW::CLEAR) } #[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 = 21; 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 `USBEVENT`"] pub enum USBEVENTW { #[doc = "Disable"] CLEAR, } impl USBEVENTW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { USBEVENTW::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _USBEVENTW<'a> { w: &'a mut W, } impl<'a> _USBEVENTW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: USBEVENTW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(USBEVENTW::CLEAR) } #[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 = 22; 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 `EP0SETUP`"] pub enum EP0SETUPW { #[doc = "Disable"] CLEAR, } impl EP0SETUPW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { EP0SETUPW::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _EP0SETUPW<'a> { w: &'a mut W, } impl<'a> _EP0SETUPW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: EP0SETUPW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(EP0SETUPW::CLEAR) } #[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 = 23; 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 `EPDATA`"] pub enum EPDATAW { #[doc = "Disable"] CLEAR, } impl EPDATAW { #[allow(missing_docs)] #[doc(hidden)] #[inline] pub fn _bits(&self) -> bool { match *self { EPDATAW::CLEAR => true, } } } #[doc = r" Proxy"] pub struct _EPDATAW<'a> { w: &'a mut W, } impl<'a> _EPDATAW<'a> { #[doc = r" Writes `variant` to the field"] #[inline] pub fn variant(self, variant: EPDATAW) -> &'a mut W { { self.bit(variant._bits()) } } #[doc = "Disable"] #[inline] pub fn clear(self) -> &'a mut W { self.variant(EPDATAW::CLEAR) } #[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 = 24; 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 = "Bit 0 - Write '1' to disable interrupt for USBRESET event"] #[inline] pub fn usbreset(&self) -> USBRESETR { USBRESETR::_from({ const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 1 - Write '1' to disable interrupt for STARTED event"] #[inline] pub fn started(&self) -> STARTEDR { STARTEDR::_from({ const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 2 - Write '1' to disable interrupt for ENDEPIN[0] event"] #[inline] pub fn endepin0(&self) -> ENDEPIN0R { ENDEPIN0R::_from({ const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 3 - Write '1' to disable interrupt for ENDEPIN[1] event"] #[inline] pub fn endepin1(&self) -> ENDEPIN1R { ENDEPIN1R::_from({ const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 4 - Write '1' to disable interrupt for ENDEPIN[2] event"] #[inline] pub fn endepin2(&self) -> ENDEPIN2R { ENDEPIN2R::_from({ const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 5 - Write '1' to disable interrupt for ENDEPIN[3] event"] #[inline] pub fn endepin3(&self) -> ENDEPIN3R { ENDEPIN3R::_from({ const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 6 - Write '1' to disable interrupt for ENDEPIN[4] event"] #[inline] pub fn endepin4(&self) -> ENDEPIN4R { ENDEPIN4R::_from({ const MASK: bool = true; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 7 - Write '1' to disable interrupt for ENDEPIN[5] event"] #[inline] pub fn endepin5(&self) -> ENDEPIN5R { ENDEPIN5R::_from({ const MASK: bool = true; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 8 - Write '1' to disable interrupt for ENDEPIN[6] event"] #[inline] pub fn endepin6(&self) -> ENDEPIN6R { ENDEPIN6R::_from({ const MASK: bool = true; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 9 - Write '1' to disable interrupt for ENDEPIN[7] event"] #[inline] pub fn endepin7(&self) -> ENDEPIN7R { ENDEPIN7R::_from({ const MASK: bool = true; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 10 - Write '1' to disable interrupt for EP0DATADONE event"] #[inline] pub fn ep0datadone(&self) -> EP0DATADONER { EP0DATADONER::_from({ const MASK: bool = true; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 11 - Write '1' to disable interrupt for ENDISOIN event"] #[inline] pub fn endisoin(&self) -> ENDISOINR { ENDISOINR::_from({ const MASK: bool = true; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 12 - Write '1' to disable interrupt for ENDEPOUT[0] event"] #[inline] pub fn endepout0(&self) -> ENDEPOUT0R { ENDEPOUT0R::_from({ const MASK: bool = true; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 13 - Write '1' to disable interrupt for ENDEPOUT[1] event"] #[inline] pub fn endepout1(&self) -> ENDEPOUT1R { ENDEPOUT1R::_from({ const MASK: bool = true; const OFFSET: u8 = 13; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 14 - Write '1' to disable interrupt for ENDEPOUT[2] event"] #[inline] pub fn endepout2(&self) -> ENDEPOUT2R { ENDEPOUT2R::_from({ const MASK: bool = true; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 15 - Write '1' to disable interrupt for ENDEPOUT[3] event"] #[inline] pub fn endepout3(&self) -> ENDEPOUT3R { ENDEPOUT3R::_from({ const MASK: bool = true; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 16 - Write '1' to disable interrupt for ENDEPOUT[4] event"] #[inline] pub fn endepout4(&self) -> ENDEPOUT4R { ENDEPOUT4R::_from({ const MASK: bool = true; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 17 - Write '1' to disable interrupt for ENDEPOUT[5] event"] #[inline] pub fn endepout5(&self) -> ENDEPOUT5R { ENDEPOUT5R::_from({ const MASK: bool = true; const OFFSET: u8 = 17; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 18 - Write '1' to disable interrupt for ENDEPOUT[6] event"] #[inline] pub fn endepout6(&self) -> ENDEPOUT6R { ENDEPOUT6R::_from({ const MASK: bool = true; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 19 - Write '1' to disable interrupt for ENDEPOUT[7] event"] #[inline] pub fn endepout7(&self) -> ENDEPOUT7R { ENDEPOUT7R::_from({ const MASK: bool = true; const OFFSET: u8 = 19; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 20 - Write '1' to disable interrupt for ENDISOOUT event"] #[inline] pub fn endisoout(&self) -> ENDISOOUTR { ENDISOOUTR::_from({ const MASK: bool = true; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 21 - Write '1' to disable interrupt for SOF event"] #[inline] pub fn sof(&self) -> SOFR { SOFR::_from({ const MASK: bool = true; const OFFSET: u8 = 21; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 22 - Write '1' to disable interrupt for USBEVENT event"] #[inline] pub fn usbevent(&self) -> USBEVENTR { USBEVENTR::_from({ const MASK: bool = true; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 23 - Write '1' to disable interrupt for EP0SETUP event"] #[inline] pub fn ep0setup(&self) -> EP0SETUPR { EP0SETUPR::_from({ const MASK: bool = true; const OFFSET: u8 = 23; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } #[doc = "Bit 24 - Write '1' to disable interrupt for EPDATA event"] #[inline] pub fn epdata(&self) -> EPDATAR { EPDATAR::_from({ const MASK: bool = true; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) != 0 }) } } 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 = "Bit 0 - Write '1' to disable interrupt for USBRESET event"] #[inline] pub fn usbreset(&mut self) -> _USBRESETW { _USBRESETW { w: self } } #[doc = "Bit 1 - Write '1' to disable interrupt for STARTED event"] #[inline] pub fn started(&mut self) -> _STARTEDW { _STARTEDW { w: self } } #[doc = "Bit 2 - Write '1' to disable interrupt for ENDEPIN[0] event"] #[inline] pub fn endepin0(&mut self) -> _ENDEPIN0W { _ENDEPIN0W { w: self } } #[doc = "Bit 3 - Write '1' to disable interrupt for ENDEPIN[1] event"] #[inline] pub fn endepin1(&mut self) -> _ENDEPIN1W { _ENDEPIN1W { w: self } } #[doc = "Bit 4 - Write '1' to disable interrupt for ENDEPIN[2] event"] #[inline] pub fn endepin2(&mut self) -> _ENDEPIN2W { _ENDEPIN2W { w: self } } #[doc = "Bit 5 - Write '1' to disable interrupt for ENDEPIN[3] event"] #[inline] pub fn endepin3(&mut self) -> _ENDEPIN3W { _ENDEPIN3W { w: self } } #[doc = "Bit 6 - Write '1' to disable interrupt for ENDEPIN[4] event"] #[inline] pub fn endepin4(&mut self) -> _ENDEPIN4W { _ENDEPIN4W { w: self } } #[doc = "Bit 7 - Write '1' to disable interrupt for ENDEPIN[5] event"] #[inline] pub fn endepin5(&mut self) -> _ENDEPIN5W { _ENDEPIN5W { w: self } } #[doc = "Bit 8 - Write '1' to disable interrupt for ENDEPIN[6] event"] #[inline] pub fn endepin6(&mut self) -> _ENDEPIN6W { _ENDEPIN6W { w: self } } #[doc = "Bit 9 - Write '1' to disable interrupt for ENDEPIN[7] event"] #[inline] pub fn endepin7(&mut self) -> _ENDEPIN7W { _ENDEPIN7W { w: self } } #[doc = "Bit 10 - Write '1' to disable interrupt for EP0DATADONE event"] #[inline] pub fn ep0datadone(&mut self) -> _EP0DATADONEW { _EP0DATADONEW { w: self } } #[doc = "Bit 11 - Write '1' to disable interrupt for ENDISOIN event"] #[inline] pub fn endisoin(&mut self) -> _ENDISOINW { _ENDISOINW { w: self } } #[doc = "Bit 12 - Write '1' to disable interrupt for ENDEPOUT[0] event"] #[inline] pub fn endepout0(&mut self) -> _ENDEPOUT0W { _ENDEPOUT0W { w: self } } #[doc = "Bit 13 - Write '1' to disable interrupt for ENDEPOUT[1] event"] #[inline] pub fn endepout1(&mut self) -> _ENDEPOUT1W { _ENDEPOUT1W { w: self } } #[doc = "Bit 14 - Write '1' to disable interrupt for ENDEPOUT[2] event"] #[inline] pub fn endepout2(&mut self) -> _ENDEPOUT2W { _ENDEPOUT2W { w: self } } #[doc = "Bit 15 - Write '1' to disable interrupt for ENDEPOUT[3] event"] #[inline] pub fn endepout3(&mut self) -> _ENDEPOUT3W { _ENDEPOUT3W { w: self } } #[doc = "Bit 16 - Write '1' to disable interrupt for ENDEPOUT[4] event"] #[inline] pub fn endepout4(&mut self) -> _ENDEPOUT4W { _ENDEPOUT4W { w: self } } #[doc = "Bit 17 - Write '1' to disable interrupt for ENDEPOUT[5] event"] #[inline] pub fn endepout5(&mut self) -> _ENDEPOUT5W { _ENDEPOUT5W { w: self } } #[doc = "Bit 18 - Write '1' to disable interrupt for ENDEPOUT[6] event"] #[inline] pub fn endepout6(&mut self) -> _ENDEPOUT6W { _ENDEPOUT6W { w: self } } #[doc = "Bit 19 - Write '1' to disable interrupt for ENDEPOUT[7] event"] #[inline] pub fn endepout7(&mut self) -> _ENDEPOUT7W { _ENDEPOUT7W { w: self } } #[doc = "Bit 20 - Write '1' to disable interrupt for ENDISOOUT event"] #[inline] pub fn endisoout(&mut self) -> _ENDISOOUTW { _ENDISOOUTW { w: self } } #[doc = "Bit 21 - Write '1' to disable interrupt for SOF event"] #[inline] pub fn sof(&mut self) -> _SOFW { _SOFW { w: self } } #[doc = "Bit 22 - Write '1' to disable interrupt for USBEVENT event"] #[inline] pub fn usbevent(&mut self) -> _USBEVENTW { _USBEVENTW { w: self } } #[doc = "Bit 23 - Write '1' to disable interrupt for EP0SETUP event"] #[inline] pub fn ep0setup(&mut self) -> _EP0SETUPW { _EP0SETUPW { w: self } } #[doc = "Bit 24 - Write '1' to disable interrupt for EPDATA event"] #[inline] pub fn epdata(&mut self) -> _EPDATAW { _EPDATAW { w: self } } }
use std::fs; use std::thread; use std::path::Path; use std::collections::HashMap; use std::io::{Read, Write, Error}; use std::sync::{Arc, Mutex, RwLock}; use std::os::unix::net::{UnixStream, UnixListener}; use std::net::Shutdown; use secret_integers::*; use simple::*; pub mod simple; use serde::{Serialize, Deserialize}; pub static SOCKET_PATH: &'static str = "/tmp/loopback-socket"; #[derive(Serialize, Deserialize, Debug)] pub enum MyRequest { ReqGetSecretKey, ReqEncrypt { plaintext: Vec<u8>, keyid: u64, }, ReqDecrypt { ciphertext: Vec<u8>, keyid: u64, } } #[derive(Serialize, Deserialize, Debug)] pub enum MyResponse { ResGetSecretKey { keyid: u64, }, ResEncrypt { ciphertext: Vec<u8>, }, ResDecrypt { plaintext: Vec<u8>, } } fn handle_client(mut stream: UnixStream, child_arc_keys_map: Arc<RwLock<HashMap<u64, Vec<U8>>>>, child_arc_counter: Arc<Mutex<u64>>) -> Result<(), Error> { let mut buf = [0; 4096]; // Need to check how to do it with Vectors let bytes_read = stream.read(&mut buf)?; if bytes_read == 0 {return Ok(())} if let Ok(request) = std::str::from_utf8(&buf[..bytes_read]) { let request: MyRequest = serde_json::from_str(&request).unwrap(); // GenSecretKey if let MyRequest::ReqGetSecretKey = request { if let Ok(mut write_guard) = child_arc_keys_map.write() { let mut num = child_arc_counter.lock().unwrap(); *num += 1; write_guard.insert(*num, get_secret_key()); let response = MyResponse::ResGetSecretKey{ keyid: *num}; let response_string = serde_json::to_string(&response).unwrap(); stream.write_all(response_string.as_bytes()).expect("IO Error"); stream.shutdown(Shutdown::Both).expect("shutdown function failed"); } } // Encrypt if let MyRequest::ReqEncrypt{ref plaintext, keyid} = request { if let Ok(read_guard) = child_arc_keys_map.read() { if read_guard.contains_key(&keyid) { let sk = &read_guard[&keyid]; let new_block = encrypt(&plaintext, &sk); let response = MyResponse::ResEncrypt{ ciphertext: new_block}; let response_string = serde_json::to_string(&response).unwrap(); stream.write_all(response_string.as_bytes()).expect("IO Error"); stream.shutdown(Shutdown::Both).expect("shutdown function failed"); } } } // Decrypt if let MyRequest::ReqDecrypt{ ciphertext, keyid} = request { if let Ok(read_guard) = child_arc_keys_map.read() { if read_guard.contains_key(&keyid) { let sk = &read_guard[&keyid]; let new_block = decrypt(&ciphertext, &sk); let response = MyResponse::ResDecrypt{ plaintext: new_block}; let response_string = serde_json::to_string(&response).unwrap(); stream.write_all(response_string.as_bytes()).expect("IO Error"); stream.shutdown(Shutdown::Both).expect("shutdown function failed"); } } } } return Ok(()); } fn main() { println!("Hello World"); let socket = Path::new(SOCKET_PATH); let mut children = vec![]; let keys_map: HashMap<u64, Vec<U8>> = HashMap::new(); let arc_keys_map = Arc::new(RwLock::new(keys_map)); let counter: u64 = 0; let arc_counter = Arc::new(Mutex::new(counter)); // Delete old socket if necessary if socket.exists() { fs::remove_file(&socket).unwrap(); } let listener = UnixListener::bind(&socket).unwrap(); for stream in listener.incoming() { // Returns a stream of incoming connections. // Iterating over this stream is equivalent to calling accept in a loop match stream { Ok(stream) => { println!("got connection request"); let child_arc_keys_map = arc_keys_map.clone(); let child_arc_counter = arc_counter.clone(); children.push(thread::spawn(move || handle_client(stream, child_arc_keys_map, child_arc_counter))); } Err(err) => { println!("Error: {}", err); break; } } } for child in children { let _ = child.join(); } }
#[test] fn ejemplo_j1_loc() { assert_cli::Assert::main_binary() .with_args(&["-c", "test_data/ejemploJ1_base.csv", "-l", "PENINSULA"]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 41.4, nren = 195.4, tot = 236.8") .stdout() .contains("RER = 0.17") .unwrap(); } #[test] fn ejemplo_j1() { assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ1_base.csv", "-f", "test_data/factores_paso_test.csv", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 50.0, nren = 200.0, tot = 250.0") .stdout() .contains("RER = 0.20") .unwrap(); } #[test] fn ejemplo_j2() { assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ2_basePV.csv", "-f", "test_data/factores_paso_test.csv", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 75.0, nren = 100.0, tot = 175.0") .stdout() .contains("RER = 0.43") .unwrap(); } #[test] fn ejemplo_j3() { assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ3_basePVexcess.csv", "-f", "test_data/factores_paso_test.csv", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 100.0, nren = 0.0, tot = 100.0") .stdout() .contains("RER = 1.00") .unwrap(); } #[test] fn ejemplo_j5() { assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ5_gasPV.csv", "-f", "test_data/factores_paso_test.csv", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 20.0, nren = 209.0, tot = 229.0") .stdout() .contains("RER = 0.09") .unwrap(); } #[test] fn ejemplo_j6() { assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ6_HPPV.csv", "-f", "test_data/factores_paso_test.csv", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 180.5, nren = 38.0, tot = 218.5") .stdout() .contains("RER = 0.83") .unwrap(); } #[test] fn ejemplo_j7() { // Step A assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ7_cogenfuelgasboiler.csv", "-f", "test_data/factores_paso_test.csv", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 0.0, nren = 214.5, tot = 214.5") .stdout() .contains("RER = 0.0") .unwrap(); // Step B, kexp=1 assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ7_cogenfuelgasboiler.csv", "-f", "test_data/factores_paso_test.csv", "--kexp", "1.0", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = -14.0, nren = 227.8, tot = 213.8") .stdout() .contains("RER = -0.07") .stdout() .contains("RER_nrb = 0.00") .unwrap(); } #[test] fn ejemplo_j8() { // Step A assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ8_cogenbiogasboiler.csv", "-f", "test_data/factores_paso_test.csv", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 95.0, nren = 119.5, tot = 214.5") .stdout() .contains("RER = 0.44") .stdout() .contains("RER_nrb = 0.44") .unwrap(); // Step B assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ8_cogenbiogasboiler.csv", "-f", "test_data/factores_paso_test.csv", "--kexp", "1.0", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 144.0, nren = 69.8, tot = 213.8") .stdout() .contains("RER = 0.67") .stdout() .contains("RER_nrb = 0.74") .unwrap(); } #[test] fn ejemplo_j9() { assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/ejemploJ9_electr.csv", "-f", "test_data/factores_paso_test.csv", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 1009.5, nren = 842.0, tot = 1851.5") .stdout() .contains("RER = 0.55") .unwrap(); } #[test] fn ejemplo_testcarriers() { assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/cte_test_carriers.csv", "-f", "test_data/factores_paso_test.csv", ]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 25.4, nren = 19.4, tot = 44.8") .stdout() .contains("RER = 0.57") .unwrap(); } #[test] fn ejemplo_testcarriers_loc() { assert_cli::Assert::main_binary() .with_args(&["-c", "test_data/cte_test_carriers.csv", "-l", "PENINSULA"]) .stdout() .contains("C_ep [kWh/m2.an]: ren = 24.6, nren = 18.9, tot = 43.5") .stdout() .contains("RER = 0.57") .unwrap(); } #[test] fn ejemplo_acs_demanda_ren_con_nepb() { assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/acs_demanda_ren_con_nepb.csv", "-l", "PENINSULA", ]) .stdout() .contains("Porcentaje renovable de la demanda de ACS (perímetro próximo): 77.3 [%]") .stdout() .contains("* generada y usada en servicios EPB, por origen:\n- EAMBIENTE: 26.00\n- EL_INSITU: 4.45") .unwrap(); assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/acs_demanda_ren_con_nepb.csv", "-l", "PENINSULA", "--load_matching" ]) .stdout() .contains("* generada y usada en servicios EPB, por origen:\n- EAMBIENTE: 13.00\n- EL_INSITU: 2.92") .unwrap(); } #[test] fn ejemplo_acs_demanda_ren_con_nepb_con_exclusion_aux() { assert_cli::Assert::main_binary() .with_args(&[ "-c", "test_data/acs_demanda_ren_con_exclusion_auxiliares.csv", "-l", "PENINSULA" ]) .stdout() .contains("Porcentaje renovable de la demanda de ACS (perímetro próximo): 96.7 [%]") .unwrap(); }
use std::io; use ash::vk; use ash::prelude::VkResult; use ash::version::DeviceV1_0; pub fn find_memorytype_index( memory_req: &vk::MemoryRequirements, memory_prop: &vk::PhysicalDeviceMemoryProperties, required_property_flags: vk::MemoryPropertyFlags, ) -> Option<u32> { for (index, ref memory_type) in memory_prop.memory_types.iter().enumerate() { let type_supported = (memory_req.memory_type_bits & (1<<index)) != 0; let flags_supported = (memory_type.property_flags & required_property_flags) == required_property_flags; if type_supported && flags_supported { return Some(index as u32); } } None } pub fn read_spv<R: io::Read + io::Seek>(x: &mut R) -> io::Result<Vec<u32>> { let size = x.seek(io::SeekFrom::End(0))?; if size % 4 != 0 { return Err(io::Error::new( io::ErrorKind::InvalidData, "input length not divisible by 4", )); } if size > usize::max_value() as u64 { return Err(io::Error::new(io::ErrorKind::InvalidData, "input too long")); } let words = (size / 4) as usize; let mut result = Vec::<u32>::with_capacity(words); x.seek(io::SeekFrom::Start(0))?; unsafe { x.read_exact(std::slice::from_raw_parts_mut( result.as_mut_ptr() as *mut u8, words * 4, ))?; result.set_len(words); } const MAGIC_NUMBER: u32 = 0x0723_0203; if result.len() > 0 && result[0] == MAGIC_NUMBER.swap_bytes() { for word in &mut result { *word = word.swap_bytes(); } } if result.len() == 0 || result[0] != MAGIC_NUMBER { return Err(io::Error::new( io::ErrorKind::InvalidData, "input missing SPIR-V magic number", )); } Ok(result) } pub fn submit_single_use_command_buffer<F : Fn(&vk::CommandBuffer)>( logical_device: &ash::Device, queue: &vk::Queue, command_pool: &vk::CommandPool, f: F ) -> VkResult<()> { let alloc_info = vk::CommandBufferAllocateInfo::builder() .level(vk::CommandBufferLevel::PRIMARY) .command_pool(*command_pool) .command_buffer_count(1); let begin_info = vk::CommandBufferBeginInfo::builder() .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT); let command_buffer = unsafe { let command_buffer = logical_device.allocate_command_buffers(&alloc_info)?[0]; logical_device.begin_command_buffer(command_buffer, &begin_info)?; f(&command_buffer); logical_device.end_command_buffer(command_buffer)?; command_buffer }; let command_buffers = [command_buffer]; let submit_info = vk::SubmitInfo::builder() .command_buffers(&command_buffers); unsafe { logical_device.queue_submit(*queue, &[submit_info.build()], vk::Fence::null())?; logical_device.device_wait_idle()?; logical_device.free_command_buffers(*command_pool, &command_buffers); } Ok(()) } /* pub fn transition_image_layout( logical_device: &ash::Device, queue: &vk::Queue, command_pool: &vk::CommandPool, image: &vk::Image, _format: vk::Format, old_layout: vk::ImageLayout, new_layout: vk::ImageLayout ) { super::util::submit_single_use_command_buffer(logical_device, queue, command_pool, |command_buffer| { struct SyncInfo { src_access_mask: vk::AccessFlags, dst_access_mask: vk::AccessFlags, src_stage: vk::PipelineStageFlags, dst_stage: vk::PipelineStageFlags, } let sync_info = match (old_layout, new_layout) { (vk::ImageLayout::UNDEFINED, vk::ImageLayout::TRANSFER_DST_OPTIMAL) => { SyncInfo { src_access_mask: vk::AccessFlags::empty(), dst_access_mask: vk::AccessFlags::TRANSFER_WRITE, src_stage: vk::PipelineStageFlags::TOP_OF_PIPE, dst_stage: vk::PipelineStageFlags::TRANSFER, } }, (vk::ImageLayout::TRANSFER_DST_OPTIMAL, vk::ImageLayout::SHADER_READ_ONLY_OPTIMAL) => { SyncInfo { src_access_mask: vk::AccessFlags::TRANSFER_WRITE, dst_access_mask: vk::AccessFlags::SHADER_READ, src_stage: vk::PipelineStageFlags::TRANSFER, dst_stage: vk::PipelineStageFlags::FRAGMENT_SHADER, } }, _ => { // Layout transition not yet supported unimplemented!(); } }; let subresource_range = vk::ImageSubresourceRange::builder() .aspect_mask(vk::ImageAspectFlags::COLOR) .base_mip_level(0) .level_count(1) .base_array_layer(0) .layer_count(1); let barrier_info = vk::ImageMemoryBarrier::builder() .old_layout(old_layout) .new_layout(new_layout) .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED) .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED) .image(*image) .subresource_range(*subresource_range) .src_access_mask(sync_info.src_access_mask) .dst_access_mask(sync_info.dst_access_mask); unsafe { logical_device.cmd_pipeline_barrier( *command_buffer, sync_info.src_stage, sync_info.dst_stage, vk::DependencyFlags::BY_REGION, &[], &[], &[*barrier_info]); //TODO: Can remove build() by using *? } }); } */ /* pub fn copy_buffer_to_image( logical_device: &ash::Device, queue: &vk::Queue, command_pool: &vk::CommandPool, buffer: &vk::Buffer, image: &vk::Image, extent: &vk::Extent3D ) { super::util::submit_single_use_command_buffer(logical_device, queue, command_pool, |command_buffer| { let image_subresource = vk::ImageSubresourceLayers::builder() .aspect_mask(vk::ImageAspectFlags::COLOR) .mip_level(0) .base_array_layer(0) .layer_count(1); let image_copy = vk::BufferImageCopy::builder() .buffer_offset(0) .buffer_row_length(0) .buffer_image_height(0) .image_subresource(*image_subresource) .image_offset(vk::Offset3D { x: 0, y: 0, z: 0 }) .image_extent(*extent); unsafe { logical_device.cmd_copy_buffer_to_image( *command_buffer, *buffer, *image, vk::ImageLayout::TRANSFER_DST_OPTIMAL, &[*image_copy] ); } }); } */
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[repr(transparent)] #[doc(hidden)] pub struct IXamlDirect(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXamlDirect { type Vtable = IXamlDirect_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5ffa1295_add2_590f_a051_70989b866ade); } #[repr(C)] #[doc(hidden)] pub struct IXamlDirect_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, xamldirectobject: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, object: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, typeindex: XamlTypeIndex, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::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, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::super::super::Foundation::Point) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::super::super::Foundation::Size) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::super::Color) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::CornerRadius) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::Duration) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::GridLength) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::Thickness) -> ::windows::core::HRESULT, #[cfg(feature = "UI_Xaml_Media")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::Media::Matrix) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Media"))] usize, #[cfg(feature = "UI_Xaml_Media_Media3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: super::super::Media::Media3D::Matrix3D) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Media_Media3D"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, value: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut f64) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut ::core::mem::ManuallyDrop<::windows::core::HSTRING>) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::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, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::super::super::Foundation::Point) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::super::super::Foundation::Rect) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::super::super::Foundation::Size) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::super::super::Foundation::TimeSpan) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::super::Color) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::CornerRadius) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::Duration) -> ::windows::core::HRESULT, #[cfg(not(feature = "Foundation"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::GridLength) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::Thickness) -> ::windows::core::HRESULT, #[cfg(feature = "UI_Xaml_Media")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::Media::Matrix) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Media"))] usize, #[cfg(feature = "UI_Xaml_Media_Media3D")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut super::super::Media::Media3D::Matrix3D) -> ::windows::core::HRESULT, #[cfg(not(feature = "UI_Xaml_Media_Media3D"))] usize, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, propertyindex: XamlPropertyIndex) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, result__: *mut u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, index: u32, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, index: u32, value: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, value: ::windows::core::RawPtr, result__: *mut bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, index: u32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, eventindex: XamlEventIndex, handler: ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, eventindex: XamlEventIndex, handler: ::windows::core::RawPtr, handledeventstoo: bool) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, xamldirectobject: ::windows::core::RawPtr, eventindex: XamlEventIndex, handler: ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct IXamlDirectObject(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXamlDirectObject { type Vtable = IXamlDirectObject_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x10614a82_cee4_4645_ba25_d071ce778355); } impl IXamlDirectObject {} unsafe impl ::windows::core::RuntimeType for IXamlDirectObject { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"{10614a82-cee4-4645-ba25-d071ce778355}"); } impl ::core::convert::From<IXamlDirectObject> for ::windows::core::IUnknown { fn from(value: IXamlDirectObject) -> Self { value.0 .0 } } impl ::core::convert::From<&IXamlDirectObject> for ::windows::core::IUnknown { fn from(value: &IXamlDirectObject) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for IXamlDirectObject { 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 IXamlDirectObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<IXamlDirectObject> for ::windows::core::IInspectable { fn from(value: IXamlDirectObject) -> Self { value.0 } } impl ::core::convert::From<&IXamlDirectObject> for ::windows::core::IInspectable { fn from(value: &IXamlDirectObject) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for IXamlDirectObject { 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 IXamlDirectObject { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } #[repr(C)] #[doc(hidden)] pub struct IXamlDirectObject_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IXamlDirectStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IXamlDirectStatics { type Vtable = IXamlDirectStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x321887cc_14e4_5c6f_878d_fbb604ad7d17); } #[repr(C)] #[doc(hidden)] pub struct IXamlDirectStatics_abi( pub unsafe extern "system" fn(this: ::windows::core::RawPtr, iid: &::windows::core::GUID, interface: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr) -> u32, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, count: *mut u32, values: *mut *mut ::windows::core::GUID) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, value: *mut i32) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, result__: *mut ::windows::core::RawPtr) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct XamlDirect(pub ::windows::core::IInspectable); impl XamlDirect { pub fn GetObject<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0) -> ::windows::core::Result<::windows::core::IInspectable> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), &mut result__).from_abi::<::windows::core::IInspectable>(result__) } } pub fn GetXamlDirectObject<'a, Param0: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, object: Param0) -> ::windows::core::Result<IXamlDirectObject> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), object.into_param().abi(), &mut result__).from_abi::<IXamlDirectObject>(result__) } } pub fn CreateInstance(&self, typeindex: XamlTypeIndex) -> ::windows::core::Result<IXamlDirectObject> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).8)(::core::mem::transmute_copy(this), typeindex, &mut result__).from_abi::<IXamlDirectObject>(result__) } } pub fn SetObjectProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).9)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } pub fn SetXamlDirectObjectProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } pub fn SetBooleanProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).11)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value).ok() } } pub fn SetDoubleProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: f64) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).12)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value).ok() } } pub fn SetInt32Property<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: i32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).13)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value).ok() } } pub fn SetStringProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, ::windows::core::HSTRING>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).14)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn SetDateTimeProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::DateTime>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).15)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn SetPointProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Point>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).16)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn SetRectProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Rect>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).17)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn SetSizeProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::Size>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).18)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn SetTimeSpanProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::super::super::Foundation::TimeSpan>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).19)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } pub fn SetColorProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::super::Color>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).20)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } pub fn SetCornerRadiusProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::CornerRadius>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).21)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } #[cfg(feature = "Foundation")] pub fn SetDurationProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::Duration>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).22)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } pub fn SetGridLengthProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::GridLength>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).23)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } pub fn SetThicknessProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::Thickness>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).24)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } #[cfg(feature = "UI_Xaml_Media")] pub fn SetMatrixProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::Media::Matrix>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).25)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } #[cfg(feature = "UI_Xaml_Media_Media3D")] pub fn SetMatrix3DProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, super::super::Media::Media3D::Matrix3D>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).26)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value.into_param().abi()).ok() } } pub fn SetEnumProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex, value: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).27)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, value).ok() } } pub fn GetObjectProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<::windows::core::IInspectable> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).28)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<::windows::core::IInspectable>(result__) } } pub fn GetXamlDirectObjectProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<IXamlDirectObject> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).29)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<IXamlDirectObject>(result__) } } pub fn GetBooleanProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).30)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<bool>(result__) } } pub fn GetDoubleProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<f64> { let this = self; unsafe { let mut result__: f64 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).31)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<f64>(result__) } } pub fn GetInt32Property<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<i32> { let this = self; unsafe { let mut result__: i32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).32)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<i32>(result__) } } pub fn GetStringProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::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).33)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<::windows::core::HSTRING>(result__) } } #[cfg(feature = "Foundation")] pub fn GetDateTimeProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::super::super::Foundation::DateTime> { let this = self; unsafe { let mut result__: super::super::super::super::Foundation::DateTime = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).34)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::super::super::Foundation::DateTime>(result__) } } #[cfg(feature = "Foundation")] pub fn GetPointProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::super::super::Foundation::Point> { let this = self; unsafe { let mut result__: super::super::super::super::Foundation::Point = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).35)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::super::super::Foundation::Point>(result__) } } #[cfg(feature = "Foundation")] pub fn GetRectProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::super::super::Foundation::Rect> { let this = self; unsafe { let mut result__: super::super::super::super::Foundation::Rect = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).36)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::super::super::Foundation::Rect>(result__) } } #[cfg(feature = "Foundation")] pub fn GetSizeProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::super::super::Foundation::Size> { let this = self; unsafe { let mut result__: super::super::super::super::Foundation::Size = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).37)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::super::super::Foundation::Size>(result__) } } #[cfg(feature = "Foundation")] pub fn GetTimeSpanProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::super::super::Foundation::TimeSpan> { let this = self; unsafe { let mut result__: super::super::super::super::Foundation::TimeSpan = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).38)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::super::super::Foundation::TimeSpan>(result__) } } pub fn GetColorProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::super::Color> { let this = self; unsafe { let mut result__: super::super::super::Color = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).39)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::super::Color>(result__) } } pub fn GetCornerRadiusProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::CornerRadius> { let this = self; unsafe { let mut result__: super::super::CornerRadius = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).40)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::CornerRadius>(result__) } } #[cfg(feature = "Foundation")] pub fn GetDurationProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::Duration> { let this = self; unsafe { let mut result__: super::super::Duration = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).41)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::Duration>(result__) } } pub fn GetGridLengthProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::GridLength> { let this = self; unsafe { let mut result__: super::super::GridLength = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).42)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::GridLength>(result__) } } pub fn GetThicknessProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::Thickness> { let this = self; unsafe { let mut result__: super::super::Thickness = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).43)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::Thickness>(result__) } } #[cfg(feature = "UI_Xaml_Media")] pub fn GetMatrixProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::Media::Matrix> { let this = self; unsafe { let mut result__: super::super::Media::Matrix = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).44)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::Media::Matrix>(result__) } } #[cfg(feature = "UI_Xaml_Media_Media3D")] pub fn GetMatrix3DProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<super::super::Media::Media3D::Matrix3D> { let this = self; unsafe { let mut result__: super::super::Media::Media3D::Matrix3D = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).45)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<super::super::Media::Media3D::Matrix3D>(result__) } } pub fn GetEnumProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).46)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex, &mut result__).from_abi::<u32>(result__) } } pub fn ClearProperty<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, propertyindex: XamlPropertyIndex) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).47)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), propertyindex).ok() } } pub fn GetCollectionCount<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0) -> ::windows::core::Result<u32> { let this = self; unsafe { let mut result__: u32 = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).48)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), &mut result__).from_abi::<u32>(result__) } } pub fn GetXamlDirectObjectFromCollectionAt<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, index: u32) -> ::windows::core::Result<IXamlDirectObject> { let this = self; unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).49)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), index, &mut result__).from_abi::<IXamlDirectObject>(result__) } } pub fn AddToCollection<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param1: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, value: Param1) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).50)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), value.into_param().abi()).ok() } } pub fn InsertIntoCollectionAt<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, index: u32, value: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).51)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), index, value.into_param().abi()).ok() } } pub fn RemoveFromCollection<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param1: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, value: Param1) -> ::windows::core::Result<bool> { let this = self; unsafe { let mut result__: bool = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).52)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), value.into_param().abi(), &mut result__).from_abi::<bool>(result__) } } pub fn RemoveFromCollectionAt<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0, index: u32) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).53)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), index).ok() } } pub fn ClearCollection<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>>(&self, xamldirectobject: Param0) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).54)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi()).ok() } } pub fn AddEventHandler<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, xamldirectobject: Param0, eventindex: XamlEventIndex, handler: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).55)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), eventindex, handler.into_param().abi()).ok() } } pub fn AddEventHandler_HandledEventsToo<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, xamldirectobject: Param0, eventindex: XamlEventIndex, handler: Param2, handledeventstoo: bool) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).56)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), eventindex, handler.into_param().abi(), handledeventstoo).ok() } } pub fn RemoveEventHandler<'a, Param0: ::windows::core::IntoParam<'a, IXamlDirectObject>, Param2: ::windows::core::IntoParam<'a, ::windows::core::IInspectable>>(&self, xamldirectobject: Param0, eventindex: XamlEventIndex, handler: Param2) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).57)(::core::mem::transmute_copy(this), xamldirectobject.into_param().abi(), eventindex, handler.into_param().abi()).ok() } } pub fn GetDefault() -> ::windows::core::Result<XamlDirect> { Self::IXamlDirectStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<XamlDirect>(result__) }) } pub fn IXamlDirectStatics<R, F: FnOnce(&IXamlDirectStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<XamlDirect, IXamlDirectStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for XamlDirect { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.UI.Xaml.Core.Direct.XamlDirect;{5ffa1295-add2-590f-a051-70989b866ade})"); } unsafe impl ::windows::core::Interface for XamlDirect { type Vtable = IXamlDirect_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x5ffa1295_add2_590f_a051_70989b866ade); } impl ::windows::core::RuntimeName for XamlDirect { const NAME: &'static str = "Windows.UI.Xaml.Core.Direct.XamlDirect"; } impl ::core::convert::From<XamlDirect> for ::windows::core::IUnknown { fn from(value: XamlDirect) -> Self { value.0 .0 } } impl ::core::convert::From<&XamlDirect> for ::windows::core::IUnknown { fn from(value: &XamlDirect) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for XamlDirect { 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 XamlDirect { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<XamlDirect> for ::windows::core::IInspectable { fn from(value: XamlDirect) -> Self { value.0 } } impl ::core::convert::From<&XamlDirect> for ::windows::core::IInspectable { fn from(value: &XamlDirect) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for XamlDirect { 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 XamlDirect { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for XamlDirect {} unsafe impl ::core::marker::Sync for XamlDirect {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XamlEventIndex(pub i32); impl XamlEventIndex { pub const FrameworkElement_DataContextChanged: XamlEventIndex = XamlEventIndex(16i32); pub const FrameworkElement_SizeChanged: XamlEventIndex = XamlEventIndex(17i32); pub const FrameworkElement_LayoutUpdated: XamlEventIndex = XamlEventIndex(18i32); pub const UIElement_KeyUp: XamlEventIndex = XamlEventIndex(22i32); pub const UIElement_KeyDown: XamlEventIndex = XamlEventIndex(23i32); pub const UIElement_GotFocus: XamlEventIndex = XamlEventIndex(24i32); pub const UIElement_LostFocus: XamlEventIndex = XamlEventIndex(25i32); pub const UIElement_DragStarting: XamlEventIndex = XamlEventIndex(26i32); pub const UIElement_DropCompleted: XamlEventIndex = XamlEventIndex(27i32); pub const UIElement_CharacterReceived: XamlEventIndex = XamlEventIndex(28i32); pub const UIElement_DragEnter: XamlEventIndex = XamlEventIndex(29i32); pub const UIElement_DragLeave: XamlEventIndex = XamlEventIndex(30i32); pub const UIElement_DragOver: XamlEventIndex = XamlEventIndex(31i32); pub const UIElement_Drop: XamlEventIndex = XamlEventIndex(32i32); pub const UIElement_PointerPressed: XamlEventIndex = XamlEventIndex(38i32); pub const UIElement_PointerMoved: XamlEventIndex = XamlEventIndex(39i32); pub const UIElement_PointerReleased: XamlEventIndex = XamlEventIndex(40i32); pub const UIElement_PointerEntered: XamlEventIndex = XamlEventIndex(41i32); pub const UIElement_PointerExited: XamlEventIndex = XamlEventIndex(42i32); pub const UIElement_PointerCaptureLost: XamlEventIndex = XamlEventIndex(43i32); pub const UIElement_PointerCanceled: XamlEventIndex = XamlEventIndex(44i32); pub const UIElement_PointerWheelChanged: XamlEventIndex = XamlEventIndex(45i32); pub const UIElement_Tapped: XamlEventIndex = XamlEventIndex(46i32); pub const UIElement_DoubleTapped: XamlEventIndex = XamlEventIndex(47i32); pub const UIElement_Holding: XamlEventIndex = XamlEventIndex(48i32); pub const UIElement_ContextRequested: XamlEventIndex = XamlEventIndex(49i32); pub const UIElement_ContextCanceled: XamlEventIndex = XamlEventIndex(50i32); pub const UIElement_RightTapped: XamlEventIndex = XamlEventIndex(51i32); pub const UIElement_ManipulationStarting: XamlEventIndex = XamlEventIndex(52i32); pub const UIElement_ManipulationInertiaStarting: XamlEventIndex = XamlEventIndex(53i32); pub const UIElement_ManipulationStarted: XamlEventIndex = XamlEventIndex(54i32); pub const UIElement_ManipulationDelta: XamlEventIndex = XamlEventIndex(55i32); pub const UIElement_ManipulationCompleted: XamlEventIndex = XamlEventIndex(56i32); pub const UIElement_ProcessKeyboardAccelerators: XamlEventIndex = XamlEventIndex(60i32); pub const UIElement_GettingFocus: XamlEventIndex = XamlEventIndex(61i32); pub const UIElement_LosingFocus: XamlEventIndex = XamlEventIndex(62i32); pub const UIElement_NoFocusCandidateFound: XamlEventIndex = XamlEventIndex(63i32); pub const UIElement_PreviewKeyDown: XamlEventIndex = XamlEventIndex(64i32); pub const UIElement_PreviewKeyUp: XamlEventIndex = XamlEventIndex(65i32); pub const UIElement_BringIntoViewRequested: XamlEventIndex = XamlEventIndex(66i32); pub const AppBar_Opening: XamlEventIndex = XamlEventIndex(109i32); pub const AppBar_Opened: XamlEventIndex = XamlEventIndex(110i32); pub const AppBar_Closing: XamlEventIndex = XamlEventIndex(111i32); pub const AppBar_Closed: XamlEventIndex = XamlEventIndex(112i32); pub const AutoSuggestBox_SuggestionChosen: XamlEventIndex = XamlEventIndex(113i32); pub const AutoSuggestBox_TextChanged: XamlEventIndex = XamlEventIndex(114i32); pub const AutoSuggestBox_QuerySubmitted: XamlEventIndex = XamlEventIndex(115i32); pub const CalendarDatePicker_CalendarViewDayItemChanging: XamlEventIndex = XamlEventIndex(116i32); pub const CalendarDatePicker_DateChanged: XamlEventIndex = XamlEventIndex(117i32); pub const CalendarDatePicker_Opened: XamlEventIndex = XamlEventIndex(118i32); pub const CalendarDatePicker_Closed: XamlEventIndex = XamlEventIndex(119i32); pub const CalendarView_CalendarViewDayItemChanging: XamlEventIndex = XamlEventIndex(120i32); pub const CalendarView_SelectedDatesChanged: XamlEventIndex = XamlEventIndex(121i32); pub const ComboBox_DropDownClosed: XamlEventIndex = XamlEventIndex(122i32); pub const ComboBox_DropDownOpened: XamlEventIndex = XamlEventIndex(123i32); pub const CommandBar_DynamicOverflowItemsChanging: XamlEventIndex = XamlEventIndex(124i32); pub const ContentDialog_Closing: XamlEventIndex = XamlEventIndex(126i32); pub const ContentDialog_Closed: XamlEventIndex = XamlEventIndex(127i32); pub const ContentDialog_Opened: XamlEventIndex = XamlEventIndex(128i32); pub const ContentDialog_PrimaryButtonClick: XamlEventIndex = XamlEventIndex(129i32); pub const ContentDialog_SecondaryButtonClick: XamlEventIndex = XamlEventIndex(130i32); pub const ContentDialog_CloseButtonClick: XamlEventIndex = XamlEventIndex(131i32); pub const Control_FocusEngaged: XamlEventIndex = XamlEventIndex(132i32); pub const Control_FocusDisengaged: XamlEventIndex = XamlEventIndex(133i32); pub const DatePicker_DateChanged: XamlEventIndex = XamlEventIndex(135i32); pub const Frame_Navigated: XamlEventIndex = XamlEventIndex(136i32); pub const Frame_Navigating: XamlEventIndex = XamlEventIndex(137i32); pub const Frame_NavigationFailed: XamlEventIndex = XamlEventIndex(138i32); pub const Frame_NavigationStopped: XamlEventIndex = XamlEventIndex(139i32); pub const Hub_SectionHeaderClick: XamlEventIndex = XamlEventIndex(143i32); pub const Hub_SectionsInViewChanged: XamlEventIndex = XamlEventIndex(144i32); pub const ItemsPresenter_HorizontalSnapPointsChanged: XamlEventIndex = XamlEventIndex(148i32); pub const ItemsPresenter_VerticalSnapPointsChanged: XamlEventIndex = XamlEventIndex(149i32); pub const ListViewBase_ItemClick: XamlEventIndex = XamlEventIndex(150i32); pub const ListViewBase_DragItemsStarting: XamlEventIndex = XamlEventIndex(151i32); pub const ListViewBase_DragItemsCompleted: XamlEventIndex = XamlEventIndex(152i32); pub const ListViewBase_ContainerContentChanging: XamlEventIndex = XamlEventIndex(153i32); pub const ListViewBase_ChoosingItemContainer: XamlEventIndex = XamlEventIndex(154i32); pub const ListViewBase_ChoosingGroupHeaderContainer: XamlEventIndex = XamlEventIndex(155i32); pub const MediaTransportControls_ThumbnailRequested: XamlEventIndex = XamlEventIndex(167i32); pub const MenuFlyoutItem_Click: XamlEventIndex = XamlEventIndex(168i32); pub const RichEditBox_TextChanging: XamlEventIndex = XamlEventIndex(177i32); pub const ScrollViewer_ViewChanging: XamlEventIndex = XamlEventIndex(192i32); pub const ScrollViewer_ViewChanged: XamlEventIndex = XamlEventIndex(193i32); pub const ScrollViewer_DirectManipulationStarted: XamlEventIndex = XamlEventIndex(194i32); pub const ScrollViewer_DirectManipulationCompleted: XamlEventIndex = XamlEventIndex(195i32); pub const SearchBox_QueryChanged: XamlEventIndex = XamlEventIndex(196i32); pub const SearchBox_SuggestionsRequested: XamlEventIndex = XamlEventIndex(197i32); pub const SearchBox_QuerySubmitted: XamlEventIndex = XamlEventIndex(198i32); pub const SearchBox_ResultSuggestionChosen: XamlEventIndex = XamlEventIndex(199i32); pub const SearchBox_PrepareForFocusOnKeyboardInput: XamlEventIndex = XamlEventIndex(200i32); pub const SemanticZoom_ViewChangeStarted: XamlEventIndex = XamlEventIndex(201i32); pub const SemanticZoom_ViewChangeCompleted: XamlEventIndex = XamlEventIndex(202i32); pub const SettingsFlyout_BackClick: XamlEventIndex = XamlEventIndex(203i32); pub const StackPanel_HorizontalSnapPointsChanged: XamlEventIndex = XamlEventIndex(208i32); pub const StackPanel_VerticalSnapPointsChanged: XamlEventIndex = XamlEventIndex(209i32); pub const TimePicker_TimeChanged: XamlEventIndex = XamlEventIndex(227i32); pub const ToggleSwitch_Toggled: XamlEventIndex = XamlEventIndex(228i32); pub const ToolTip_Closed: XamlEventIndex = XamlEventIndex(229i32); pub const ToolTip_Opened: XamlEventIndex = XamlEventIndex(230i32); pub const VirtualizingStackPanel_CleanUpVirtualizedItemEvent: XamlEventIndex = XamlEventIndex(231i32); pub const WebView_SeparateProcessLost: XamlEventIndex = XamlEventIndex(232i32); pub const WebView_LoadCompleted: XamlEventIndex = XamlEventIndex(233i32); pub const WebView_ScriptNotify: XamlEventIndex = XamlEventIndex(234i32); pub const WebView_NavigationFailed: XamlEventIndex = XamlEventIndex(235i32); pub const WebView_NavigationStarting: XamlEventIndex = XamlEventIndex(236i32); pub const WebView_ContentLoading: XamlEventIndex = XamlEventIndex(237i32); pub const WebView_DOMContentLoaded: XamlEventIndex = XamlEventIndex(238i32); pub const WebView_NavigationCompleted: XamlEventIndex = XamlEventIndex(239i32); pub const WebView_FrameNavigationStarting: XamlEventIndex = XamlEventIndex(240i32); pub const WebView_FrameContentLoading: XamlEventIndex = XamlEventIndex(241i32); pub const WebView_FrameDOMContentLoaded: XamlEventIndex = XamlEventIndex(242i32); pub const WebView_FrameNavigationCompleted: XamlEventIndex = XamlEventIndex(243i32); pub const WebView_LongRunningScriptDetected: XamlEventIndex = XamlEventIndex(244i32); pub const WebView_UnsafeContentWarningDisplaying: XamlEventIndex = XamlEventIndex(245i32); pub const WebView_UnviewableContentIdentified: XamlEventIndex = XamlEventIndex(246i32); pub const WebView_ContainsFullScreenElementChanged: XamlEventIndex = XamlEventIndex(247i32); pub const WebView_UnsupportedUriSchemeIdentified: XamlEventIndex = XamlEventIndex(248i32); pub const WebView_NewWindowRequested: XamlEventIndex = XamlEventIndex(249i32); pub const WebView_PermissionRequested: XamlEventIndex = XamlEventIndex(250i32); pub const ButtonBase_Click: XamlEventIndex = XamlEventIndex(256i32); pub const CarouselPanel_HorizontalSnapPointsChanged: XamlEventIndex = XamlEventIndex(257i32); pub const CarouselPanel_VerticalSnapPointsChanged: XamlEventIndex = XamlEventIndex(258i32); pub const OrientedVirtualizingPanel_HorizontalSnapPointsChanged: XamlEventIndex = XamlEventIndex(263i32); pub const OrientedVirtualizingPanel_VerticalSnapPointsChanged: XamlEventIndex = XamlEventIndex(264i32); pub const RangeBase_ValueChanged: XamlEventIndex = XamlEventIndex(267i32); pub const ScrollBar_Scroll: XamlEventIndex = XamlEventIndex(268i32); pub const Selector_SelectionChanged: XamlEventIndex = XamlEventIndex(269i32); pub const Thumb_DragStarted: XamlEventIndex = XamlEventIndex(270i32); pub const Thumb_DragDelta: XamlEventIndex = XamlEventIndex(271i32); pub const Thumb_DragCompleted: XamlEventIndex = XamlEventIndex(272i32); pub const ToggleButton_Checked: XamlEventIndex = XamlEventIndex(273i32); pub const ToggleButton_Unchecked: XamlEventIndex = XamlEventIndex(274i32); pub const ToggleButton_Indeterminate: XamlEventIndex = XamlEventIndex(275i32); pub const WebView_WebResourceRequested: XamlEventIndex = XamlEventIndex(283i32); pub const ScrollViewer_AnchorRequested: XamlEventIndex = XamlEventIndex(291i32); pub const DatePicker_SelectedDateChanged: XamlEventIndex = XamlEventIndex(322i32); pub const TimePicker_SelectedTimeChanged: XamlEventIndex = XamlEventIndex(323i32); } impl ::core::convert::From<i32> for XamlEventIndex { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XamlEventIndex { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XamlEventIndex { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Core.Direct.XamlEventIndex;i4)"); } impl ::windows::core::DefaultType for XamlEventIndex { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XamlPropertyIndex(pub i32); impl XamlPropertyIndex { pub const AutomationProperties_AcceleratorKey: XamlPropertyIndex = XamlPropertyIndex(5i32); pub const AutomationProperties_AccessibilityView: XamlPropertyIndex = XamlPropertyIndex(6i32); pub const AutomationProperties_AccessKey: XamlPropertyIndex = XamlPropertyIndex(7i32); pub const AutomationProperties_AutomationId: XamlPropertyIndex = XamlPropertyIndex(8i32); pub const AutomationProperties_ControlledPeers: XamlPropertyIndex = XamlPropertyIndex(9i32); pub const AutomationProperties_HelpText: XamlPropertyIndex = XamlPropertyIndex(10i32); pub const AutomationProperties_IsRequiredForForm: XamlPropertyIndex = XamlPropertyIndex(11i32); pub const AutomationProperties_ItemStatus: XamlPropertyIndex = XamlPropertyIndex(12i32); pub const AutomationProperties_ItemType: XamlPropertyIndex = XamlPropertyIndex(13i32); pub const AutomationProperties_LabeledBy: XamlPropertyIndex = XamlPropertyIndex(14i32); pub const AutomationProperties_LiveSetting: XamlPropertyIndex = XamlPropertyIndex(15i32); pub const AutomationProperties_Name: XamlPropertyIndex = XamlPropertyIndex(16i32); pub const ToolTipService_Placement: XamlPropertyIndex = XamlPropertyIndex(24i32); pub const ToolTipService_PlacementTarget: XamlPropertyIndex = XamlPropertyIndex(25i32); pub const ToolTipService_ToolTip: XamlPropertyIndex = XamlPropertyIndex(26i32); pub const Typography_AnnotationAlternates: XamlPropertyIndex = XamlPropertyIndex(28i32); pub const Typography_Capitals: XamlPropertyIndex = XamlPropertyIndex(29i32); pub const Typography_CapitalSpacing: XamlPropertyIndex = XamlPropertyIndex(30i32); pub const Typography_CaseSensitiveForms: XamlPropertyIndex = XamlPropertyIndex(31i32); pub const Typography_ContextualAlternates: XamlPropertyIndex = XamlPropertyIndex(32i32); pub const Typography_ContextualLigatures: XamlPropertyIndex = XamlPropertyIndex(33i32); pub const Typography_ContextualSwashes: XamlPropertyIndex = XamlPropertyIndex(34i32); pub const Typography_DiscretionaryLigatures: XamlPropertyIndex = XamlPropertyIndex(35i32); pub const Typography_EastAsianExpertForms: XamlPropertyIndex = XamlPropertyIndex(36i32); pub const Typography_EastAsianLanguage: XamlPropertyIndex = XamlPropertyIndex(37i32); pub const Typography_EastAsianWidths: XamlPropertyIndex = XamlPropertyIndex(38i32); pub const Typography_Fraction: XamlPropertyIndex = XamlPropertyIndex(39i32); pub const Typography_HistoricalForms: XamlPropertyIndex = XamlPropertyIndex(40i32); pub const Typography_HistoricalLigatures: XamlPropertyIndex = XamlPropertyIndex(41i32); pub const Typography_Kerning: XamlPropertyIndex = XamlPropertyIndex(42i32); pub const Typography_MathematicalGreek: XamlPropertyIndex = XamlPropertyIndex(43i32); pub const Typography_NumeralAlignment: XamlPropertyIndex = XamlPropertyIndex(44i32); pub const Typography_NumeralStyle: XamlPropertyIndex = XamlPropertyIndex(45i32); pub const Typography_SlashedZero: XamlPropertyIndex = XamlPropertyIndex(46i32); pub const Typography_StandardLigatures: XamlPropertyIndex = XamlPropertyIndex(47i32); pub const Typography_StandardSwashes: XamlPropertyIndex = XamlPropertyIndex(48i32); pub const Typography_StylisticAlternates: XamlPropertyIndex = XamlPropertyIndex(49i32); pub const Typography_StylisticSet1: XamlPropertyIndex = XamlPropertyIndex(50i32); pub const Typography_StylisticSet10: XamlPropertyIndex = XamlPropertyIndex(51i32); pub const Typography_StylisticSet11: XamlPropertyIndex = XamlPropertyIndex(52i32); pub const Typography_StylisticSet12: XamlPropertyIndex = XamlPropertyIndex(53i32); pub const Typography_StylisticSet13: XamlPropertyIndex = XamlPropertyIndex(54i32); pub const Typography_StylisticSet14: XamlPropertyIndex = XamlPropertyIndex(55i32); pub const Typography_StylisticSet15: XamlPropertyIndex = XamlPropertyIndex(56i32); pub const Typography_StylisticSet16: XamlPropertyIndex = XamlPropertyIndex(57i32); pub const Typography_StylisticSet17: XamlPropertyIndex = XamlPropertyIndex(58i32); pub const Typography_StylisticSet18: XamlPropertyIndex = XamlPropertyIndex(59i32); pub const Typography_StylisticSet19: XamlPropertyIndex = XamlPropertyIndex(60i32); pub const Typography_StylisticSet2: XamlPropertyIndex = XamlPropertyIndex(61i32); pub const Typography_StylisticSet20: XamlPropertyIndex = XamlPropertyIndex(62i32); pub const Typography_StylisticSet3: XamlPropertyIndex = XamlPropertyIndex(63i32); pub const Typography_StylisticSet4: XamlPropertyIndex = XamlPropertyIndex(64i32); pub const Typography_StylisticSet5: XamlPropertyIndex = XamlPropertyIndex(65i32); pub const Typography_StylisticSet6: XamlPropertyIndex = XamlPropertyIndex(66i32); pub const Typography_StylisticSet7: XamlPropertyIndex = XamlPropertyIndex(67i32); pub const Typography_StylisticSet8: XamlPropertyIndex = XamlPropertyIndex(68i32); pub const Typography_StylisticSet9: XamlPropertyIndex = XamlPropertyIndex(69i32); pub const Typography_Variants: XamlPropertyIndex = XamlPropertyIndex(70i32); pub const AutomationPeer_EventsSource: XamlPropertyIndex = XamlPropertyIndex(75i32); pub const AutoSuggestBoxSuggestionChosenEventArgs_SelectedItem: XamlPropertyIndex = XamlPropertyIndex(76i32); pub const AutoSuggestBoxTextChangedEventArgs_Reason: XamlPropertyIndex = XamlPropertyIndex(77i32); pub const Brush_Opacity: XamlPropertyIndex = XamlPropertyIndex(78i32); pub const Brush_RelativeTransform: XamlPropertyIndex = XamlPropertyIndex(79i32); pub const Brush_Transform: XamlPropertyIndex = XamlPropertyIndex(80i32); pub const CollectionViewSource_IsSourceGrouped: XamlPropertyIndex = XamlPropertyIndex(81i32); pub const CollectionViewSource_ItemsPath: XamlPropertyIndex = XamlPropertyIndex(82i32); pub const CollectionViewSource_Source: XamlPropertyIndex = XamlPropertyIndex(83i32); pub const CollectionViewSource_View: XamlPropertyIndex = XamlPropertyIndex(84i32); pub const ColorKeyFrame_KeyTime: XamlPropertyIndex = XamlPropertyIndex(90i32); pub const ColorKeyFrame_Value: XamlPropertyIndex = XamlPropertyIndex(91i32); pub const ColumnDefinition_ActualWidth: XamlPropertyIndex = XamlPropertyIndex(92i32); pub const ColumnDefinition_MaxWidth: XamlPropertyIndex = XamlPropertyIndex(93i32); pub const ColumnDefinition_MinWidth: XamlPropertyIndex = XamlPropertyIndex(94i32); pub const ColumnDefinition_Width: XamlPropertyIndex = XamlPropertyIndex(95i32); pub const ComboBoxTemplateSettings_DropDownClosedHeight: XamlPropertyIndex = XamlPropertyIndex(96i32); pub const ComboBoxTemplateSettings_DropDownOffset: XamlPropertyIndex = XamlPropertyIndex(97i32); pub const ComboBoxTemplateSettings_DropDownOpenedHeight: XamlPropertyIndex = XamlPropertyIndex(98i32); pub const ComboBoxTemplateSettings_SelectedItemDirection: XamlPropertyIndex = XamlPropertyIndex(99i32); pub const DoubleKeyFrame_KeyTime: XamlPropertyIndex = XamlPropertyIndex(107i32); pub const DoubleKeyFrame_Value: XamlPropertyIndex = XamlPropertyIndex(108i32); pub const EasingFunctionBase_EasingMode: XamlPropertyIndex = XamlPropertyIndex(111i32); pub const FlyoutBase_AttachedFlyout: XamlPropertyIndex = XamlPropertyIndex(114i32); pub const FlyoutBase_Placement: XamlPropertyIndex = XamlPropertyIndex(115i32); pub const Geometry_Bounds: XamlPropertyIndex = XamlPropertyIndex(118i32); pub const Geometry_Transform: XamlPropertyIndex = XamlPropertyIndex(119i32); pub const GradientStop_Color: XamlPropertyIndex = XamlPropertyIndex(120i32); pub const GradientStop_Offset: XamlPropertyIndex = XamlPropertyIndex(121i32); pub const GroupStyle_ContainerStyle: XamlPropertyIndex = XamlPropertyIndex(124i32); pub const GroupStyle_ContainerStyleSelector: XamlPropertyIndex = XamlPropertyIndex(125i32); pub const GroupStyle_HeaderContainerStyle: XamlPropertyIndex = XamlPropertyIndex(126i32); pub const GroupStyle_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(127i32); pub const GroupStyle_HeaderTemplateSelector: XamlPropertyIndex = XamlPropertyIndex(128i32); pub const GroupStyle_HidesIfEmpty: XamlPropertyIndex = XamlPropertyIndex(129i32); pub const GroupStyle_Panel: XamlPropertyIndex = XamlPropertyIndex(130i32); pub const InertiaExpansionBehavior_DesiredDeceleration: XamlPropertyIndex = XamlPropertyIndex(144i32); pub const InertiaExpansionBehavior_DesiredExpansion: XamlPropertyIndex = XamlPropertyIndex(145i32); pub const InertiaRotationBehavior_DesiredDeceleration: XamlPropertyIndex = XamlPropertyIndex(146i32); pub const InertiaRotationBehavior_DesiredRotation: XamlPropertyIndex = XamlPropertyIndex(147i32); pub const InertiaTranslationBehavior_DesiredDeceleration: XamlPropertyIndex = XamlPropertyIndex(148i32); pub const InertiaTranslationBehavior_DesiredDisplacement: XamlPropertyIndex = XamlPropertyIndex(149i32); pub const InputScope_Names: XamlPropertyIndex = XamlPropertyIndex(150i32); pub const InputScopeName_NameValue: XamlPropertyIndex = XamlPropertyIndex(151i32); pub const KeySpline_ControlPoint1: XamlPropertyIndex = XamlPropertyIndex(153i32); pub const KeySpline_ControlPoint2: XamlPropertyIndex = XamlPropertyIndex(154i32); pub const ManipulationPivot_Center: XamlPropertyIndex = XamlPropertyIndex(159i32); pub const ManipulationPivot_Radius: XamlPropertyIndex = XamlPropertyIndex(160i32); pub const ObjectKeyFrame_KeyTime: XamlPropertyIndex = XamlPropertyIndex(183i32); pub const ObjectKeyFrame_Value: XamlPropertyIndex = XamlPropertyIndex(184i32); pub const PageStackEntry_SourcePageType: XamlPropertyIndex = XamlPropertyIndex(185i32); pub const PathFigure_IsClosed: XamlPropertyIndex = XamlPropertyIndex(192i32); pub const PathFigure_IsFilled: XamlPropertyIndex = XamlPropertyIndex(193i32); pub const PathFigure_Segments: XamlPropertyIndex = XamlPropertyIndex(194i32); pub const PathFigure_StartPoint: XamlPropertyIndex = XamlPropertyIndex(195i32); pub const Pointer_IsInContact: XamlPropertyIndex = XamlPropertyIndex(199i32); pub const Pointer_IsInRange: XamlPropertyIndex = XamlPropertyIndex(200i32); pub const Pointer_PointerDeviceType: XamlPropertyIndex = XamlPropertyIndex(201i32); pub const Pointer_PointerId: XamlPropertyIndex = XamlPropertyIndex(202i32); pub const PointKeyFrame_KeyTime: XamlPropertyIndex = XamlPropertyIndex(205i32); pub const PointKeyFrame_Value: XamlPropertyIndex = XamlPropertyIndex(206i32); pub const PrintDocument_DocumentSource: XamlPropertyIndex = XamlPropertyIndex(209i32); pub const ProgressBarTemplateSettings_ContainerAnimationEndPosition: XamlPropertyIndex = XamlPropertyIndex(211i32); pub const ProgressBarTemplateSettings_ContainerAnimationStartPosition: XamlPropertyIndex = XamlPropertyIndex(212i32); pub const ProgressBarTemplateSettings_EllipseAnimationEndPosition: XamlPropertyIndex = XamlPropertyIndex(213i32); pub const ProgressBarTemplateSettings_EllipseAnimationWellPosition: XamlPropertyIndex = XamlPropertyIndex(214i32); pub const ProgressBarTemplateSettings_EllipseDiameter: XamlPropertyIndex = XamlPropertyIndex(215i32); pub const ProgressBarTemplateSettings_EllipseOffset: XamlPropertyIndex = XamlPropertyIndex(216i32); pub const ProgressBarTemplateSettings_IndicatorLengthDelta: XamlPropertyIndex = XamlPropertyIndex(217i32); pub const ProgressRingTemplateSettings_EllipseDiameter: XamlPropertyIndex = XamlPropertyIndex(218i32); pub const ProgressRingTemplateSettings_EllipseOffset: XamlPropertyIndex = XamlPropertyIndex(219i32); pub const ProgressRingTemplateSettings_MaxSideLength: XamlPropertyIndex = XamlPropertyIndex(220i32); pub const PropertyPath_Path: XamlPropertyIndex = XamlPropertyIndex(221i32); pub const RowDefinition_ActualHeight: XamlPropertyIndex = XamlPropertyIndex(226i32); pub const RowDefinition_Height: XamlPropertyIndex = XamlPropertyIndex(227i32); pub const RowDefinition_MaxHeight: XamlPropertyIndex = XamlPropertyIndex(228i32); pub const RowDefinition_MinHeight: XamlPropertyIndex = XamlPropertyIndex(229i32); pub const SetterBase_IsSealed: XamlPropertyIndex = XamlPropertyIndex(233i32); pub const SettingsFlyoutTemplateSettings_BorderBrush: XamlPropertyIndex = XamlPropertyIndex(234i32); pub const SettingsFlyoutTemplateSettings_BorderThickness: XamlPropertyIndex = XamlPropertyIndex(235i32); pub const SettingsFlyoutTemplateSettings_ContentTransitions: XamlPropertyIndex = XamlPropertyIndex(236i32); pub const SettingsFlyoutTemplateSettings_HeaderBackground: XamlPropertyIndex = XamlPropertyIndex(237i32); pub const SettingsFlyoutTemplateSettings_HeaderForeground: XamlPropertyIndex = XamlPropertyIndex(238i32); pub const SettingsFlyoutTemplateSettings_IconSource: XamlPropertyIndex = XamlPropertyIndex(239i32); pub const Style_BasedOn: XamlPropertyIndex = XamlPropertyIndex(244i32); pub const Style_IsSealed: XamlPropertyIndex = XamlPropertyIndex(245i32); pub const Style_Setters: XamlPropertyIndex = XamlPropertyIndex(246i32); pub const Style_TargetType: XamlPropertyIndex = XamlPropertyIndex(247i32); pub const TextElement_CharacterSpacing: XamlPropertyIndex = XamlPropertyIndex(249i32); pub const TextElement_FontFamily: XamlPropertyIndex = XamlPropertyIndex(250i32); pub const TextElement_FontSize: XamlPropertyIndex = XamlPropertyIndex(251i32); pub const TextElement_FontStretch: XamlPropertyIndex = XamlPropertyIndex(252i32); pub const TextElement_FontStyle: XamlPropertyIndex = XamlPropertyIndex(253i32); pub const TextElement_FontWeight: XamlPropertyIndex = XamlPropertyIndex(254i32); pub const TextElement_Foreground: XamlPropertyIndex = XamlPropertyIndex(255i32); pub const TextElement_IsTextScaleFactorEnabled: XamlPropertyIndex = XamlPropertyIndex(256i32); pub const TextElement_Language: XamlPropertyIndex = XamlPropertyIndex(257i32); pub const Timeline_AutoReverse: XamlPropertyIndex = XamlPropertyIndex(263i32); pub const Timeline_BeginTime: XamlPropertyIndex = XamlPropertyIndex(264i32); pub const Timeline_Duration: XamlPropertyIndex = XamlPropertyIndex(265i32); pub const Timeline_FillBehavior: XamlPropertyIndex = XamlPropertyIndex(266i32); pub const Timeline_RepeatBehavior: XamlPropertyIndex = XamlPropertyIndex(267i32); pub const Timeline_SpeedRatio: XamlPropertyIndex = XamlPropertyIndex(268i32); pub const TimelineMarker_Text: XamlPropertyIndex = XamlPropertyIndex(269i32); pub const TimelineMarker_Time: XamlPropertyIndex = XamlPropertyIndex(270i32); pub const TimelineMarker_Type: XamlPropertyIndex = XamlPropertyIndex(271i32); pub const ToggleSwitchTemplateSettings_CurtainCurrentToOffOffset: XamlPropertyIndex = XamlPropertyIndex(273i32); pub const ToggleSwitchTemplateSettings_CurtainCurrentToOnOffset: XamlPropertyIndex = XamlPropertyIndex(274i32); pub const ToggleSwitchTemplateSettings_CurtainOffToOnOffset: XamlPropertyIndex = XamlPropertyIndex(275i32); pub const ToggleSwitchTemplateSettings_CurtainOnToOffOffset: XamlPropertyIndex = XamlPropertyIndex(276i32); pub const ToggleSwitchTemplateSettings_KnobCurrentToOffOffset: XamlPropertyIndex = XamlPropertyIndex(277i32); pub const ToggleSwitchTemplateSettings_KnobCurrentToOnOffset: XamlPropertyIndex = XamlPropertyIndex(278i32); pub const ToggleSwitchTemplateSettings_KnobOffToOnOffset: XamlPropertyIndex = XamlPropertyIndex(279i32); pub const ToggleSwitchTemplateSettings_KnobOnToOffOffset: XamlPropertyIndex = XamlPropertyIndex(280i32); pub const ToolTipTemplateSettings_FromHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(281i32); pub const ToolTipTemplateSettings_FromVerticalOffset: XamlPropertyIndex = XamlPropertyIndex(282i32); pub const UIElement_AllowDrop: XamlPropertyIndex = XamlPropertyIndex(292i32); pub const UIElement_CacheMode: XamlPropertyIndex = XamlPropertyIndex(293i32); pub const UIElement_Clip: XamlPropertyIndex = XamlPropertyIndex(295i32); pub const UIElement_CompositeMode: XamlPropertyIndex = XamlPropertyIndex(296i32); pub const UIElement_IsDoubleTapEnabled: XamlPropertyIndex = XamlPropertyIndex(297i32); pub const UIElement_IsHitTestVisible: XamlPropertyIndex = XamlPropertyIndex(298i32); pub const UIElement_IsHoldingEnabled: XamlPropertyIndex = XamlPropertyIndex(299i32); pub const UIElement_IsRightTapEnabled: XamlPropertyIndex = XamlPropertyIndex(300i32); pub const UIElement_IsTapEnabled: XamlPropertyIndex = XamlPropertyIndex(301i32); pub const UIElement_ManipulationMode: XamlPropertyIndex = XamlPropertyIndex(302i32); pub const UIElement_Opacity: XamlPropertyIndex = XamlPropertyIndex(303i32); pub const UIElement_PointerCaptures: XamlPropertyIndex = XamlPropertyIndex(304i32); pub const UIElement_Projection: XamlPropertyIndex = XamlPropertyIndex(305i32); pub const UIElement_RenderSize: XamlPropertyIndex = XamlPropertyIndex(306i32); pub const UIElement_RenderTransform: XamlPropertyIndex = XamlPropertyIndex(307i32); pub const UIElement_RenderTransformOrigin: XamlPropertyIndex = XamlPropertyIndex(308i32); pub const UIElement_Transitions: XamlPropertyIndex = XamlPropertyIndex(309i32); pub const UIElement_UseLayoutRounding: XamlPropertyIndex = XamlPropertyIndex(311i32); pub const UIElement_Visibility: XamlPropertyIndex = XamlPropertyIndex(312i32); pub const VisualState_Storyboard: XamlPropertyIndex = XamlPropertyIndex(322i32); pub const VisualStateGroup_States: XamlPropertyIndex = XamlPropertyIndex(323i32); pub const VisualStateGroup_Transitions: XamlPropertyIndex = XamlPropertyIndex(324i32); pub const VisualStateManager_CustomVisualStateManager: XamlPropertyIndex = XamlPropertyIndex(325i32); pub const VisualStateManager_VisualStateGroups: XamlPropertyIndex = XamlPropertyIndex(326i32); pub const VisualTransition_From: XamlPropertyIndex = XamlPropertyIndex(327i32); pub const VisualTransition_GeneratedDuration: XamlPropertyIndex = XamlPropertyIndex(328i32); pub const VisualTransition_GeneratedEasingFunction: XamlPropertyIndex = XamlPropertyIndex(329i32); pub const VisualTransition_Storyboard: XamlPropertyIndex = XamlPropertyIndex(330i32); pub const VisualTransition_To: XamlPropertyIndex = XamlPropertyIndex(331i32); pub const ArcSegment_IsLargeArc: XamlPropertyIndex = XamlPropertyIndex(332i32); pub const ArcSegment_Point: XamlPropertyIndex = XamlPropertyIndex(333i32); pub const ArcSegment_RotationAngle: XamlPropertyIndex = XamlPropertyIndex(334i32); pub const ArcSegment_Size: XamlPropertyIndex = XamlPropertyIndex(335i32); pub const ArcSegment_SweepDirection: XamlPropertyIndex = XamlPropertyIndex(336i32); pub const BackEase_Amplitude: XamlPropertyIndex = XamlPropertyIndex(337i32); pub const BeginStoryboard_Storyboard: XamlPropertyIndex = XamlPropertyIndex(338i32); pub const BezierSegment_Point1: XamlPropertyIndex = XamlPropertyIndex(339i32); pub const BezierSegment_Point2: XamlPropertyIndex = XamlPropertyIndex(340i32); pub const BezierSegment_Point3: XamlPropertyIndex = XamlPropertyIndex(341i32); pub const BitmapSource_PixelHeight: XamlPropertyIndex = XamlPropertyIndex(342i32); pub const BitmapSource_PixelWidth: XamlPropertyIndex = XamlPropertyIndex(343i32); pub const Block_LineHeight: XamlPropertyIndex = XamlPropertyIndex(344i32); pub const Block_LineStackingStrategy: XamlPropertyIndex = XamlPropertyIndex(345i32); pub const Block_Margin: XamlPropertyIndex = XamlPropertyIndex(346i32); pub const Block_TextAlignment: XamlPropertyIndex = XamlPropertyIndex(347i32); pub const BounceEase_Bounces: XamlPropertyIndex = XamlPropertyIndex(348i32); pub const BounceEase_Bounciness: XamlPropertyIndex = XamlPropertyIndex(349i32); pub const ColorAnimation_By: XamlPropertyIndex = XamlPropertyIndex(350i32); pub const ColorAnimation_EasingFunction: XamlPropertyIndex = XamlPropertyIndex(351i32); pub const ColorAnimation_EnableDependentAnimation: XamlPropertyIndex = XamlPropertyIndex(352i32); pub const ColorAnimation_From: XamlPropertyIndex = XamlPropertyIndex(353i32); pub const ColorAnimation_To: XamlPropertyIndex = XamlPropertyIndex(354i32); pub const ColorAnimationUsingKeyFrames_EnableDependentAnimation: XamlPropertyIndex = XamlPropertyIndex(355i32); pub const ColorAnimationUsingKeyFrames_KeyFrames: XamlPropertyIndex = XamlPropertyIndex(356i32); pub const ContentThemeTransition_HorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(357i32); pub const ContentThemeTransition_VerticalOffset: XamlPropertyIndex = XamlPropertyIndex(358i32); pub const ControlTemplate_TargetType: XamlPropertyIndex = XamlPropertyIndex(359i32); pub const DispatcherTimer_Interval: XamlPropertyIndex = XamlPropertyIndex(362i32); pub const DoubleAnimation_By: XamlPropertyIndex = XamlPropertyIndex(363i32); pub const DoubleAnimation_EasingFunction: XamlPropertyIndex = XamlPropertyIndex(364i32); pub const DoubleAnimation_EnableDependentAnimation: XamlPropertyIndex = XamlPropertyIndex(365i32); pub const DoubleAnimation_From: XamlPropertyIndex = XamlPropertyIndex(366i32); pub const DoubleAnimation_To: XamlPropertyIndex = XamlPropertyIndex(367i32); pub const DoubleAnimationUsingKeyFrames_EnableDependentAnimation: XamlPropertyIndex = XamlPropertyIndex(368i32); pub const DoubleAnimationUsingKeyFrames_KeyFrames: XamlPropertyIndex = XamlPropertyIndex(369i32); pub const EasingColorKeyFrame_EasingFunction: XamlPropertyIndex = XamlPropertyIndex(372i32); pub const EasingDoubleKeyFrame_EasingFunction: XamlPropertyIndex = XamlPropertyIndex(373i32); pub const EasingPointKeyFrame_EasingFunction: XamlPropertyIndex = XamlPropertyIndex(374i32); pub const EdgeUIThemeTransition_Edge: XamlPropertyIndex = XamlPropertyIndex(375i32); pub const ElasticEase_Oscillations: XamlPropertyIndex = XamlPropertyIndex(376i32); pub const ElasticEase_Springiness: XamlPropertyIndex = XamlPropertyIndex(377i32); pub const EllipseGeometry_Center: XamlPropertyIndex = XamlPropertyIndex(378i32); pub const EllipseGeometry_RadiusX: XamlPropertyIndex = XamlPropertyIndex(379i32); pub const EllipseGeometry_RadiusY: XamlPropertyIndex = XamlPropertyIndex(380i32); pub const EntranceThemeTransition_FromHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(381i32); pub const EntranceThemeTransition_FromVerticalOffset: XamlPropertyIndex = XamlPropertyIndex(382i32); pub const EntranceThemeTransition_IsStaggeringEnabled: XamlPropertyIndex = XamlPropertyIndex(383i32); pub const EventTrigger_Actions: XamlPropertyIndex = XamlPropertyIndex(384i32); pub const EventTrigger_RoutedEvent: XamlPropertyIndex = XamlPropertyIndex(385i32); pub const ExponentialEase_Exponent: XamlPropertyIndex = XamlPropertyIndex(386i32); pub const Flyout_Content: XamlPropertyIndex = XamlPropertyIndex(387i32); pub const Flyout_FlyoutPresenterStyle: XamlPropertyIndex = XamlPropertyIndex(388i32); pub const FrameworkElement_ActualHeight: XamlPropertyIndex = XamlPropertyIndex(389i32); pub const FrameworkElement_ActualWidth: XamlPropertyIndex = XamlPropertyIndex(390i32); pub const FrameworkElement_DataContext: XamlPropertyIndex = XamlPropertyIndex(391i32); pub const FrameworkElement_FlowDirection: XamlPropertyIndex = XamlPropertyIndex(392i32); pub const FrameworkElement_Height: XamlPropertyIndex = XamlPropertyIndex(393i32); pub const FrameworkElement_HorizontalAlignment: XamlPropertyIndex = XamlPropertyIndex(394i32); pub const FrameworkElement_Language: XamlPropertyIndex = XamlPropertyIndex(396i32); pub const FrameworkElement_Margin: XamlPropertyIndex = XamlPropertyIndex(397i32); pub const FrameworkElement_MaxHeight: XamlPropertyIndex = XamlPropertyIndex(398i32); pub const FrameworkElement_MaxWidth: XamlPropertyIndex = XamlPropertyIndex(399i32); pub const FrameworkElement_MinHeight: XamlPropertyIndex = XamlPropertyIndex(400i32); pub const FrameworkElement_MinWidth: XamlPropertyIndex = XamlPropertyIndex(401i32); pub const FrameworkElement_Parent: XamlPropertyIndex = XamlPropertyIndex(402i32); pub const FrameworkElement_RequestedTheme: XamlPropertyIndex = XamlPropertyIndex(403i32); pub const FrameworkElement_Resources: XamlPropertyIndex = XamlPropertyIndex(404i32); pub const FrameworkElement_Style: XamlPropertyIndex = XamlPropertyIndex(405i32); pub const FrameworkElement_Tag: XamlPropertyIndex = XamlPropertyIndex(406i32); pub const FrameworkElement_Triggers: XamlPropertyIndex = XamlPropertyIndex(407i32); pub const FrameworkElement_VerticalAlignment: XamlPropertyIndex = XamlPropertyIndex(408i32); pub const FrameworkElement_Width: XamlPropertyIndex = XamlPropertyIndex(409i32); pub const FrameworkElementAutomationPeer_Owner: XamlPropertyIndex = XamlPropertyIndex(410i32); pub const GeometryGroup_Children: XamlPropertyIndex = XamlPropertyIndex(411i32); pub const GeometryGroup_FillRule: XamlPropertyIndex = XamlPropertyIndex(412i32); pub const GradientBrush_ColorInterpolationMode: XamlPropertyIndex = XamlPropertyIndex(413i32); pub const GradientBrush_GradientStops: XamlPropertyIndex = XamlPropertyIndex(414i32); pub const GradientBrush_MappingMode: XamlPropertyIndex = XamlPropertyIndex(415i32); pub const GradientBrush_SpreadMethod: XamlPropertyIndex = XamlPropertyIndex(416i32); pub const GridViewItemTemplateSettings_DragItemsCount: XamlPropertyIndex = XamlPropertyIndex(417i32); pub const ItemAutomationPeer_Item: XamlPropertyIndex = XamlPropertyIndex(419i32); pub const ItemAutomationPeer_ItemsControlAutomationPeer: XamlPropertyIndex = XamlPropertyIndex(420i32); pub const LineGeometry_EndPoint: XamlPropertyIndex = XamlPropertyIndex(422i32); pub const LineGeometry_StartPoint: XamlPropertyIndex = XamlPropertyIndex(423i32); pub const LineSegment_Point: XamlPropertyIndex = XamlPropertyIndex(424i32); pub const ListViewItemTemplateSettings_DragItemsCount: XamlPropertyIndex = XamlPropertyIndex(425i32); pub const Matrix3DProjection_ProjectionMatrix: XamlPropertyIndex = XamlPropertyIndex(426i32); pub const MenuFlyout_Items: XamlPropertyIndex = XamlPropertyIndex(427i32); pub const MenuFlyout_MenuFlyoutPresenterStyle: XamlPropertyIndex = XamlPropertyIndex(428i32); pub const ObjectAnimationUsingKeyFrames_EnableDependentAnimation: XamlPropertyIndex = XamlPropertyIndex(429i32); pub const ObjectAnimationUsingKeyFrames_KeyFrames: XamlPropertyIndex = XamlPropertyIndex(430i32); pub const PaneThemeTransition_Edge: XamlPropertyIndex = XamlPropertyIndex(431i32); pub const PathGeometry_Figures: XamlPropertyIndex = XamlPropertyIndex(432i32); pub const PathGeometry_FillRule: XamlPropertyIndex = XamlPropertyIndex(433i32); pub const PlaneProjection_CenterOfRotationX: XamlPropertyIndex = XamlPropertyIndex(434i32); pub const PlaneProjection_CenterOfRotationY: XamlPropertyIndex = XamlPropertyIndex(435i32); pub const PlaneProjection_CenterOfRotationZ: XamlPropertyIndex = XamlPropertyIndex(436i32); pub const PlaneProjection_GlobalOffsetX: XamlPropertyIndex = XamlPropertyIndex(437i32); pub const PlaneProjection_GlobalOffsetY: XamlPropertyIndex = XamlPropertyIndex(438i32); pub const PlaneProjection_GlobalOffsetZ: XamlPropertyIndex = XamlPropertyIndex(439i32); pub const PlaneProjection_LocalOffsetX: XamlPropertyIndex = XamlPropertyIndex(440i32); pub const PlaneProjection_LocalOffsetY: XamlPropertyIndex = XamlPropertyIndex(441i32); pub const PlaneProjection_LocalOffsetZ: XamlPropertyIndex = XamlPropertyIndex(442i32); pub const PlaneProjection_ProjectionMatrix: XamlPropertyIndex = XamlPropertyIndex(443i32); pub const PlaneProjection_RotationX: XamlPropertyIndex = XamlPropertyIndex(444i32); pub const PlaneProjection_RotationY: XamlPropertyIndex = XamlPropertyIndex(445i32); pub const PlaneProjection_RotationZ: XamlPropertyIndex = XamlPropertyIndex(446i32); pub const PointAnimation_By: XamlPropertyIndex = XamlPropertyIndex(447i32); pub const PointAnimation_EasingFunction: XamlPropertyIndex = XamlPropertyIndex(448i32); pub const PointAnimation_EnableDependentAnimation: XamlPropertyIndex = XamlPropertyIndex(449i32); pub const PointAnimation_From: XamlPropertyIndex = XamlPropertyIndex(450i32); pub const PointAnimation_To: XamlPropertyIndex = XamlPropertyIndex(451i32); pub const PointAnimationUsingKeyFrames_EnableDependentAnimation: XamlPropertyIndex = XamlPropertyIndex(452i32); pub const PointAnimationUsingKeyFrames_KeyFrames: XamlPropertyIndex = XamlPropertyIndex(453i32); pub const PolyBezierSegment_Points: XamlPropertyIndex = XamlPropertyIndex(456i32); pub const PolyLineSegment_Points: XamlPropertyIndex = XamlPropertyIndex(457i32); pub const PolyQuadraticBezierSegment_Points: XamlPropertyIndex = XamlPropertyIndex(458i32); pub const PopupThemeTransition_FromHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(459i32); pub const PopupThemeTransition_FromVerticalOffset: XamlPropertyIndex = XamlPropertyIndex(460i32); pub const PowerEase_Power: XamlPropertyIndex = XamlPropertyIndex(461i32); pub const QuadraticBezierSegment_Point1: XamlPropertyIndex = XamlPropertyIndex(466i32); pub const QuadraticBezierSegment_Point2: XamlPropertyIndex = XamlPropertyIndex(467i32); pub const RectangleGeometry_Rect: XamlPropertyIndex = XamlPropertyIndex(470i32); pub const RelativeSource_Mode: XamlPropertyIndex = XamlPropertyIndex(471i32); pub const RenderTargetBitmap_PixelHeight: XamlPropertyIndex = XamlPropertyIndex(472i32); pub const RenderTargetBitmap_PixelWidth: XamlPropertyIndex = XamlPropertyIndex(473i32); pub const Setter_Property: XamlPropertyIndex = XamlPropertyIndex(474i32); pub const Setter_Value: XamlPropertyIndex = XamlPropertyIndex(475i32); pub const SolidColorBrush_Color: XamlPropertyIndex = XamlPropertyIndex(476i32); pub const SplineColorKeyFrame_KeySpline: XamlPropertyIndex = XamlPropertyIndex(477i32); pub const SplineDoubleKeyFrame_KeySpline: XamlPropertyIndex = XamlPropertyIndex(478i32); pub const SplinePointKeyFrame_KeySpline: XamlPropertyIndex = XamlPropertyIndex(479i32); pub const TileBrush_AlignmentX: XamlPropertyIndex = XamlPropertyIndex(483i32); pub const TileBrush_AlignmentY: XamlPropertyIndex = XamlPropertyIndex(484i32); pub const TileBrush_Stretch: XamlPropertyIndex = XamlPropertyIndex(485i32); pub const Binding_Converter: XamlPropertyIndex = XamlPropertyIndex(487i32); pub const Binding_ConverterLanguage: XamlPropertyIndex = XamlPropertyIndex(488i32); pub const Binding_ConverterParameter: XamlPropertyIndex = XamlPropertyIndex(489i32); pub const Binding_ElementName: XamlPropertyIndex = XamlPropertyIndex(490i32); pub const Binding_FallbackValue: XamlPropertyIndex = XamlPropertyIndex(491i32); pub const Binding_Mode: XamlPropertyIndex = XamlPropertyIndex(492i32); pub const Binding_Path: XamlPropertyIndex = XamlPropertyIndex(493i32); pub const Binding_RelativeSource: XamlPropertyIndex = XamlPropertyIndex(494i32); pub const Binding_Source: XamlPropertyIndex = XamlPropertyIndex(495i32); pub const Binding_TargetNullValue: XamlPropertyIndex = XamlPropertyIndex(496i32); pub const Binding_UpdateSourceTrigger: XamlPropertyIndex = XamlPropertyIndex(497i32); pub const BitmapImage_CreateOptions: XamlPropertyIndex = XamlPropertyIndex(498i32); pub const BitmapImage_DecodePixelHeight: XamlPropertyIndex = XamlPropertyIndex(499i32); pub const BitmapImage_DecodePixelType: XamlPropertyIndex = XamlPropertyIndex(500i32); pub const BitmapImage_DecodePixelWidth: XamlPropertyIndex = XamlPropertyIndex(501i32); pub const BitmapImage_UriSource: XamlPropertyIndex = XamlPropertyIndex(502i32); pub const Border_Background: XamlPropertyIndex = XamlPropertyIndex(503i32); pub const Border_BorderBrush: XamlPropertyIndex = XamlPropertyIndex(504i32); pub const Border_BorderThickness: XamlPropertyIndex = XamlPropertyIndex(505i32); pub const Border_Child: XamlPropertyIndex = XamlPropertyIndex(506i32); pub const Border_ChildTransitions: XamlPropertyIndex = XamlPropertyIndex(507i32); pub const Border_CornerRadius: XamlPropertyIndex = XamlPropertyIndex(508i32); pub const Border_Padding: XamlPropertyIndex = XamlPropertyIndex(509i32); pub const CaptureElement_Source: XamlPropertyIndex = XamlPropertyIndex(510i32); pub const CaptureElement_Stretch: XamlPropertyIndex = XamlPropertyIndex(511i32); pub const CompositeTransform_CenterX: XamlPropertyIndex = XamlPropertyIndex(514i32); pub const CompositeTransform_CenterY: XamlPropertyIndex = XamlPropertyIndex(515i32); pub const CompositeTransform_Rotation: XamlPropertyIndex = XamlPropertyIndex(516i32); pub const CompositeTransform_ScaleX: XamlPropertyIndex = XamlPropertyIndex(517i32); pub const CompositeTransform_ScaleY: XamlPropertyIndex = XamlPropertyIndex(518i32); pub const CompositeTransform_SkewX: XamlPropertyIndex = XamlPropertyIndex(519i32); pub const CompositeTransform_SkewY: XamlPropertyIndex = XamlPropertyIndex(520i32); pub const CompositeTransform_TranslateX: XamlPropertyIndex = XamlPropertyIndex(521i32); pub const CompositeTransform_TranslateY: XamlPropertyIndex = XamlPropertyIndex(522i32); pub const ContentPresenter_CharacterSpacing: XamlPropertyIndex = XamlPropertyIndex(523i32); pub const ContentPresenter_Content: XamlPropertyIndex = XamlPropertyIndex(524i32); pub const ContentPresenter_ContentTemplate: XamlPropertyIndex = XamlPropertyIndex(525i32); pub const ContentPresenter_ContentTemplateSelector: XamlPropertyIndex = XamlPropertyIndex(526i32); pub const ContentPresenter_ContentTransitions: XamlPropertyIndex = XamlPropertyIndex(527i32); pub const ContentPresenter_FontFamily: XamlPropertyIndex = XamlPropertyIndex(528i32); pub const ContentPresenter_FontSize: XamlPropertyIndex = XamlPropertyIndex(529i32); pub const ContentPresenter_FontStretch: XamlPropertyIndex = XamlPropertyIndex(530i32); pub const ContentPresenter_FontStyle: XamlPropertyIndex = XamlPropertyIndex(531i32); pub const ContentPresenter_FontWeight: XamlPropertyIndex = XamlPropertyIndex(532i32); pub const ContentPresenter_Foreground: XamlPropertyIndex = XamlPropertyIndex(533i32); pub const ContentPresenter_IsTextScaleFactorEnabled: XamlPropertyIndex = XamlPropertyIndex(534i32); pub const ContentPresenter_LineStackingStrategy: XamlPropertyIndex = XamlPropertyIndex(535i32); pub const ContentPresenter_MaxLines: XamlPropertyIndex = XamlPropertyIndex(536i32); pub const ContentPresenter_OpticalMarginAlignment: XamlPropertyIndex = XamlPropertyIndex(537i32); pub const ContentPresenter_TextLineBounds: XamlPropertyIndex = XamlPropertyIndex(539i32); pub const ContentPresenter_TextWrapping: XamlPropertyIndex = XamlPropertyIndex(540i32); pub const Control_Background: XamlPropertyIndex = XamlPropertyIndex(541i32); pub const Control_BorderBrush: XamlPropertyIndex = XamlPropertyIndex(542i32); pub const Control_BorderThickness: XamlPropertyIndex = XamlPropertyIndex(543i32); pub const Control_CharacterSpacing: XamlPropertyIndex = XamlPropertyIndex(544i32); pub const Control_FocusState: XamlPropertyIndex = XamlPropertyIndex(546i32); pub const Control_FontFamily: XamlPropertyIndex = XamlPropertyIndex(547i32); pub const Control_FontSize: XamlPropertyIndex = XamlPropertyIndex(548i32); pub const Control_FontStretch: XamlPropertyIndex = XamlPropertyIndex(549i32); pub const Control_FontStyle: XamlPropertyIndex = XamlPropertyIndex(550i32); pub const Control_FontWeight: XamlPropertyIndex = XamlPropertyIndex(551i32); pub const Control_Foreground: XamlPropertyIndex = XamlPropertyIndex(552i32); pub const Control_HorizontalContentAlignment: XamlPropertyIndex = XamlPropertyIndex(553i32); pub const Control_IsEnabled: XamlPropertyIndex = XamlPropertyIndex(554i32); pub const Control_IsTabStop: XamlPropertyIndex = XamlPropertyIndex(555i32); pub const Control_IsTextScaleFactorEnabled: XamlPropertyIndex = XamlPropertyIndex(556i32); pub const Control_Padding: XamlPropertyIndex = XamlPropertyIndex(557i32); pub const Control_TabIndex: XamlPropertyIndex = XamlPropertyIndex(558i32); pub const Control_TabNavigation: XamlPropertyIndex = XamlPropertyIndex(559i32); pub const Control_Template: XamlPropertyIndex = XamlPropertyIndex(560i32); pub const Control_VerticalContentAlignment: XamlPropertyIndex = XamlPropertyIndex(561i32); pub const DragItemThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(565i32); pub const DragOverThemeAnimation_Direction: XamlPropertyIndex = XamlPropertyIndex(566i32); pub const DragOverThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(567i32); pub const DragOverThemeAnimation_ToOffset: XamlPropertyIndex = XamlPropertyIndex(568i32); pub const DropTargetItemThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(569i32); pub const FadeInThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(570i32); pub const FadeOutThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(571i32); pub const Glyphs_Fill: XamlPropertyIndex = XamlPropertyIndex(574i32); pub const Glyphs_FontRenderingEmSize: XamlPropertyIndex = XamlPropertyIndex(575i32); pub const Glyphs_FontUri: XamlPropertyIndex = XamlPropertyIndex(576i32); pub const Glyphs_Indices: XamlPropertyIndex = XamlPropertyIndex(577i32); pub const Glyphs_OriginX: XamlPropertyIndex = XamlPropertyIndex(578i32); pub const Glyphs_OriginY: XamlPropertyIndex = XamlPropertyIndex(579i32); pub const Glyphs_StyleSimulations: XamlPropertyIndex = XamlPropertyIndex(580i32); pub const Glyphs_UnicodeString: XamlPropertyIndex = XamlPropertyIndex(581i32); pub const IconElement_Foreground: XamlPropertyIndex = XamlPropertyIndex(584i32); pub const Image_NineGrid: XamlPropertyIndex = XamlPropertyIndex(586i32); pub const Image_PlayToSource: XamlPropertyIndex = XamlPropertyIndex(587i32); pub const Image_Source: XamlPropertyIndex = XamlPropertyIndex(588i32); pub const Image_Stretch: XamlPropertyIndex = XamlPropertyIndex(589i32); pub const ImageBrush_ImageSource: XamlPropertyIndex = XamlPropertyIndex(591i32); pub const InlineUIContainer_Child: XamlPropertyIndex = XamlPropertyIndex(592i32); pub const ItemsPresenter_Footer: XamlPropertyIndex = XamlPropertyIndex(594i32); pub const ItemsPresenter_FooterTemplate: XamlPropertyIndex = XamlPropertyIndex(595i32); pub const ItemsPresenter_FooterTransitions: XamlPropertyIndex = XamlPropertyIndex(596i32); pub const ItemsPresenter_Header: XamlPropertyIndex = XamlPropertyIndex(597i32); pub const ItemsPresenter_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(598i32); pub const ItemsPresenter_HeaderTransitions: XamlPropertyIndex = XamlPropertyIndex(599i32); pub const ItemsPresenter_Padding: XamlPropertyIndex = XamlPropertyIndex(601i32); pub const LinearGradientBrush_EndPoint: XamlPropertyIndex = XamlPropertyIndex(602i32); pub const LinearGradientBrush_StartPoint: XamlPropertyIndex = XamlPropertyIndex(603i32); pub const MatrixTransform_Matrix: XamlPropertyIndex = XamlPropertyIndex(604i32); pub const MediaElement_ActualStereo3DVideoPackingMode: XamlPropertyIndex = XamlPropertyIndex(605i32); pub const MediaElement_AreTransportControlsEnabled: XamlPropertyIndex = XamlPropertyIndex(606i32); pub const MediaElement_AspectRatioHeight: XamlPropertyIndex = XamlPropertyIndex(607i32); pub const MediaElement_AspectRatioWidth: XamlPropertyIndex = XamlPropertyIndex(608i32); pub const MediaElement_AudioCategory: XamlPropertyIndex = XamlPropertyIndex(609i32); pub const MediaElement_AudioDeviceType: XamlPropertyIndex = XamlPropertyIndex(610i32); pub const MediaElement_AudioStreamCount: XamlPropertyIndex = XamlPropertyIndex(611i32); pub const MediaElement_AudioStreamIndex: XamlPropertyIndex = XamlPropertyIndex(612i32); pub const MediaElement_AutoPlay: XamlPropertyIndex = XamlPropertyIndex(613i32); pub const MediaElement_Balance: XamlPropertyIndex = XamlPropertyIndex(614i32); pub const MediaElement_BufferingProgress: XamlPropertyIndex = XamlPropertyIndex(615i32); pub const MediaElement_CanPause: XamlPropertyIndex = XamlPropertyIndex(616i32); pub const MediaElement_CanSeek: XamlPropertyIndex = XamlPropertyIndex(617i32); pub const MediaElement_CurrentState: XamlPropertyIndex = XamlPropertyIndex(618i32); pub const MediaElement_DefaultPlaybackRate: XamlPropertyIndex = XamlPropertyIndex(619i32); pub const MediaElement_DownloadProgress: XamlPropertyIndex = XamlPropertyIndex(620i32); pub const MediaElement_DownloadProgressOffset: XamlPropertyIndex = XamlPropertyIndex(621i32); pub const MediaElement_IsAudioOnly: XamlPropertyIndex = XamlPropertyIndex(623i32); pub const MediaElement_IsFullWindow: XamlPropertyIndex = XamlPropertyIndex(624i32); pub const MediaElement_IsLooping: XamlPropertyIndex = XamlPropertyIndex(625i32); pub const MediaElement_IsMuted: XamlPropertyIndex = XamlPropertyIndex(626i32); pub const MediaElement_IsStereo3DVideo: XamlPropertyIndex = XamlPropertyIndex(627i32); pub const MediaElement_Markers: XamlPropertyIndex = XamlPropertyIndex(628i32); pub const MediaElement_NaturalDuration: XamlPropertyIndex = XamlPropertyIndex(629i32); pub const MediaElement_NaturalVideoHeight: XamlPropertyIndex = XamlPropertyIndex(630i32); pub const MediaElement_NaturalVideoWidth: XamlPropertyIndex = XamlPropertyIndex(631i32); pub const MediaElement_PlaybackRate: XamlPropertyIndex = XamlPropertyIndex(632i32); pub const MediaElement_PlayToPreferredSourceUri: XamlPropertyIndex = XamlPropertyIndex(633i32); pub const MediaElement_PlayToSource: XamlPropertyIndex = XamlPropertyIndex(634i32); pub const MediaElement_Position: XamlPropertyIndex = XamlPropertyIndex(635i32); pub const MediaElement_PosterSource: XamlPropertyIndex = XamlPropertyIndex(636i32); pub const MediaElement_ProtectionManager: XamlPropertyIndex = XamlPropertyIndex(637i32); pub const MediaElement_RealTimePlayback: XamlPropertyIndex = XamlPropertyIndex(638i32); pub const MediaElement_Source: XamlPropertyIndex = XamlPropertyIndex(639i32); pub const MediaElement_Stereo3DVideoPackingMode: XamlPropertyIndex = XamlPropertyIndex(640i32); pub const MediaElement_Stereo3DVideoRenderMode: XamlPropertyIndex = XamlPropertyIndex(641i32); pub const MediaElement_Stretch: XamlPropertyIndex = XamlPropertyIndex(642i32); pub const MediaElement_TransportControls: XamlPropertyIndex = XamlPropertyIndex(643i32); pub const MediaElement_Volume: XamlPropertyIndex = XamlPropertyIndex(644i32); pub const Panel_Background: XamlPropertyIndex = XamlPropertyIndex(647i32); pub const Panel_Children: XamlPropertyIndex = XamlPropertyIndex(648i32); pub const Panel_ChildrenTransitions: XamlPropertyIndex = XamlPropertyIndex(649i32); pub const Panel_IsItemsHost: XamlPropertyIndex = XamlPropertyIndex(651i32); pub const Paragraph_Inlines: XamlPropertyIndex = XamlPropertyIndex(652i32); pub const Paragraph_TextIndent: XamlPropertyIndex = XamlPropertyIndex(653i32); pub const PointerDownThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(660i32); pub const PointerUpThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(662i32); pub const PopInThemeAnimation_FromHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(664i32); pub const PopInThemeAnimation_FromVerticalOffset: XamlPropertyIndex = XamlPropertyIndex(665i32); pub const PopInThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(666i32); pub const PopOutThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(667i32); pub const Popup_Child: XamlPropertyIndex = XamlPropertyIndex(668i32); pub const Popup_ChildTransitions: XamlPropertyIndex = XamlPropertyIndex(669i32); pub const Popup_HorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(670i32); pub const Popup_IsLightDismissEnabled: XamlPropertyIndex = XamlPropertyIndex(673i32); pub const Popup_IsOpen: XamlPropertyIndex = XamlPropertyIndex(674i32); pub const Popup_VerticalOffset: XamlPropertyIndex = XamlPropertyIndex(676i32); pub const RepositionThemeAnimation_FromHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(683i32); pub const RepositionThemeAnimation_FromVerticalOffset: XamlPropertyIndex = XamlPropertyIndex(684i32); pub const RepositionThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(685i32); pub const ResourceDictionary_MergedDictionaries: XamlPropertyIndex = XamlPropertyIndex(687i32); pub const ResourceDictionary_Source: XamlPropertyIndex = XamlPropertyIndex(688i32); pub const ResourceDictionary_ThemeDictionaries: XamlPropertyIndex = XamlPropertyIndex(689i32); pub const RichTextBlock_Blocks: XamlPropertyIndex = XamlPropertyIndex(691i32); pub const RichTextBlock_CharacterSpacing: XamlPropertyIndex = XamlPropertyIndex(692i32); pub const RichTextBlock_FontFamily: XamlPropertyIndex = XamlPropertyIndex(693i32); pub const RichTextBlock_FontSize: XamlPropertyIndex = XamlPropertyIndex(694i32); pub const RichTextBlock_FontStretch: XamlPropertyIndex = XamlPropertyIndex(695i32); pub const RichTextBlock_FontStyle: XamlPropertyIndex = XamlPropertyIndex(696i32); pub const RichTextBlock_FontWeight: XamlPropertyIndex = XamlPropertyIndex(697i32); pub const RichTextBlock_Foreground: XamlPropertyIndex = XamlPropertyIndex(698i32); pub const RichTextBlock_HasOverflowContent: XamlPropertyIndex = XamlPropertyIndex(699i32); pub const RichTextBlock_IsColorFontEnabled: XamlPropertyIndex = XamlPropertyIndex(700i32); pub const RichTextBlock_IsTextScaleFactorEnabled: XamlPropertyIndex = XamlPropertyIndex(701i32); pub const RichTextBlock_IsTextSelectionEnabled: XamlPropertyIndex = XamlPropertyIndex(702i32); pub const RichTextBlock_LineHeight: XamlPropertyIndex = XamlPropertyIndex(703i32); pub const RichTextBlock_LineStackingStrategy: XamlPropertyIndex = XamlPropertyIndex(704i32); pub const RichTextBlock_MaxLines: XamlPropertyIndex = XamlPropertyIndex(705i32); pub const RichTextBlock_OpticalMarginAlignment: XamlPropertyIndex = XamlPropertyIndex(706i32); pub const RichTextBlock_OverflowContentTarget: XamlPropertyIndex = XamlPropertyIndex(707i32); pub const RichTextBlock_Padding: XamlPropertyIndex = XamlPropertyIndex(708i32); pub const RichTextBlock_SelectedText: XamlPropertyIndex = XamlPropertyIndex(709i32); pub const RichTextBlock_SelectionHighlightColor: XamlPropertyIndex = XamlPropertyIndex(710i32); pub const RichTextBlock_TextAlignment: XamlPropertyIndex = XamlPropertyIndex(711i32); pub const RichTextBlock_TextIndent: XamlPropertyIndex = XamlPropertyIndex(712i32); pub const RichTextBlock_TextLineBounds: XamlPropertyIndex = XamlPropertyIndex(713i32); pub const RichTextBlock_TextReadingOrder: XamlPropertyIndex = XamlPropertyIndex(714i32); pub const RichTextBlock_TextTrimming: XamlPropertyIndex = XamlPropertyIndex(715i32); pub const RichTextBlock_TextWrapping: XamlPropertyIndex = XamlPropertyIndex(716i32); pub const RichTextBlockOverflow_HasOverflowContent: XamlPropertyIndex = XamlPropertyIndex(717i32); pub const RichTextBlockOverflow_MaxLines: XamlPropertyIndex = XamlPropertyIndex(718i32); pub const RichTextBlockOverflow_OverflowContentTarget: XamlPropertyIndex = XamlPropertyIndex(719i32); pub const RichTextBlockOverflow_Padding: XamlPropertyIndex = XamlPropertyIndex(720i32); pub const RotateTransform_Angle: XamlPropertyIndex = XamlPropertyIndex(721i32); pub const RotateTransform_CenterX: XamlPropertyIndex = XamlPropertyIndex(722i32); pub const RotateTransform_CenterY: XamlPropertyIndex = XamlPropertyIndex(723i32); pub const Run_FlowDirection: XamlPropertyIndex = XamlPropertyIndex(725i32); pub const Run_Text: XamlPropertyIndex = XamlPropertyIndex(726i32); pub const ScaleTransform_CenterX: XamlPropertyIndex = XamlPropertyIndex(727i32); pub const ScaleTransform_CenterY: XamlPropertyIndex = XamlPropertyIndex(728i32); pub const ScaleTransform_ScaleX: XamlPropertyIndex = XamlPropertyIndex(729i32); pub const ScaleTransform_ScaleY: XamlPropertyIndex = XamlPropertyIndex(730i32); pub const SetterBaseCollection_IsSealed: XamlPropertyIndex = XamlPropertyIndex(732i32); pub const Shape_Fill: XamlPropertyIndex = XamlPropertyIndex(733i32); pub const Shape_GeometryTransform: XamlPropertyIndex = XamlPropertyIndex(734i32); pub const Shape_Stretch: XamlPropertyIndex = XamlPropertyIndex(735i32); pub const Shape_Stroke: XamlPropertyIndex = XamlPropertyIndex(736i32); pub const Shape_StrokeDashArray: XamlPropertyIndex = XamlPropertyIndex(737i32); pub const Shape_StrokeDashCap: XamlPropertyIndex = XamlPropertyIndex(738i32); pub const Shape_StrokeDashOffset: XamlPropertyIndex = XamlPropertyIndex(739i32); pub const Shape_StrokeEndLineCap: XamlPropertyIndex = XamlPropertyIndex(740i32); pub const Shape_StrokeLineJoin: XamlPropertyIndex = XamlPropertyIndex(741i32); pub const Shape_StrokeMiterLimit: XamlPropertyIndex = XamlPropertyIndex(742i32); pub const Shape_StrokeStartLineCap: XamlPropertyIndex = XamlPropertyIndex(743i32); pub const Shape_StrokeThickness: XamlPropertyIndex = XamlPropertyIndex(744i32); pub const SkewTransform_AngleX: XamlPropertyIndex = XamlPropertyIndex(745i32); pub const SkewTransform_AngleY: XamlPropertyIndex = XamlPropertyIndex(746i32); pub const SkewTransform_CenterX: XamlPropertyIndex = XamlPropertyIndex(747i32); pub const SkewTransform_CenterY: XamlPropertyIndex = XamlPropertyIndex(748i32); pub const Span_Inlines: XamlPropertyIndex = XamlPropertyIndex(749i32); pub const SplitCloseThemeAnimation_ClosedLength: XamlPropertyIndex = XamlPropertyIndex(750i32); pub const SplitCloseThemeAnimation_ClosedTarget: XamlPropertyIndex = XamlPropertyIndex(751i32); pub const SplitCloseThemeAnimation_ClosedTargetName: XamlPropertyIndex = XamlPropertyIndex(752i32); pub const SplitCloseThemeAnimation_ContentTarget: XamlPropertyIndex = XamlPropertyIndex(753i32); pub const SplitCloseThemeAnimation_ContentTargetName: XamlPropertyIndex = XamlPropertyIndex(754i32); pub const SplitCloseThemeAnimation_ContentTranslationDirection: XamlPropertyIndex = XamlPropertyIndex(755i32); pub const SplitCloseThemeAnimation_ContentTranslationOffset: XamlPropertyIndex = XamlPropertyIndex(756i32); pub const SplitCloseThemeAnimation_OffsetFromCenter: XamlPropertyIndex = XamlPropertyIndex(757i32); pub const SplitCloseThemeAnimation_OpenedLength: XamlPropertyIndex = XamlPropertyIndex(758i32); pub const SplitCloseThemeAnimation_OpenedTarget: XamlPropertyIndex = XamlPropertyIndex(759i32); pub const SplitCloseThemeAnimation_OpenedTargetName: XamlPropertyIndex = XamlPropertyIndex(760i32); pub const SplitOpenThemeAnimation_ClosedLength: XamlPropertyIndex = XamlPropertyIndex(761i32); pub const SplitOpenThemeAnimation_ClosedTarget: XamlPropertyIndex = XamlPropertyIndex(762i32); pub const SplitOpenThemeAnimation_ClosedTargetName: XamlPropertyIndex = XamlPropertyIndex(763i32); pub const SplitOpenThemeAnimation_ContentTarget: XamlPropertyIndex = XamlPropertyIndex(764i32); pub const SplitOpenThemeAnimation_ContentTargetName: XamlPropertyIndex = XamlPropertyIndex(765i32); pub const SplitOpenThemeAnimation_ContentTranslationDirection: XamlPropertyIndex = XamlPropertyIndex(766i32); pub const SplitOpenThemeAnimation_ContentTranslationOffset: XamlPropertyIndex = XamlPropertyIndex(767i32); pub const SplitOpenThemeAnimation_OffsetFromCenter: XamlPropertyIndex = XamlPropertyIndex(768i32); pub const SplitOpenThemeAnimation_OpenedLength: XamlPropertyIndex = XamlPropertyIndex(769i32); pub const SplitOpenThemeAnimation_OpenedTarget: XamlPropertyIndex = XamlPropertyIndex(770i32); pub const SplitOpenThemeAnimation_OpenedTargetName: XamlPropertyIndex = XamlPropertyIndex(771i32); pub const Storyboard_Children: XamlPropertyIndex = XamlPropertyIndex(772i32); pub const Storyboard_TargetName: XamlPropertyIndex = XamlPropertyIndex(774i32); pub const Storyboard_TargetProperty: XamlPropertyIndex = XamlPropertyIndex(775i32); pub const SwipeBackThemeAnimation_FromHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(776i32); pub const SwipeBackThemeAnimation_FromVerticalOffset: XamlPropertyIndex = XamlPropertyIndex(777i32); pub const SwipeBackThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(778i32); pub const SwipeHintThemeAnimation_TargetName: XamlPropertyIndex = XamlPropertyIndex(779i32); pub const SwipeHintThemeAnimation_ToHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(780i32); pub const SwipeHintThemeAnimation_ToVerticalOffset: XamlPropertyIndex = XamlPropertyIndex(781i32); pub const TextBlock_CharacterSpacing: XamlPropertyIndex = XamlPropertyIndex(782i32); pub const TextBlock_FontFamily: XamlPropertyIndex = XamlPropertyIndex(783i32); pub const TextBlock_FontSize: XamlPropertyIndex = XamlPropertyIndex(784i32); pub const TextBlock_FontStretch: XamlPropertyIndex = XamlPropertyIndex(785i32); pub const TextBlock_FontStyle: XamlPropertyIndex = XamlPropertyIndex(786i32); pub const TextBlock_FontWeight: XamlPropertyIndex = XamlPropertyIndex(787i32); pub const TextBlock_Foreground: XamlPropertyIndex = XamlPropertyIndex(788i32); pub const TextBlock_Inlines: XamlPropertyIndex = XamlPropertyIndex(789i32); pub const TextBlock_IsColorFontEnabled: XamlPropertyIndex = XamlPropertyIndex(790i32); pub const TextBlock_IsTextScaleFactorEnabled: XamlPropertyIndex = XamlPropertyIndex(791i32); pub const TextBlock_IsTextSelectionEnabled: XamlPropertyIndex = XamlPropertyIndex(792i32); pub const TextBlock_LineHeight: XamlPropertyIndex = XamlPropertyIndex(793i32); pub const TextBlock_LineStackingStrategy: XamlPropertyIndex = XamlPropertyIndex(794i32); pub const TextBlock_MaxLines: XamlPropertyIndex = XamlPropertyIndex(795i32); pub const TextBlock_OpticalMarginAlignment: XamlPropertyIndex = XamlPropertyIndex(796i32); pub const TextBlock_Padding: XamlPropertyIndex = XamlPropertyIndex(797i32); pub const TextBlock_SelectedText: XamlPropertyIndex = XamlPropertyIndex(798i32); pub const TextBlock_SelectionHighlightColor: XamlPropertyIndex = XamlPropertyIndex(799i32); pub const TextBlock_Text: XamlPropertyIndex = XamlPropertyIndex(800i32); pub const TextBlock_TextAlignment: XamlPropertyIndex = XamlPropertyIndex(801i32); pub const TextBlock_TextDecorations: XamlPropertyIndex = XamlPropertyIndex(802i32); pub const TextBlock_TextLineBounds: XamlPropertyIndex = XamlPropertyIndex(803i32); pub const TextBlock_TextReadingOrder: XamlPropertyIndex = XamlPropertyIndex(804i32); pub const TextBlock_TextTrimming: XamlPropertyIndex = XamlPropertyIndex(805i32); pub const TextBlock_TextWrapping: XamlPropertyIndex = XamlPropertyIndex(806i32); pub const TransformGroup_Children: XamlPropertyIndex = XamlPropertyIndex(811i32); pub const TransformGroup_Value: XamlPropertyIndex = XamlPropertyIndex(812i32); pub const TranslateTransform_X: XamlPropertyIndex = XamlPropertyIndex(814i32); pub const TranslateTransform_Y: XamlPropertyIndex = XamlPropertyIndex(815i32); pub const Viewbox_Child: XamlPropertyIndex = XamlPropertyIndex(819i32); pub const Viewbox_Stretch: XamlPropertyIndex = XamlPropertyIndex(820i32); pub const Viewbox_StretchDirection: XamlPropertyIndex = XamlPropertyIndex(821i32); pub const WebViewBrush_SourceName: XamlPropertyIndex = XamlPropertyIndex(825i32); pub const AppBarSeparator_IsCompact: XamlPropertyIndex = XamlPropertyIndex(826i32); pub const BitmapIcon_UriSource: XamlPropertyIndex = XamlPropertyIndex(827i32); pub const Canvas_Left: XamlPropertyIndex = XamlPropertyIndex(828i32); pub const Canvas_Top: XamlPropertyIndex = XamlPropertyIndex(829i32); pub const Canvas_ZIndex: XamlPropertyIndex = XamlPropertyIndex(830i32); pub const ContentControl_Content: XamlPropertyIndex = XamlPropertyIndex(832i32); pub const ContentControl_ContentTemplate: XamlPropertyIndex = XamlPropertyIndex(833i32); pub const ContentControl_ContentTemplateSelector: XamlPropertyIndex = XamlPropertyIndex(834i32); pub const ContentControl_ContentTransitions: XamlPropertyIndex = XamlPropertyIndex(835i32); pub const DatePicker_CalendarIdentifier: XamlPropertyIndex = XamlPropertyIndex(837i32); pub const DatePicker_Date: XamlPropertyIndex = XamlPropertyIndex(838i32); pub const DatePicker_DayFormat: XamlPropertyIndex = XamlPropertyIndex(839i32); pub const DatePicker_DayVisible: XamlPropertyIndex = XamlPropertyIndex(840i32); pub const DatePicker_Header: XamlPropertyIndex = XamlPropertyIndex(841i32); pub const DatePicker_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(842i32); pub const DatePicker_MaxYear: XamlPropertyIndex = XamlPropertyIndex(843i32); pub const DatePicker_MinYear: XamlPropertyIndex = XamlPropertyIndex(844i32); pub const DatePicker_MonthFormat: XamlPropertyIndex = XamlPropertyIndex(845i32); pub const DatePicker_MonthVisible: XamlPropertyIndex = XamlPropertyIndex(846i32); pub const DatePicker_Orientation: XamlPropertyIndex = XamlPropertyIndex(847i32); pub const DatePicker_YearFormat: XamlPropertyIndex = XamlPropertyIndex(848i32); pub const DatePicker_YearVisible: XamlPropertyIndex = XamlPropertyIndex(849i32); pub const FontIcon_FontFamily: XamlPropertyIndex = XamlPropertyIndex(851i32); pub const FontIcon_FontSize: XamlPropertyIndex = XamlPropertyIndex(852i32); pub const FontIcon_FontStyle: XamlPropertyIndex = XamlPropertyIndex(853i32); pub const FontIcon_FontWeight: XamlPropertyIndex = XamlPropertyIndex(854i32); pub const FontIcon_Glyph: XamlPropertyIndex = XamlPropertyIndex(855i32); pub const FontIcon_IsTextScaleFactorEnabled: XamlPropertyIndex = XamlPropertyIndex(856i32); pub const Grid_Column: XamlPropertyIndex = XamlPropertyIndex(857i32); pub const Grid_ColumnDefinitions: XamlPropertyIndex = XamlPropertyIndex(858i32); pub const Grid_ColumnSpan: XamlPropertyIndex = XamlPropertyIndex(859i32); pub const Grid_Row: XamlPropertyIndex = XamlPropertyIndex(860i32); pub const Grid_RowDefinitions: XamlPropertyIndex = XamlPropertyIndex(861i32); pub const Grid_RowSpan: XamlPropertyIndex = XamlPropertyIndex(862i32); pub const Hub_DefaultSectionIndex: XamlPropertyIndex = XamlPropertyIndex(863i32); pub const Hub_Header: XamlPropertyIndex = XamlPropertyIndex(864i32); pub const Hub_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(865i32); pub const Hub_IsActiveView: XamlPropertyIndex = XamlPropertyIndex(866i32); pub const Hub_IsZoomedInView: XamlPropertyIndex = XamlPropertyIndex(867i32); pub const Hub_Orientation: XamlPropertyIndex = XamlPropertyIndex(868i32); pub const Hub_SectionHeaders: XamlPropertyIndex = XamlPropertyIndex(869i32); pub const Hub_Sections: XamlPropertyIndex = XamlPropertyIndex(870i32); pub const Hub_SectionsInView: XamlPropertyIndex = XamlPropertyIndex(871i32); pub const Hub_SemanticZoomOwner: XamlPropertyIndex = XamlPropertyIndex(872i32); pub const HubSection_ContentTemplate: XamlPropertyIndex = XamlPropertyIndex(873i32); pub const HubSection_Header: XamlPropertyIndex = XamlPropertyIndex(874i32); pub const HubSection_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(875i32); pub const HubSection_IsHeaderInteractive: XamlPropertyIndex = XamlPropertyIndex(876i32); pub const Hyperlink_NavigateUri: XamlPropertyIndex = XamlPropertyIndex(877i32); pub const ItemsControl_DisplayMemberPath: XamlPropertyIndex = XamlPropertyIndex(879i32); pub const ItemsControl_GroupStyle: XamlPropertyIndex = XamlPropertyIndex(880i32); pub const ItemsControl_GroupStyleSelector: XamlPropertyIndex = XamlPropertyIndex(881i32); pub const ItemsControl_IsGrouping: XamlPropertyIndex = XamlPropertyIndex(882i32); pub const ItemsControl_ItemContainerStyle: XamlPropertyIndex = XamlPropertyIndex(884i32); pub const ItemsControl_ItemContainerStyleSelector: XamlPropertyIndex = XamlPropertyIndex(885i32); pub const ItemsControl_ItemContainerTransitions: XamlPropertyIndex = XamlPropertyIndex(886i32); pub const ItemsControl_Items: XamlPropertyIndex = XamlPropertyIndex(887i32); pub const ItemsControl_ItemsPanel: XamlPropertyIndex = XamlPropertyIndex(889i32); pub const ItemsControl_ItemsSource: XamlPropertyIndex = XamlPropertyIndex(890i32); pub const ItemsControl_ItemTemplate: XamlPropertyIndex = XamlPropertyIndex(891i32); pub const ItemsControl_ItemTemplateSelector: XamlPropertyIndex = XamlPropertyIndex(892i32); pub const Line_X1: XamlPropertyIndex = XamlPropertyIndex(893i32); pub const Line_X2: XamlPropertyIndex = XamlPropertyIndex(894i32); pub const Line_Y1: XamlPropertyIndex = XamlPropertyIndex(895i32); pub const Line_Y2: XamlPropertyIndex = XamlPropertyIndex(896i32); pub const MediaTransportControls_IsFastForwardButtonVisible: XamlPropertyIndex = XamlPropertyIndex(898i32); pub const MediaTransportControls_IsFastRewindButtonVisible: XamlPropertyIndex = XamlPropertyIndex(900i32); pub const MediaTransportControls_IsFullWindowButtonVisible: XamlPropertyIndex = XamlPropertyIndex(902i32); pub const MediaTransportControls_IsPlaybackRateButtonVisible: XamlPropertyIndex = XamlPropertyIndex(904i32); pub const MediaTransportControls_IsSeekBarVisible: XamlPropertyIndex = XamlPropertyIndex(905i32); pub const MediaTransportControls_IsStopButtonVisible: XamlPropertyIndex = XamlPropertyIndex(908i32); pub const MediaTransportControls_IsVolumeButtonVisible: XamlPropertyIndex = XamlPropertyIndex(910i32); pub const MediaTransportControls_IsZoomButtonVisible: XamlPropertyIndex = XamlPropertyIndex(912i32); pub const PasswordBox_Header: XamlPropertyIndex = XamlPropertyIndex(913i32); pub const PasswordBox_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(914i32); pub const PasswordBox_IsPasswordRevealButtonEnabled: XamlPropertyIndex = XamlPropertyIndex(915i32); pub const PasswordBox_MaxLength: XamlPropertyIndex = XamlPropertyIndex(916i32); pub const PasswordBox_Password: XamlPropertyIndex = XamlPropertyIndex(917i32); pub const PasswordBox_PasswordChar: XamlPropertyIndex = XamlPropertyIndex(918i32); pub const PasswordBox_PlaceholderText: XamlPropertyIndex = XamlPropertyIndex(919i32); pub const PasswordBox_PreventKeyboardDisplayOnProgrammaticFocus: XamlPropertyIndex = XamlPropertyIndex(920i32); pub const PasswordBox_SelectionHighlightColor: XamlPropertyIndex = XamlPropertyIndex(921i32); pub const Path_Data: XamlPropertyIndex = XamlPropertyIndex(922i32); pub const PathIcon_Data: XamlPropertyIndex = XamlPropertyIndex(923i32); pub const Polygon_FillRule: XamlPropertyIndex = XamlPropertyIndex(924i32); pub const Polygon_Points: XamlPropertyIndex = XamlPropertyIndex(925i32); pub const Polyline_FillRule: XamlPropertyIndex = XamlPropertyIndex(926i32); pub const Polyline_Points: XamlPropertyIndex = XamlPropertyIndex(927i32); pub const ProgressRing_IsActive: XamlPropertyIndex = XamlPropertyIndex(928i32); pub const ProgressRing_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(929i32); pub const RangeBase_LargeChange: XamlPropertyIndex = XamlPropertyIndex(930i32); pub const RangeBase_Maximum: XamlPropertyIndex = XamlPropertyIndex(931i32); pub const RangeBase_Minimum: XamlPropertyIndex = XamlPropertyIndex(932i32); pub const RangeBase_SmallChange: XamlPropertyIndex = XamlPropertyIndex(933i32); pub const RangeBase_Value: XamlPropertyIndex = XamlPropertyIndex(934i32); pub const Rectangle_RadiusX: XamlPropertyIndex = XamlPropertyIndex(935i32); pub const Rectangle_RadiusY: XamlPropertyIndex = XamlPropertyIndex(936i32); pub const RichEditBox_AcceptsReturn: XamlPropertyIndex = XamlPropertyIndex(937i32); pub const RichEditBox_Header: XamlPropertyIndex = XamlPropertyIndex(938i32); pub const RichEditBox_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(939i32); pub const RichEditBox_InputScope: XamlPropertyIndex = XamlPropertyIndex(940i32); pub const RichEditBox_IsColorFontEnabled: XamlPropertyIndex = XamlPropertyIndex(941i32); pub const RichEditBox_IsReadOnly: XamlPropertyIndex = XamlPropertyIndex(942i32); pub const RichEditBox_IsSpellCheckEnabled: XamlPropertyIndex = XamlPropertyIndex(943i32); pub const RichEditBox_IsTextPredictionEnabled: XamlPropertyIndex = XamlPropertyIndex(944i32); pub const RichEditBox_PlaceholderText: XamlPropertyIndex = XamlPropertyIndex(945i32); pub const RichEditBox_PreventKeyboardDisplayOnProgrammaticFocus: XamlPropertyIndex = XamlPropertyIndex(946i32); pub const RichEditBox_SelectionHighlightColor: XamlPropertyIndex = XamlPropertyIndex(947i32); pub const RichEditBox_TextAlignment: XamlPropertyIndex = XamlPropertyIndex(948i32); pub const RichEditBox_TextWrapping: XamlPropertyIndex = XamlPropertyIndex(949i32); pub const SearchBox_ChooseSuggestionOnEnter: XamlPropertyIndex = XamlPropertyIndex(950i32); pub const SearchBox_FocusOnKeyboardInput: XamlPropertyIndex = XamlPropertyIndex(951i32); pub const SearchBox_PlaceholderText: XamlPropertyIndex = XamlPropertyIndex(952i32); pub const SearchBox_QueryText: XamlPropertyIndex = XamlPropertyIndex(953i32); pub const SearchBox_SearchHistoryContext: XamlPropertyIndex = XamlPropertyIndex(954i32); pub const SearchBox_SearchHistoryEnabled: XamlPropertyIndex = XamlPropertyIndex(955i32); pub const SemanticZoom_CanChangeViews: XamlPropertyIndex = XamlPropertyIndex(956i32); pub const SemanticZoom_IsZoomedInViewActive: XamlPropertyIndex = XamlPropertyIndex(957i32); pub const SemanticZoom_IsZoomOutButtonEnabled: XamlPropertyIndex = XamlPropertyIndex(958i32); pub const SemanticZoom_ZoomedInView: XamlPropertyIndex = XamlPropertyIndex(959i32); pub const SemanticZoom_ZoomedOutView: XamlPropertyIndex = XamlPropertyIndex(960i32); pub const StackPanel_AreScrollSnapPointsRegular: XamlPropertyIndex = XamlPropertyIndex(961i32); pub const StackPanel_Orientation: XamlPropertyIndex = XamlPropertyIndex(962i32); pub const SymbolIcon_Symbol: XamlPropertyIndex = XamlPropertyIndex(963i32); pub const TextBox_AcceptsReturn: XamlPropertyIndex = XamlPropertyIndex(964i32); pub const TextBox_Header: XamlPropertyIndex = XamlPropertyIndex(965i32); pub const TextBox_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(966i32); pub const TextBox_InputScope: XamlPropertyIndex = XamlPropertyIndex(967i32); pub const TextBox_IsColorFontEnabled: XamlPropertyIndex = XamlPropertyIndex(968i32); pub const TextBox_IsReadOnly: XamlPropertyIndex = XamlPropertyIndex(971i32); pub const TextBox_IsSpellCheckEnabled: XamlPropertyIndex = XamlPropertyIndex(972i32); pub const TextBox_IsTextPredictionEnabled: XamlPropertyIndex = XamlPropertyIndex(973i32); pub const TextBox_MaxLength: XamlPropertyIndex = XamlPropertyIndex(974i32); pub const TextBox_PlaceholderText: XamlPropertyIndex = XamlPropertyIndex(975i32); pub const TextBox_PreventKeyboardDisplayOnProgrammaticFocus: XamlPropertyIndex = XamlPropertyIndex(976i32); pub const TextBox_SelectedText: XamlPropertyIndex = XamlPropertyIndex(977i32); pub const TextBox_SelectionHighlightColor: XamlPropertyIndex = XamlPropertyIndex(978i32); pub const TextBox_SelectionLength: XamlPropertyIndex = XamlPropertyIndex(979i32); pub const TextBox_SelectionStart: XamlPropertyIndex = XamlPropertyIndex(980i32); pub const TextBox_Text: XamlPropertyIndex = XamlPropertyIndex(981i32); pub const TextBox_TextAlignment: XamlPropertyIndex = XamlPropertyIndex(982i32); pub const TextBox_TextWrapping: XamlPropertyIndex = XamlPropertyIndex(983i32); pub const Thumb_IsDragging: XamlPropertyIndex = XamlPropertyIndex(984i32); pub const TickBar_Fill: XamlPropertyIndex = XamlPropertyIndex(985i32); pub const TimePicker_ClockIdentifier: XamlPropertyIndex = XamlPropertyIndex(986i32); pub const TimePicker_Header: XamlPropertyIndex = XamlPropertyIndex(987i32); pub const TimePicker_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(988i32); pub const TimePicker_MinuteIncrement: XamlPropertyIndex = XamlPropertyIndex(989i32); pub const TimePicker_Time: XamlPropertyIndex = XamlPropertyIndex(990i32); pub const ToggleSwitch_Header: XamlPropertyIndex = XamlPropertyIndex(991i32); pub const ToggleSwitch_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(992i32); pub const ToggleSwitch_IsOn: XamlPropertyIndex = XamlPropertyIndex(993i32); pub const ToggleSwitch_OffContent: XamlPropertyIndex = XamlPropertyIndex(994i32); pub const ToggleSwitch_OffContentTemplate: XamlPropertyIndex = XamlPropertyIndex(995i32); pub const ToggleSwitch_OnContent: XamlPropertyIndex = XamlPropertyIndex(996i32); pub const ToggleSwitch_OnContentTemplate: XamlPropertyIndex = XamlPropertyIndex(997i32); pub const ToggleSwitch_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(998i32); pub const UserControl_Content: XamlPropertyIndex = XamlPropertyIndex(999i32); pub const VariableSizedWrapGrid_ColumnSpan: XamlPropertyIndex = XamlPropertyIndex(1000i32); pub const VariableSizedWrapGrid_HorizontalChildrenAlignment: XamlPropertyIndex = XamlPropertyIndex(1001i32); pub const VariableSizedWrapGrid_ItemHeight: XamlPropertyIndex = XamlPropertyIndex(1002i32); pub const VariableSizedWrapGrid_ItemWidth: XamlPropertyIndex = XamlPropertyIndex(1003i32); pub const VariableSizedWrapGrid_MaximumRowsOrColumns: XamlPropertyIndex = XamlPropertyIndex(1004i32); pub const VariableSizedWrapGrid_Orientation: XamlPropertyIndex = XamlPropertyIndex(1005i32); pub const VariableSizedWrapGrid_RowSpan: XamlPropertyIndex = XamlPropertyIndex(1006i32); pub const VariableSizedWrapGrid_VerticalChildrenAlignment: XamlPropertyIndex = XamlPropertyIndex(1007i32); pub const WebView_AllowedScriptNotifyUris: XamlPropertyIndex = XamlPropertyIndex(1008i32); pub const WebView_CanGoBack: XamlPropertyIndex = XamlPropertyIndex(1009i32); pub const WebView_CanGoForward: XamlPropertyIndex = XamlPropertyIndex(1010i32); pub const WebView_ContainsFullScreenElement: XamlPropertyIndex = XamlPropertyIndex(1011i32); pub const WebView_DataTransferPackage: XamlPropertyIndex = XamlPropertyIndex(1012i32); pub const WebView_DefaultBackgroundColor: XamlPropertyIndex = XamlPropertyIndex(1013i32); pub const WebView_DocumentTitle: XamlPropertyIndex = XamlPropertyIndex(1014i32); pub const WebView_Source: XamlPropertyIndex = XamlPropertyIndex(1015i32); pub const AppBar_ClosedDisplayMode: XamlPropertyIndex = XamlPropertyIndex(1016i32); pub const AppBar_IsOpen: XamlPropertyIndex = XamlPropertyIndex(1017i32); pub const AppBar_IsSticky: XamlPropertyIndex = XamlPropertyIndex(1018i32); pub const AutoSuggestBox_AutoMaximizeSuggestionArea: XamlPropertyIndex = XamlPropertyIndex(1019i32); pub const AutoSuggestBox_Header: XamlPropertyIndex = XamlPropertyIndex(1020i32); pub const AutoSuggestBox_IsSuggestionListOpen: XamlPropertyIndex = XamlPropertyIndex(1021i32); pub const AutoSuggestBox_MaxSuggestionListHeight: XamlPropertyIndex = XamlPropertyIndex(1022i32); pub const AutoSuggestBox_PlaceholderText: XamlPropertyIndex = XamlPropertyIndex(1023i32); pub const AutoSuggestBox_Text: XamlPropertyIndex = XamlPropertyIndex(1024i32); pub const AutoSuggestBox_TextBoxStyle: XamlPropertyIndex = XamlPropertyIndex(1025i32); pub const AutoSuggestBox_TextMemberPath: XamlPropertyIndex = XamlPropertyIndex(1026i32); pub const AutoSuggestBox_UpdateTextOnSelect: XamlPropertyIndex = XamlPropertyIndex(1027i32); pub const ButtonBase_ClickMode: XamlPropertyIndex = XamlPropertyIndex(1029i32); pub const ButtonBase_Command: XamlPropertyIndex = XamlPropertyIndex(1030i32); pub const ButtonBase_CommandParameter: XamlPropertyIndex = XamlPropertyIndex(1031i32); pub const ButtonBase_IsPointerOver: XamlPropertyIndex = XamlPropertyIndex(1032i32); pub const ButtonBase_IsPressed: XamlPropertyIndex = XamlPropertyIndex(1033i32); pub const ContentDialog_FullSizeDesired: XamlPropertyIndex = XamlPropertyIndex(1034i32); pub const ContentDialog_IsPrimaryButtonEnabled: XamlPropertyIndex = XamlPropertyIndex(1035i32); pub const ContentDialog_IsSecondaryButtonEnabled: XamlPropertyIndex = XamlPropertyIndex(1036i32); pub const ContentDialog_PrimaryButtonCommand: XamlPropertyIndex = XamlPropertyIndex(1037i32); pub const ContentDialog_PrimaryButtonCommandParameter: XamlPropertyIndex = XamlPropertyIndex(1038i32); pub const ContentDialog_PrimaryButtonText: XamlPropertyIndex = XamlPropertyIndex(1039i32); pub const ContentDialog_SecondaryButtonCommand: XamlPropertyIndex = XamlPropertyIndex(1040i32); pub const ContentDialog_SecondaryButtonCommandParameter: XamlPropertyIndex = XamlPropertyIndex(1041i32); pub const ContentDialog_SecondaryButtonText: XamlPropertyIndex = XamlPropertyIndex(1042i32); pub const ContentDialog_Title: XamlPropertyIndex = XamlPropertyIndex(1043i32); pub const ContentDialog_TitleTemplate: XamlPropertyIndex = XamlPropertyIndex(1044i32); pub const Frame_BackStack: XamlPropertyIndex = XamlPropertyIndex(1045i32); pub const Frame_BackStackDepth: XamlPropertyIndex = XamlPropertyIndex(1046i32); pub const Frame_CacheSize: XamlPropertyIndex = XamlPropertyIndex(1047i32); pub const Frame_CanGoBack: XamlPropertyIndex = XamlPropertyIndex(1048i32); pub const Frame_CanGoForward: XamlPropertyIndex = XamlPropertyIndex(1049i32); pub const Frame_CurrentSourcePageType: XamlPropertyIndex = XamlPropertyIndex(1050i32); pub const Frame_ForwardStack: XamlPropertyIndex = XamlPropertyIndex(1051i32); pub const Frame_SourcePageType: XamlPropertyIndex = XamlPropertyIndex(1052i32); pub const GridViewItemPresenter_CheckBrush: XamlPropertyIndex = XamlPropertyIndex(1053i32); pub const GridViewItemPresenter_CheckHintBrush: XamlPropertyIndex = XamlPropertyIndex(1054i32); pub const GridViewItemPresenter_CheckSelectingBrush: XamlPropertyIndex = XamlPropertyIndex(1055i32); pub const GridViewItemPresenter_ContentMargin: XamlPropertyIndex = XamlPropertyIndex(1056i32); pub const GridViewItemPresenter_DisabledOpacity: XamlPropertyIndex = XamlPropertyIndex(1057i32); pub const GridViewItemPresenter_DragBackground: XamlPropertyIndex = XamlPropertyIndex(1058i32); pub const GridViewItemPresenter_DragForeground: XamlPropertyIndex = XamlPropertyIndex(1059i32); pub const GridViewItemPresenter_DragOpacity: XamlPropertyIndex = XamlPropertyIndex(1060i32); pub const GridViewItemPresenter_FocusBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1061i32); pub const GridViewItemPresenter_GridViewItemPresenterHorizontalContentAlignment: XamlPropertyIndex = XamlPropertyIndex(1062i32); pub const GridViewItemPresenter_GridViewItemPresenterPadding: XamlPropertyIndex = XamlPropertyIndex(1063i32); pub const GridViewItemPresenter_PlaceholderBackground: XamlPropertyIndex = XamlPropertyIndex(1064i32); pub const GridViewItemPresenter_PointerOverBackground: XamlPropertyIndex = XamlPropertyIndex(1065i32); pub const GridViewItemPresenter_PointerOverBackgroundMargin: XamlPropertyIndex = XamlPropertyIndex(1066i32); pub const GridViewItemPresenter_ReorderHintOffset: XamlPropertyIndex = XamlPropertyIndex(1067i32); pub const GridViewItemPresenter_SelectedBackground: XamlPropertyIndex = XamlPropertyIndex(1068i32); pub const GridViewItemPresenter_SelectedBorderThickness: XamlPropertyIndex = XamlPropertyIndex(1069i32); pub const GridViewItemPresenter_SelectedForeground: XamlPropertyIndex = XamlPropertyIndex(1070i32); pub const GridViewItemPresenter_SelectedPointerOverBackground: XamlPropertyIndex = XamlPropertyIndex(1071i32); pub const GridViewItemPresenter_SelectedPointerOverBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1072i32); pub const GridViewItemPresenter_SelectionCheckMarkVisualEnabled: XamlPropertyIndex = XamlPropertyIndex(1073i32); pub const GridViewItemPresenter_GridViewItemPresenterVerticalContentAlignment: XamlPropertyIndex = XamlPropertyIndex(1074i32); pub const ItemsStackPanel_CacheLength: XamlPropertyIndex = XamlPropertyIndex(1076i32); pub const ItemsStackPanel_GroupHeaderPlacement: XamlPropertyIndex = XamlPropertyIndex(1077i32); pub const ItemsStackPanel_GroupPadding: XamlPropertyIndex = XamlPropertyIndex(1078i32); pub const ItemsStackPanel_ItemsUpdatingScrollMode: XamlPropertyIndex = XamlPropertyIndex(1079i32); pub const ItemsStackPanel_Orientation: XamlPropertyIndex = XamlPropertyIndex(1080i32); pub const ItemsWrapGrid_CacheLength: XamlPropertyIndex = XamlPropertyIndex(1081i32); pub const ItemsWrapGrid_GroupHeaderPlacement: XamlPropertyIndex = XamlPropertyIndex(1082i32); pub const ItemsWrapGrid_GroupPadding: XamlPropertyIndex = XamlPropertyIndex(1083i32); pub const ItemsWrapGrid_ItemHeight: XamlPropertyIndex = XamlPropertyIndex(1084i32); pub const ItemsWrapGrid_ItemWidth: XamlPropertyIndex = XamlPropertyIndex(1085i32); pub const ItemsWrapGrid_MaximumRowsOrColumns: XamlPropertyIndex = XamlPropertyIndex(1086i32); pub const ItemsWrapGrid_Orientation: XamlPropertyIndex = XamlPropertyIndex(1087i32); pub const ListViewItemPresenter_CheckBrush: XamlPropertyIndex = XamlPropertyIndex(1088i32); pub const ListViewItemPresenter_CheckHintBrush: XamlPropertyIndex = XamlPropertyIndex(1089i32); pub const ListViewItemPresenter_CheckSelectingBrush: XamlPropertyIndex = XamlPropertyIndex(1090i32); pub const ListViewItemPresenter_ContentMargin: XamlPropertyIndex = XamlPropertyIndex(1091i32); pub const ListViewItemPresenter_DisabledOpacity: XamlPropertyIndex = XamlPropertyIndex(1092i32); pub const ListViewItemPresenter_DragBackground: XamlPropertyIndex = XamlPropertyIndex(1093i32); pub const ListViewItemPresenter_DragForeground: XamlPropertyIndex = XamlPropertyIndex(1094i32); pub const ListViewItemPresenter_DragOpacity: XamlPropertyIndex = XamlPropertyIndex(1095i32); pub const ListViewItemPresenter_FocusBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1096i32); pub const ListViewItemPresenter_ListViewItemPresenterHorizontalContentAlignment: XamlPropertyIndex = XamlPropertyIndex(1097i32); pub const ListViewItemPresenter_ListViewItemPresenterPadding: XamlPropertyIndex = XamlPropertyIndex(1098i32); pub const ListViewItemPresenter_PlaceholderBackground: XamlPropertyIndex = XamlPropertyIndex(1099i32); pub const ListViewItemPresenter_PointerOverBackground: XamlPropertyIndex = XamlPropertyIndex(1100i32); pub const ListViewItemPresenter_PointerOverBackgroundMargin: XamlPropertyIndex = XamlPropertyIndex(1101i32); pub const ListViewItemPresenter_ReorderHintOffset: XamlPropertyIndex = XamlPropertyIndex(1102i32); pub const ListViewItemPresenter_SelectedBackground: XamlPropertyIndex = XamlPropertyIndex(1103i32); pub const ListViewItemPresenter_SelectedBorderThickness: XamlPropertyIndex = XamlPropertyIndex(1104i32); pub const ListViewItemPresenter_SelectedForeground: XamlPropertyIndex = XamlPropertyIndex(1105i32); pub const ListViewItemPresenter_SelectedPointerOverBackground: XamlPropertyIndex = XamlPropertyIndex(1106i32); pub const ListViewItemPresenter_SelectedPointerOverBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1107i32); pub const ListViewItemPresenter_SelectionCheckMarkVisualEnabled: XamlPropertyIndex = XamlPropertyIndex(1108i32); pub const ListViewItemPresenter_ListViewItemPresenterVerticalContentAlignment: XamlPropertyIndex = XamlPropertyIndex(1109i32); pub const MenuFlyoutItem_Command: XamlPropertyIndex = XamlPropertyIndex(1110i32); pub const MenuFlyoutItem_CommandParameter: XamlPropertyIndex = XamlPropertyIndex(1111i32); pub const MenuFlyoutItem_Text: XamlPropertyIndex = XamlPropertyIndex(1112i32); pub const Page_BottomAppBar: XamlPropertyIndex = XamlPropertyIndex(1114i32); pub const Page_Frame: XamlPropertyIndex = XamlPropertyIndex(1115i32); pub const Page_NavigationCacheMode: XamlPropertyIndex = XamlPropertyIndex(1116i32); pub const Page_TopAppBar: XamlPropertyIndex = XamlPropertyIndex(1117i32); pub const ProgressBar_IsIndeterminate: XamlPropertyIndex = XamlPropertyIndex(1118i32); pub const ProgressBar_ShowError: XamlPropertyIndex = XamlPropertyIndex(1119i32); pub const ProgressBar_ShowPaused: XamlPropertyIndex = XamlPropertyIndex(1120i32); pub const ProgressBar_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1121i32); pub const ScrollBar_IndicatorMode: XamlPropertyIndex = XamlPropertyIndex(1122i32); pub const ScrollBar_Orientation: XamlPropertyIndex = XamlPropertyIndex(1123i32); pub const ScrollBar_ViewportSize: XamlPropertyIndex = XamlPropertyIndex(1124i32); pub const Selector_IsSynchronizedWithCurrentItem: XamlPropertyIndex = XamlPropertyIndex(1126i32); pub const Selector_SelectedIndex: XamlPropertyIndex = XamlPropertyIndex(1127i32); pub const Selector_SelectedItem: XamlPropertyIndex = XamlPropertyIndex(1128i32); pub const Selector_SelectedValue: XamlPropertyIndex = XamlPropertyIndex(1129i32); pub const Selector_SelectedValuePath: XamlPropertyIndex = XamlPropertyIndex(1130i32); pub const SelectorItem_IsSelected: XamlPropertyIndex = XamlPropertyIndex(1131i32); pub const SettingsFlyout_HeaderBackground: XamlPropertyIndex = XamlPropertyIndex(1132i32); pub const SettingsFlyout_HeaderForeground: XamlPropertyIndex = XamlPropertyIndex(1133i32); pub const SettingsFlyout_IconSource: XamlPropertyIndex = XamlPropertyIndex(1134i32); pub const SettingsFlyout_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1135i32); pub const SettingsFlyout_Title: XamlPropertyIndex = XamlPropertyIndex(1136i32); pub const Slider_Header: XamlPropertyIndex = XamlPropertyIndex(1137i32); pub const Slider_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(1138i32); pub const Slider_IntermediateValue: XamlPropertyIndex = XamlPropertyIndex(1139i32); pub const Slider_IsDirectionReversed: XamlPropertyIndex = XamlPropertyIndex(1140i32); pub const Slider_IsThumbToolTipEnabled: XamlPropertyIndex = XamlPropertyIndex(1141i32); pub const Slider_Orientation: XamlPropertyIndex = XamlPropertyIndex(1142i32); pub const Slider_SnapsTo: XamlPropertyIndex = XamlPropertyIndex(1143i32); pub const Slider_StepFrequency: XamlPropertyIndex = XamlPropertyIndex(1144i32); pub const Slider_ThumbToolTipValueConverter: XamlPropertyIndex = XamlPropertyIndex(1145i32); pub const Slider_TickFrequency: XamlPropertyIndex = XamlPropertyIndex(1146i32); pub const Slider_TickPlacement: XamlPropertyIndex = XamlPropertyIndex(1147i32); pub const SwapChainPanel_CompositionScaleX: XamlPropertyIndex = XamlPropertyIndex(1148i32); pub const SwapChainPanel_CompositionScaleY: XamlPropertyIndex = XamlPropertyIndex(1149i32); pub const ToolTip_HorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(1150i32); pub const ToolTip_IsOpen: XamlPropertyIndex = XamlPropertyIndex(1151i32); pub const ToolTip_Placement: XamlPropertyIndex = XamlPropertyIndex(1152i32); pub const ToolTip_PlacementTarget: XamlPropertyIndex = XamlPropertyIndex(1153i32); pub const ToolTip_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1154i32); pub const ToolTip_VerticalOffset: XamlPropertyIndex = XamlPropertyIndex(1155i32); pub const Button_Flyout: XamlPropertyIndex = XamlPropertyIndex(1156i32); pub const ComboBox_Header: XamlPropertyIndex = XamlPropertyIndex(1157i32); pub const ComboBox_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(1158i32); pub const ComboBox_IsDropDownOpen: XamlPropertyIndex = XamlPropertyIndex(1159i32); pub const ComboBox_IsEditable: XamlPropertyIndex = XamlPropertyIndex(1160i32); pub const ComboBox_IsSelectionBoxHighlighted: XamlPropertyIndex = XamlPropertyIndex(1161i32); pub const ComboBox_MaxDropDownHeight: XamlPropertyIndex = XamlPropertyIndex(1162i32); pub const ComboBox_PlaceholderText: XamlPropertyIndex = XamlPropertyIndex(1163i32); pub const ComboBox_SelectionBoxItem: XamlPropertyIndex = XamlPropertyIndex(1164i32); pub const ComboBox_SelectionBoxItemTemplate: XamlPropertyIndex = XamlPropertyIndex(1165i32); pub const ComboBox_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1166i32); pub const CommandBar_PrimaryCommands: XamlPropertyIndex = XamlPropertyIndex(1167i32); pub const CommandBar_SecondaryCommands: XamlPropertyIndex = XamlPropertyIndex(1168i32); pub const FlipView_UseTouchAnimationsForAllNavigation: XamlPropertyIndex = XamlPropertyIndex(1169i32); pub const HyperlinkButton_NavigateUri: XamlPropertyIndex = XamlPropertyIndex(1170i32); pub const ListBox_SelectedItems: XamlPropertyIndex = XamlPropertyIndex(1171i32); pub const ListBox_SelectionMode: XamlPropertyIndex = XamlPropertyIndex(1172i32); pub const ListViewBase_CanDragItems: XamlPropertyIndex = XamlPropertyIndex(1173i32); pub const ListViewBase_CanReorderItems: XamlPropertyIndex = XamlPropertyIndex(1174i32); pub const ListViewBase_DataFetchSize: XamlPropertyIndex = XamlPropertyIndex(1175i32); pub const ListViewBase_Footer: XamlPropertyIndex = XamlPropertyIndex(1176i32); pub const ListViewBase_FooterTemplate: XamlPropertyIndex = XamlPropertyIndex(1177i32); pub const ListViewBase_FooterTransitions: XamlPropertyIndex = XamlPropertyIndex(1178i32); pub const ListViewBase_Header: XamlPropertyIndex = XamlPropertyIndex(1179i32); pub const ListViewBase_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(1180i32); pub const ListViewBase_HeaderTransitions: XamlPropertyIndex = XamlPropertyIndex(1181i32); pub const ListViewBase_IncrementalLoadingThreshold: XamlPropertyIndex = XamlPropertyIndex(1182i32); pub const ListViewBase_IncrementalLoadingTrigger: XamlPropertyIndex = XamlPropertyIndex(1183i32); pub const ListViewBase_IsActiveView: XamlPropertyIndex = XamlPropertyIndex(1184i32); pub const ListViewBase_IsItemClickEnabled: XamlPropertyIndex = XamlPropertyIndex(1185i32); pub const ListViewBase_IsSwipeEnabled: XamlPropertyIndex = XamlPropertyIndex(1186i32); pub const ListViewBase_IsZoomedInView: XamlPropertyIndex = XamlPropertyIndex(1187i32); pub const ListViewBase_ReorderMode: XamlPropertyIndex = XamlPropertyIndex(1188i32); pub const ListViewBase_SelectedItems: XamlPropertyIndex = XamlPropertyIndex(1189i32); pub const ListViewBase_SelectionMode: XamlPropertyIndex = XamlPropertyIndex(1190i32); pub const ListViewBase_SemanticZoomOwner: XamlPropertyIndex = XamlPropertyIndex(1191i32); pub const ListViewBase_ShowsScrollingPlaceholders: XamlPropertyIndex = XamlPropertyIndex(1192i32); pub const RepeatButton_Delay: XamlPropertyIndex = XamlPropertyIndex(1193i32); pub const RepeatButton_Interval: XamlPropertyIndex = XamlPropertyIndex(1194i32); pub const ScrollViewer_BringIntoViewOnFocusChange: XamlPropertyIndex = XamlPropertyIndex(1195i32); pub const ScrollViewer_ComputedHorizontalScrollBarVisibility: XamlPropertyIndex = XamlPropertyIndex(1196i32); pub const ScrollViewer_ComputedVerticalScrollBarVisibility: XamlPropertyIndex = XamlPropertyIndex(1197i32); pub const ScrollViewer_ExtentHeight: XamlPropertyIndex = XamlPropertyIndex(1198i32); pub const ScrollViewer_ExtentWidth: XamlPropertyIndex = XamlPropertyIndex(1199i32); pub const ScrollViewer_HorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(1200i32); pub const ScrollViewer_HorizontalScrollBarVisibility: XamlPropertyIndex = XamlPropertyIndex(1201i32); pub const ScrollViewer_HorizontalScrollMode: XamlPropertyIndex = XamlPropertyIndex(1202i32); pub const ScrollViewer_HorizontalSnapPointsAlignment: XamlPropertyIndex = XamlPropertyIndex(1203i32); pub const ScrollViewer_HorizontalSnapPointsType: XamlPropertyIndex = XamlPropertyIndex(1204i32); pub const ScrollViewer_IsDeferredScrollingEnabled: XamlPropertyIndex = XamlPropertyIndex(1205i32); pub const ScrollViewer_IsHorizontalRailEnabled: XamlPropertyIndex = XamlPropertyIndex(1206i32); pub const ScrollViewer_IsHorizontalScrollChainingEnabled: XamlPropertyIndex = XamlPropertyIndex(1207i32); pub const ScrollViewer_IsScrollInertiaEnabled: XamlPropertyIndex = XamlPropertyIndex(1208i32); pub const ScrollViewer_IsVerticalRailEnabled: XamlPropertyIndex = XamlPropertyIndex(1209i32); pub const ScrollViewer_IsVerticalScrollChainingEnabled: XamlPropertyIndex = XamlPropertyIndex(1210i32); pub const ScrollViewer_IsZoomChainingEnabled: XamlPropertyIndex = XamlPropertyIndex(1211i32); pub const ScrollViewer_IsZoomInertiaEnabled: XamlPropertyIndex = XamlPropertyIndex(1212i32); pub const ScrollViewer_LeftHeader: XamlPropertyIndex = XamlPropertyIndex(1213i32); pub const ScrollViewer_MaxZoomFactor: XamlPropertyIndex = XamlPropertyIndex(1214i32); pub const ScrollViewer_MinZoomFactor: XamlPropertyIndex = XamlPropertyIndex(1215i32); pub const ScrollViewer_ScrollableHeight: XamlPropertyIndex = XamlPropertyIndex(1216i32); pub const ScrollViewer_ScrollableWidth: XamlPropertyIndex = XamlPropertyIndex(1217i32); pub const ScrollViewer_TopHeader: XamlPropertyIndex = XamlPropertyIndex(1218i32); pub const ScrollViewer_TopLeftHeader: XamlPropertyIndex = XamlPropertyIndex(1219i32); pub const ScrollViewer_VerticalOffset: XamlPropertyIndex = XamlPropertyIndex(1220i32); pub const ScrollViewer_VerticalScrollBarVisibility: XamlPropertyIndex = XamlPropertyIndex(1221i32); pub const ScrollViewer_VerticalScrollMode: XamlPropertyIndex = XamlPropertyIndex(1222i32); pub const ScrollViewer_VerticalSnapPointsAlignment: XamlPropertyIndex = XamlPropertyIndex(1223i32); pub const ScrollViewer_VerticalSnapPointsType: XamlPropertyIndex = XamlPropertyIndex(1224i32); pub const ScrollViewer_ViewportHeight: XamlPropertyIndex = XamlPropertyIndex(1225i32); pub const ScrollViewer_ViewportWidth: XamlPropertyIndex = XamlPropertyIndex(1226i32); pub const ScrollViewer_ZoomFactor: XamlPropertyIndex = XamlPropertyIndex(1227i32); pub const ScrollViewer_ZoomMode: XamlPropertyIndex = XamlPropertyIndex(1228i32); pub const ScrollViewer_ZoomSnapPoints: XamlPropertyIndex = XamlPropertyIndex(1229i32); pub const ScrollViewer_ZoomSnapPointsType: XamlPropertyIndex = XamlPropertyIndex(1230i32); pub const ToggleButton_IsChecked: XamlPropertyIndex = XamlPropertyIndex(1231i32); pub const ToggleButton_IsThreeState: XamlPropertyIndex = XamlPropertyIndex(1232i32); pub const ToggleMenuFlyoutItem_IsChecked: XamlPropertyIndex = XamlPropertyIndex(1233i32); pub const VirtualizingStackPanel_AreScrollSnapPointsRegular: XamlPropertyIndex = XamlPropertyIndex(1234i32); pub const VirtualizingStackPanel_IsVirtualizing: XamlPropertyIndex = XamlPropertyIndex(1236i32); pub const VirtualizingStackPanel_Orientation: XamlPropertyIndex = XamlPropertyIndex(1237i32); pub const VirtualizingStackPanel_VirtualizationMode: XamlPropertyIndex = XamlPropertyIndex(1238i32); pub const WrapGrid_HorizontalChildrenAlignment: XamlPropertyIndex = XamlPropertyIndex(1239i32); pub const WrapGrid_ItemHeight: XamlPropertyIndex = XamlPropertyIndex(1240i32); pub const WrapGrid_ItemWidth: XamlPropertyIndex = XamlPropertyIndex(1241i32); pub const WrapGrid_MaximumRowsOrColumns: XamlPropertyIndex = XamlPropertyIndex(1242i32); pub const WrapGrid_Orientation: XamlPropertyIndex = XamlPropertyIndex(1243i32); pub const WrapGrid_VerticalChildrenAlignment: XamlPropertyIndex = XamlPropertyIndex(1244i32); pub const AppBarButton_Icon: XamlPropertyIndex = XamlPropertyIndex(1245i32); pub const AppBarButton_IsCompact: XamlPropertyIndex = XamlPropertyIndex(1246i32); pub const AppBarButton_Label: XamlPropertyIndex = XamlPropertyIndex(1247i32); pub const AppBarToggleButton_Icon: XamlPropertyIndex = XamlPropertyIndex(1248i32); pub const AppBarToggleButton_IsCompact: XamlPropertyIndex = XamlPropertyIndex(1249i32); pub const AppBarToggleButton_Label: XamlPropertyIndex = XamlPropertyIndex(1250i32); pub const GridViewItem_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1251i32); pub const ListViewItem_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1252i32); pub const RadioButton_GroupName: XamlPropertyIndex = XamlPropertyIndex(1253i32); pub const Glyphs_ColorFontPaletteIndex: XamlPropertyIndex = XamlPropertyIndex(1267i32); pub const Glyphs_IsColorFontEnabled: XamlPropertyIndex = XamlPropertyIndex(1268i32); pub const CalendarViewTemplateSettings_HasMoreContentAfter: XamlPropertyIndex = XamlPropertyIndex(1274i32); pub const CalendarViewTemplateSettings_HasMoreContentBefore: XamlPropertyIndex = XamlPropertyIndex(1275i32); pub const CalendarViewTemplateSettings_HasMoreViews: XamlPropertyIndex = XamlPropertyIndex(1276i32); pub const CalendarViewTemplateSettings_HeaderText: XamlPropertyIndex = XamlPropertyIndex(1277i32); pub const CalendarViewTemplateSettings_WeekDay1: XamlPropertyIndex = XamlPropertyIndex(1280i32); pub const CalendarViewTemplateSettings_WeekDay2: XamlPropertyIndex = XamlPropertyIndex(1281i32); pub const CalendarViewTemplateSettings_WeekDay3: XamlPropertyIndex = XamlPropertyIndex(1282i32); pub const CalendarViewTemplateSettings_WeekDay4: XamlPropertyIndex = XamlPropertyIndex(1283i32); pub const CalendarViewTemplateSettings_WeekDay5: XamlPropertyIndex = XamlPropertyIndex(1284i32); pub const CalendarViewTemplateSettings_WeekDay6: XamlPropertyIndex = XamlPropertyIndex(1285i32); pub const CalendarViewTemplateSettings_WeekDay7: XamlPropertyIndex = XamlPropertyIndex(1286i32); pub const CalendarView_CalendarIdentifier: XamlPropertyIndex = XamlPropertyIndex(1291i32); pub const CalendarView_DayOfWeekFormat: XamlPropertyIndex = XamlPropertyIndex(1299i32); pub const CalendarView_DisplayMode: XamlPropertyIndex = XamlPropertyIndex(1302i32); pub const CalendarView_FirstDayOfWeek: XamlPropertyIndex = XamlPropertyIndex(1303i32); pub const CalendarView_IsOutOfScopeEnabled: XamlPropertyIndex = XamlPropertyIndex(1317i32); pub const CalendarView_IsTodayHighlighted: XamlPropertyIndex = XamlPropertyIndex(1318i32); pub const CalendarView_MaxDate: XamlPropertyIndex = XamlPropertyIndex(1320i32); pub const CalendarView_MinDate: XamlPropertyIndex = XamlPropertyIndex(1321i32); pub const CalendarView_NumberOfWeeksInView: XamlPropertyIndex = XamlPropertyIndex(1327i32); pub const CalendarView_SelectedDates: XamlPropertyIndex = XamlPropertyIndex(1333i32); pub const CalendarView_SelectionMode: XamlPropertyIndex = XamlPropertyIndex(1335i32); pub const CalendarView_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1336i32); pub const CalendarViewDayItem_Date: XamlPropertyIndex = XamlPropertyIndex(1339i32); pub const CalendarViewDayItem_IsBlackout: XamlPropertyIndex = XamlPropertyIndex(1340i32); pub const MediaTransportControls_IsFastForwardEnabled: XamlPropertyIndex = XamlPropertyIndex(1382i32); pub const MediaTransportControls_IsFastRewindEnabled: XamlPropertyIndex = XamlPropertyIndex(1383i32); pub const MediaTransportControls_IsFullWindowEnabled: XamlPropertyIndex = XamlPropertyIndex(1384i32); pub const MediaTransportControls_IsPlaybackRateEnabled: XamlPropertyIndex = XamlPropertyIndex(1385i32); pub const MediaTransportControls_IsSeekEnabled: XamlPropertyIndex = XamlPropertyIndex(1386i32); pub const MediaTransportControls_IsStopEnabled: XamlPropertyIndex = XamlPropertyIndex(1387i32); pub const MediaTransportControls_IsVolumeEnabled: XamlPropertyIndex = XamlPropertyIndex(1388i32); pub const MediaTransportControls_IsZoomEnabled: XamlPropertyIndex = XamlPropertyIndex(1389i32); pub const ContentPresenter_LineHeight: XamlPropertyIndex = XamlPropertyIndex(1425i32); pub const CalendarViewTemplateSettings_MinViewWidth: XamlPropertyIndex = XamlPropertyIndex(1435i32); pub const ListViewBase_SelectedRanges: XamlPropertyIndex = XamlPropertyIndex(1459i32); pub const SplitViewTemplateSettings_CompactPaneGridLength: XamlPropertyIndex = XamlPropertyIndex(1462i32); pub const SplitViewTemplateSettings_NegativeOpenPaneLength: XamlPropertyIndex = XamlPropertyIndex(1463i32); pub const SplitViewTemplateSettings_NegativeOpenPaneLengthMinusCompactLength: XamlPropertyIndex = XamlPropertyIndex(1464i32); pub const SplitViewTemplateSettings_OpenPaneGridLength: XamlPropertyIndex = XamlPropertyIndex(1465i32); pub const SplitViewTemplateSettings_OpenPaneLengthMinusCompactLength: XamlPropertyIndex = XamlPropertyIndex(1466i32); pub const SplitView_CompactPaneLength: XamlPropertyIndex = XamlPropertyIndex(1467i32); pub const SplitView_Content: XamlPropertyIndex = XamlPropertyIndex(1468i32); pub const SplitView_DisplayMode: XamlPropertyIndex = XamlPropertyIndex(1469i32); pub const SplitView_IsPaneOpen: XamlPropertyIndex = XamlPropertyIndex(1470i32); pub const SplitView_OpenPaneLength: XamlPropertyIndex = XamlPropertyIndex(1471i32); pub const SplitView_Pane: XamlPropertyIndex = XamlPropertyIndex(1472i32); pub const SplitView_PanePlacement: XamlPropertyIndex = XamlPropertyIndex(1473i32); pub const SplitView_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1474i32); pub const UIElement_Transform3D: XamlPropertyIndex = XamlPropertyIndex(1475i32); pub const CompositeTransform3D_CenterX: XamlPropertyIndex = XamlPropertyIndex(1476i32); pub const CompositeTransform3D_CenterY: XamlPropertyIndex = XamlPropertyIndex(1478i32); pub const CompositeTransform3D_CenterZ: XamlPropertyIndex = XamlPropertyIndex(1480i32); pub const CompositeTransform3D_RotationX: XamlPropertyIndex = XamlPropertyIndex(1482i32); pub const CompositeTransform3D_RotationY: XamlPropertyIndex = XamlPropertyIndex(1484i32); pub const CompositeTransform3D_RotationZ: XamlPropertyIndex = XamlPropertyIndex(1486i32); pub const CompositeTransform3D_ScaleX: XamlPropertyIndex = XamlPropertyIndex(1488i32); pub const CompositeTransform3D_ScaleY: XamlPropertyIndex = XamlPropertyIndex(1490i32); pub const CompositeTransform3D_ScaleZ: XamlPropertyIndex = XamlPropertyIndex(1492i32); pub const CompositeTransform3D_TranslateX: XamlPropertyIndex = XamlPropertyIndex(1494i32); pub const CompositeTransform3D_TranslateY: XamlPropertyIndex = XamlPropertyIndex(1496i32); pub const CompositeTransform3D_TranslateZ: XamlPropertyIndex = XamlPropertyIndex(1498i32); pub const PerspectiveTransform3D_Depth: XamlPropertyIndex = XamlPropertyIndex(1500i32); pub const PerspectiveTransform3D_OffsetX: XamlPropertyIndex = XamlPropertyIndex(1501i32); pub const PerspectiveTransform3D_OffsetY: XamlPropertyIndex = XamlPropertyIndex(1502i32); pub const RelativePanel_Above: XamlPropertyIndex = XamlPropertyIndex(1508i32); pub const RelativePanel_AlignBottomWith: XamlPropertyIndex = XamlPropertyIndex(1509i32); pub const RelativePanel_AlignLeftWith: XamlPropertyIndex = XamlPropertyIndex(1510i32); pub const RelativePanel_AlignRightWith: XamlPropertyIndex = XamlPropertyIndex(1515i32); pub const RelativePanel_AlignTopWith: XamlPropertyIndex = XamlPropertyIndex(1516i32); pub const RelativePanel_Below: XamlPropertyIndex = XamlPropertyIndex(1517i32); pub const RelativePanel_LeftOf: XamlPropertyIndex = XamlPropertyIndex(1520i32); pub const RelativePanel_RightOf: XamlPropertyIndex = XamlPropertyIndex(1521i32); pub const SplitViewTemplateSettings_OpenPaneLength: XamlPropertyIndex = XamlPropertyIndex(1524i32); pub const PasswordBox_PasswordRevealMode: XamlPropertyIndex = XamlPropertyIndex(1527i32); pub const SplitView_PaneBackground: XamlPropertyIndex = XamlPropertyIndex(1528i32); pub const ItemsStackPanel_AreStickyGroupHeadersEnabled: XamlPropertyIndex = XamlPropertyIndex(1529i32); pub const ItemsWrapGrid_AreStickyGroupHeadersEnabled: XamlPropertyIndex = XamlPropertyIndex(1530i32); pub const MenuFlyoutSubItem_Items: XamlPropertyIndex = XamlPropertyIndex(1531i32); pub const MenuFlyoutSubItem_Text: XamlPropertyIndex = XamlPropertyIndex(1532i32); pub const UIElement_CanDrag: XamlPropertyIndex = XamlPropertyIndex(1534i32); pub const DataTemplate_ExtensionInstance: XamlPropertyIndex = XamlPropertyIndex(1535i32); pub const RelativePanel_AlignHorizontalCenterWith: XamlPropertyIndex = XamlPropertyIndex(1552i32); pub const RelativePanel_AlignVerticalCenterWith: XamlPropertyIndex = XamlPropertyIndex(1553i32); pub const TargetPropertyPath_Path: XamlPropertyIndex = XamlPropertyIndex(1555i32); pub const TargetPropertyPath_Target: XamlPropertyIndex = XamlPropertyIndex(1556i32); pub const VisualState_Setters: XamlPropertyIndex = XamlPropertyIndex(1558i32); pub const VisualState_StateTriggers: XamlPropertyIndex = XamlPropertyIndex(1559i32); pub const AdaptiveTrigger_MinWindowHeight: XamlPropertyIndex = XamlPropertyIndex(1560i32); pub const AdaptiveTrigger_MinWindowWidth: XamlPropertyIndex = XamlPropertyIndex(1561i32); pub const Setter_Target: XamlPropertyIndex = XamlPropertyIndex(1562i32); pub const CalendarView_BlackoutForeground: XamlPropertyIndex = XamlPropertyIndex(1565i32); pub const CalendarView_CalendarItemBackground: XamlPropertyIndex = XamlPropertyIndex(1566i32); pub const CalendarView_CalendarItemBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1567i32); pub const CalendarView_CalendarItemBorderThickness: XamlPropertyIndex = XamlPropertyIndex(1568i32); pub const CalendarView_CalendarItemForeground: XamlPropertyIndex = XamlPropertyIndex(1569i32); pub const CalendarView_CalendarViewDayItemStyle: XamlPropertyIndex = XamlPropertyIndex(1570i32); pub const CalendarView_DayItemFontFamily: XamlPropertyIndex = XamlPropertyIndex(1571i32); pub const CalendarView_DayItemFontSize: XamlPropertyIndex = XamlPropertyIndex(1572i32); pub const CalendarView_DayItemFontStyle: XamlPropertyIndex = XamlPropertyIndex(1573i32); pub const CalendarView_DayItemFontWeight: XamlPropertyIndex = XamlPropertyIndex(1574i32); pub const CalendarView_FirstOfMonthLabelFontFamily: XamlPropertyIndex = XamlPropertyIndex(1575i32); pub const CalendarView_FirstOfMonthLabelFontSize: XamlPropertyIndex = XamlPropertyIndex(1576i32); pub const CalendarView_FirstOfMonthLabelFontStyle: XamlPropertyIndex = XamlPropertyIndex(1577i32); pub const CalendarView_FirstOfMonthLabelFontWeight: XamlPropertyIndex = XamlPropertyIndex(1578i32); pub const CalendarView_FirstOfYearDecadeLabelFontFamily: XamlPropertyIndex = XamlPropertyIndex(1579i32); pub const CalendarView_FirstOfYearDecadeLabelFontSize: XamlPropertyIndex = XamlPropertyIndex(1580i32); pub const CalendarView_FirstOfYearDecadeLabelFontStyle: XamlPropertyIndex = XamlPropertyIndex(1581i32); pub const CalendarView_FirstOfYearDecadeLabelFontWeight: XamlPropertyIndex = XamlPropertyIndex(1582i32); pub const CalendarView_FocusBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1583i32); pub const CalendarView_HorizontalDayItemAlignment: XamlPropertyIndex = XamlPropertyIndex(1584i32); pub const CalendarView_HorizontalFirstOfMonthLabelAlignment: XamlPropertyIndex = XamlPropertyIndex(1585i32); pub const CalendarView_HoverBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1586i32); pub const CalendarView_MonthYearItemFontFamily: XamlPropertyIndex = XamlPropertyIndex(1588i32); pub const CalendarView_MonthYearItemFontSize: XamlPropertyIndex = XamlPropertyIndex(1589i32); pub const CalendarView_MonthYearItemFontStyle: XamlPropertyIndex = XamlPropertyIndex(1590i32); pub const CalendarView_MonthYearItemFontWeight: XamlPropertyIndex = XamlPropertyIndex(1591i32); pub const CalendarView_OutOfScopeBackground: XamlPropertyIndex = XamlPropertyIndex(1592i32); pub const CalendarView_OutOfScopeForeground: XamlPropertyIndex = XamlPropertyIndex(1593i32); pub const CalendarView_PressedBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1594i32); pub const CalendarView_PressedForeground: XamlPropertyIndex = XamlPropertyIndex(1595i32); pub const CalendarView_SelectedBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1596i32); pub const CalendarView_SelectedForeground: XamlPropertyIndex = XamlPropertyIndex(1597i32); pub const CalendarView_SelectedHoverBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1598i32); pub const CalendarView_SelectedPressedBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1599i32); pub const CalendarView_TodayFontWeight: XamlPropertyIndex = XamlPropertyIndex(1600i32); pub const CalendarView_TodayForeground: XamlPropertyIndex = XamlPropertyIndex(1601i32); pub const CalendarView_VerticalDayItemAlignment: XamlPropertyIndex = XamlPropertyIndex(1602i32); pub const CalendarView_VerticalFirstOfMonthLabelAlignment: XamlPropertyIndex = XamlPropertyIndex(1603i32); pub const MediaTransportControls_IsCompact: XamlPropertyIndex = XamlPropertyIndex(1605i32); pub const RelativePanel_AlignBottomWithPanel: XamlPropertyIndex = XamlPropertyIndex(1606i32); pub const RelativePanel_AlignHorizontalCenterWithPanel: XamlPropertyIndex = XamlPropertyIndex(1607i32); pub const RelativePanel_AlignLeftWithPanel: XamlPropertyIndex = XamlPropertyIndex(1608i32); pub const RelativePanel_AlignRightWithPanel: XamlPropertyIndex = XamlPropertyIndex(1609i32); pub const RelativePanel_AlignTopWithPanel: XamlPropertyIndex = XamlPropertyIndex(1610i32); pub const RelativePanel_AlignVerticalCenterWithPanel: XamlPropertyIndex = XamlPropertyIndex(1611i32); pub const ListViewBase_IsMultiSelectCheckBoxEnabled: XamlPropertyIndex = XamlPropertyIndex(1612i32); pub const AutomationProperties_Level: XamlPropertyIndex = XamlPropertyIndex(1614i32); pub const AutomationProperties_PositionInSet: XamlPropertyIndex = XamlPropertyIndex(1615i32); pub const AutomationProperties_SizeOfSet: XamlPropertyIndex = XamlPropertyIndex(1616i32); pub const ListViewItemPresenter_CheckBoxBrush: XamlPropertyIndex = XamlPropertyIndex(1617i32); pub const ListViewItemPresenter_CheckMode: XamlPropertyIndex = XamlPropertyIndex(1618i32); pub const ListViewItemPresenter_PressedBackground: XamlPropertyIndex = XamlPropertyIndex(1620i32); pub const ListViewItemPresenter_SelectedPressedBackground: XamlPropertyIndex = XamlPropertyIndex(1621i32); pub const Control_IsTemplateFocusTarget: XamlPropertyIndex = XamlPropertyIndex(1623i32); pub const Control_UseSystemFocusVisuals: XamlPropertyIndex = XamlPropertyIndex(1624i32); pub const ListViewItemPresenter_FocusSecondaryBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1628i32); pub const ListViewItemPresenter_PointerOverForeground: XamlPropertyIndex = XamlPropertyIndex(1630i32); pub const FontIcon_MirroredWhenRightToLeft: XamlPropertyIndex = XamlPropertyIndex(1631i32); pub const CalendarViewTemplateSettings_CenterX: XamlPropertyIndex = XamlPropertyIndex(1632i32); pub const CalendarViewTemplateSettings_CenterY: XamlPropertyIndex = XamlPropertyIndex(1633i32); pub const CalendarViewTemplateSettings_ClipRect: XamlPropertyIndex = XamlPropertyIndex(1634i32); pub const PasswordBox_TextReadingOrder: XamlPropertyIndex = XamlPropertyIndex(1650i32); pub const RichEditBox_TextReadingOrder: XamlPropertyIndex = XamlPropertyIndex(1651i32); pub const TextBox_TextReadingOrder: XamlPropertyIndex = XamlPropertyIndex(1652i32); pub const WebView_ExecutionMode: XamlPropertyIndex = XamlPropertyIndex(1653i32); pub const WebView_DeferredPermissionRequests: XamlPropertyIndex = XamlPropertyIndex(1655i32); pub const WebView_Settings: XamlPropertyIndex = XamlPropertyIndex(1656i32); pub const RichEditBox_DesiredCandidateWindowAlignment: XamlPropertyIndex = XamlPropertyIndex(1660i32); pub const TextBox_DesiredCandidateWindowAlignment: XamlPropertyIndex = XamlPropertyIndex(1662i32); pub const CalendarDatePicker_CalendarIdentifier: XamlPropertyIndex = XamlPropertyIndex(1663i32); pub const CalendarDatePicker_CalendarViewStyle: XamlPropertyIndex = XamlPropertyIndex(1664i32); pub const CalendarDatePicker_Date: XamlPropertyIndex = XamlPropertyIndex(1665i32); pub const CalendarDatePicker_DateFormat: XamlPropertyIndex = XamlPropertyIndex(1666i32); pub const CalendarDatePicker_DayOfWeekFormat: XamlPropertyIndex = XamlPropertyIndex(1667i32); pub const CalendarDatePicker_DisplayMode: XamlPropertyIndex = XamlPropertyIndex(1668i32); pub const CalendarDatePicker_FirstDayOfWeek: XamlPropertyIndex = XamlPropertyIndex(1669i32); pub const CalendarDatePicker_Header: XamlPropertyIndex = XamlPropertyIndex(1670i32); pub const CalendarDatePicker_HeaderTemplate: XamlPropertyIndex = XamlPropertyIndex(1671i32); pub const CalendarDatePicker_IsCalendarOpen: XamlPropertyIndex = XamlPropertyIndex(1672i32); pub const CalendarDatePicker_IsGroupLabelVisible: XamlPropertyIndex = XamlPropertyIndex(1673i32); pub const CalendarDatePicker_IsOutOfScopeEnabled: XamlPropertyIndex = XamlPropertyIndex(1674i32); pub const CalendarDatePicker_IsTodayHighlighted: XamlPropertyIndex = XamlPropertyIndex(1675i32); pub const CalendarDatePicker_MaxDate: XamlPropertyIndex = XamlPropertyIndex(1676i32); pub const CalendarDatePicker_MinDate: XamlPropertyIndex = XamlPropertyIndex(1677i32); pub const CalendarDatePicker_PlaceholderText: XamlPropertyIndex = XamlPropertyIndex(1678i32); pub const CalendarView_IsGroupLabelVisible: XamlPropertyIndex = XamlPropertyIndex(1679i32); pub const ContentPresenter_Background: XamlPropertyIndex = XamlPropertyIndex(1680i32); pub const ContentPresenter_BorderBrush: XamlPropertyIndex = XamlPropertyIndex(1681i32); pub const ContentPresenter_BorderThickness: XamlPropertyIndex = XamlPropertyIndex(1682i32); pub const ContentPresenter_CornerRadius: XamlPropertyIndex = XamlPropertyIndex(1683i32); pub const ContentPresenter_Padding: XamlPropertyIndex = XamlPropertyIndex(1684i32); pub const Grid_BorderBrush: XamlPropertyIndex = XamlPropertyIndex(1685i32); pub const Grid_BorderThickness: XamlPropertyIndex = XamlPropertyIndex(1686i32); pub const Grid_CornerRadius: XamlPropertyIndex = XamlPropertyIndex(1687i32); pub const Grid_Padding: XamlPropertyIndex = XamlPropertyIndex(1688i32); pub const RelativePanel_BorderBrush: XamlPropertyIndex = XamlPropertyIndex(1689i32); pub const RelativePanel_BorderThickness: XamlPropertyIndex = XamlPropertyIndex(1690i32); pub const RelativePanel_CornerRadius: XamlPropertyIndex = XamlPropertyIndex(1691i32); pub const RelativePanel_Padding: XamlPropertyIndex = XamlPropertyIndex(1692i32); pub const StackPanel_BorderBrush: XamlPropertyIndex = XamlPropertyIndex(1693i32); pub const StackPanel_BorderThickness: XamlPropertyIndex = XamlPropertyIndex(1694i32); pub const StackPanel_CornerRadius: XamlPropertyIndex = XamlPropertyIndex(1695i32); pub const StackPanel_Padding: XamlPropertyIndex = XamlPropertyIndex(1696i32); pub const PasswordBox_InputScope: XamlPropertyIndex = XamlPropertyIndex(1697i32); pub const MediaTransportControlsHelper_DropoutOrder: XamlPropertyIndex = XamlPropertyIndex(1698i32); pub const AutoSuggestBoxQuerySubmittedEventArgs_ChosenSuggestion: XamlPropertyIndex = XamlPropertyIndex(1699i32); pub const AutoSuggestBoxQuerySubmittedEventArgs_QueryText: XamlPropertyIndex = XamlPropertyIndex(1700i32); pub const AutoSuggestBox_QueryIcon: XamlPropertyIndex = XamlPropertyIndex(1701i32); pub const StateTrigger_IsActive: XamlPropertyIndex = XamlPropertyIndex(1702i32); pub const ContentPresenter_HorizontalContentAlignment: XamlPropertyIndex = XamlPropertyIndex(1703i32); pub const ContentPresenter_VerticalContentAlignment: XamlPropertyIndex = XamlPropertyIndex(1704i32); pub const AppBarTemplateSettings_ClipRect: XamlPropertyIndex = XamlPropertyIndex(1705i32); pub const AppBarTemplateSettings_CompactRootMargin: XamlPropertyIndex = XamlPropertyIndex(1706i32); pub const AppBarTemplateSettings_CompactVerticalDelta: XamlPropertyIndex = XamlPropertyIndex(1707i32); pub const AppBarTemplateSettings_HiddenRootMargin: XamlPropertyIndex = XamlPropertyIndex(1708i32); pub const AppBarTemplateSettings_HiddenVerticalDelta: XamlPropertyIndex = XamlPropertyIndex(1709i32); pub const AppBarTemplateSettings_MinimalRootMargin: XamlPropertyIndex = XamlPropertyIndex(1710i32); pub const AppBarTemplateSettings_MinimalVerticalDelta: XamlPropertyIndex = XamlPropertyIndex(1711i32); pub const CommandBarTemplateSettings_ContentHeight: XamlPropertyIndex = XamlPropertyIndex(1712i32); pub const CommandBarTemplateSettings_NegativeOverflowContentHeight: XamlPropertyIndex = XamlPropertyIndex(1713i32); pub const CommandBarTemplateSettings_OverflowContentClipRect: XamlPropertyIndex = XamlPropertyIndex(1714i32); pub const CommandBarTemplateSettings_OverflowContentHeight: XamlPropertyIndex = XamlPropertyIndex(1715i32); pub const CommandBarTemplateSettings_OverflowContentHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(1716i32); pub const CommandBarTemplateSettings_OverflowContentMaxHeight: XamlPropertyIndex = XamlPropertyIndex(1717i32); pub const CommandBarTemplateSettings_OverflowContentMinWidth: XamlPropertyIndex = XamlPropertyIndex(1718i32); pub const AppBar_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1719i32); pub const CommandBar_CommandBarOverflowPresenterStyle: XamlPropertyIndex = XamlPropertyIndex(1720i32); pub const CommandBar_CommandBarTemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1721i32); pub const DrillInThemeAnimation_EntranceTarget: XamlPropertyIndex = XamlPropertyIndex(1722i32); pub const DrillInThemeAnimation_EntranceTargetName: XamlPropertyIndex = XamlPropertyIndex(1723i32); pub const DrillInThemeAnimation_ExitTarget: XamlPropertyIndex = XamlPropertyIndex(1724i32); pub const DrillInThemeAnimation_ExitTargetName: XamlPropertyIndex = XamlPropertyIndex(1725i32); pub const DrillOutThemeAnimation_EntranceTarget: XamlPropertyIndex = XamlPropertyIndex(1726i32); pub const DrillOutThemeAnimation_EntranceTargetName: XamlPropertyIndex = XamlPropertyIndex(1727i32); pub const DrillOutThemeAnimation_ExitTarget: XamlPropertyIndex = XamlPropertyIndex(1728i32); pub const DrillOutThemeAnimation_ExitTargetName: XamlPropertyIndex = XamlPropertyIndex(1729i32); pub const XamlBindingHelper_DataTemplateComponent: XamlPropertyIndex = XamlPropertyIndex(1730i32); pub const AutomationProperties_Annotations: XamlPropertyIndex = XamlPropertyIndex(1732i32); pub const AutomationAnnotation_Element: XamlPropertyIndex = XamlPropertyIndex(1733i32); pub const AutomationAnnotation_Type: XamlPropertyIndex = XamlPropertyIndex(1734i32); pub const AutomationPeerAnnotation_Peer: XamlPropertyIndex = XamlPropertyIndex(1735i32); pub const AutomationPeerAnnotation_Type: XamlPropertyIndex = XamlPropertyIndex(1736i32); pub const Hyperlink_UnderlineStyle: XamlPropertyIndex = XamlPropertyIndex(1741i32); pub const CalendarView_DisabledForeground: XamlPropertyIndex = XamlPropertyIndex(1742i32); pub const CalendarView_TodayBackground: XamlPropertyIndex = XamlPropertyIndex(1743i32); pub const CalendarView_TodayBlackoutBackground: XamlPropertyIndex = XamlPropertyIndex(1744i32); pub const CalendarView_TodaySelectedInnerBorderBrush: XamlPropertyIndex = XamlPropertyIndex(1747i32); pub const Control_IsFocusEngaged: XamlPropertyIndex = XamlPropertyIndex(1749i32); pub const Control_IsFocusEngagementEnabled: XamlPropertyIndex = XamlPropertyIndex(1752i32); pub const RichEditBox_ClipboardCopyFormat: XamlPropertyIndex = XamlPropertyIndex(1754i32); pub const CommandBarTemplateSettings_OverflowContentMaxWidth: XamlPropertyIndex = XamlPropertyIndex(1757i32); pub const ComboBoxTemplateSettings_DropDownContentMinWidth: XamlPropertyIndex = XamlPropertyIndex(1758i32); pub const MenuFlyoutPresenterTemplateSettings_FlyoutContentMinWidth: XamlPropertyIndex = XamlPropertyIndex(1762i32); pub const MenuFlyoutPresenter_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(1763i32); pub const AutomationProperties_LandmarkType: XamlPropertyIndex = XamlPropertyIndex(1766i32); pub const AutomationProperties_LocalizedLandmarkType: XamlPropertyIndex = XamlPropertyIndex(1767i32); pub const RepositionThemeTransition_IsStaggeringEnabled: XamlPropertyIndex = XamlPropertyIndex(1769i32); pub const ListBox_SingleSelectionFollowsFocus: XamlPropertyIndex = XamlPropertyIndex(1770i32); pub const ListViewBase_SingleSelectionFollowsFocus: XamlPropertyIndex = XamlPropertyIndex(1771i32); pub const BitmapImage_AutoPlay: XamlPropertyIndex = XamlPropertyIndex(1773i32); pub const BitmapImage_IsAnimatedBitmap: XamlPropertyIndex = XamlPropertyIndex(1774i32); pub const BitmapImage_IsPlaying: XamlPropertyIndex = XamlPropertyIndex(1775i32); pub const AutomationProperties_FullDescription: XamlPropertyIndex = XamlPropertyIndex(1776i32); pub const AutomationProperties_IsDataValidForForm: XamlPropertyIndex = XamlPropertyIndex(1777i32); pub const AutomationProperties_IsPeripheral: XamlPropertyIndex = XamlPropertyIndex(1778i32); pub const AutomationProperties_LocalizedControlType: XamlPropertyIndex = XamlPropertyIndex(1779i32); pub const FlyoutBase_AllowFocusOnInteraction: XamlPropertyIndex = XamlPropertyIndex(1780i32); pub const TextElement_AllowFocusOnInteraction: XamlPropertyIndex = XamlPropertyIndex(1781i32); pub const FrameworkElement_AllowFocusOnInteraction: XamlPropertyIndex = XamlPropertyIndex(1782i32); pub const Control_RequiresPointer: XamlPropertyIndex = XamlPropertyIndex(1783i32); pub const UIElement_ContextFlyout: XamlPropertyIndex = XamlPropertyIndex(1785i32); pub const TextElement_AccessKey: XamlPropertyIndex = XamlPropertyIndex(1786i32); pub const UIElement_AccessKeyScopeOwner: XamlPropertyIndex = XamlPropertyIndex(1787i32); pub const UIElement_IsAccessKeyScope: XamlPropertyIndex = XamlPropertyIndex(1788i32); pub const AutomationProperties_DescribedBy: XamlPropertyIndex = XamlPropertyIndex(1790i32); pub const UIElement_AccessKey: XamlPropertyIndex = XamlPropertyIndex(1803i32); pub const Control_XYFocusDown: XamlPropertyIndex = XamlPropertyIndex(1804i32); pub const Control_XYFocusLeft: XamlPropertyIndex = XamlPropertyIndex(1805i32); pub const Control_XYFocusRight: XamlPropertyIndex = XamlPropertyIndex(1806i32); pub const Control_XYFocusUp: XamlPropertyIndex = XamlPropertyIndex(1807i32); pub const Hyperlink_XYFocusDown: XamlPropertyIndex = XamlPropertyIndex(1808i32); pub const Hyperlink_XYFocusLeft: XamlPropertyIndex = XamlPropertyIndex(1809i32); pub const Hyperlink_XYFocusRight: XamlPropertyIndex = XamlPropertyIndex(1810i32); pub const Hyperlink_XYFocusUp: XamlPropertyIndex = XamlPropertyIndex(1811i32); pub const WebView_XYFocusDown: XamlPropertyIndex = XamlPropertyIndex(1812i32); pub const WebView_XYFocusLeft: XamlPropertyIndex = XamlPropertyIndex(1813i32); pub const WebView_XYFocusRight: XamlPropertyIndex = XamlPropertyIndex(1814i32); pub const WebView_XYFocusUp: XamlPropertyIndex = XamlPropertyIndex(1815i32); pub const CommandBarTemplateSettings_EffectiveOverflowButtonVisibility: XamlPropertyIndex = XamlPropertyIndex(1816i32); pub const AppBarSeparator_IsInOverflow: XamlPropertyIndex = XamlPropertyIndex(1817i32); pub const CommandBar_DefaultLabelPosition: XamlPropertyIndex = XamlPropertyIndex(1818i32); pub const CommandBar_IsDynamicOverflowEnabled: XamlPropertyIndex = XamlPropertyIndex(1819i32); pub const CommandBar_OverflowButtonVisibility: XamlPropertyIndex = XamlPropertyIndex(1820i32); pub const AppBarButton_IsInOverflow: XamlPropertyIndex = XamlPropertyIndex(1821i32); pub const AppBarButton_LabelPosition: XamlPropertyIndex = XamlPropertyIndex(1822i32); pub const AppBarToggleButton_IsInOverflow: XamlPropertyIndex = XamlPropertyIndex(1823i32); pub const AppBarToggleButton_LabelPosition: XamlPropertyIndex = XamlPropertyIndex(1824i32); pub const FlyoutBase_LightDismissOverlayMode: XamlPropertyIndex = XamlPropertyIndex(1825i32); pub const Popup_LightDismissOverlayMode: XamlPropertyIndex = XamlPropertyIndex(1827i32); pub const CalendarDatePicker_LightDismissOverlayMode: XamlPropertyIndex = XamlPropertyIndex(1829i32); pub const DatePicker_LightDismissOverlayMode: XamlPropertyIndex = XamlPropertyIndex(1830i32); pub const SplitView_LightDismissOverlayMode: XamlPropertyIndex = XamlPropertyIndex(1831i32); pub const TimePicker_LightDismissOverlayMode: XamlPropertyIndex = XamlPropertyIndex(1832i32); pub const AppBar_LightDismissOverlayMode: XamlPropertyIndex = XamlPropertyIndex(1833i32); pub const AutoSuggestBox_LightDismissOverlayMode: XamlPropertyIndex = XamlPropertyIndex(1834i32); pub const ComboBox_LightDismissOverlayMode: XamlPropertyIndex = XamlPropertyIndex(1835i32); pub const AppBarSeparator_DynamicOverflowOrder: XamlPropertyIndex = XamlPropertyIndex(1836i32); pub const AppBarButton_DynamicOverflowOrder: XamlPropertyIndex = XamlPropertyIndex(1837i32); pub const AppBarToggleButton_DynamicOverflowOrder: XamlPropertyIndex = XamlPropertyIndex(1838i32); pub const FrameworkElement_FocusVisualMargin: XamlPropertyIndex = XamlPropertyIndex(1839i32); pub const FrameworkElement_FocusVisualPrimaryBrush: XamlPropertyIndex = XamlPropertyIndex(1840i32); pub const FrameworkElement_FocusVisualPrimaryThickness: XamlPropertyIndex = XamlPropertyIndex(1841i32); pub const FrameworkElement_FocusVisualSecondaryBrush: XamlPropertyIndex = XamlPropertyIndex(1842i32); pub const FrameworkElement_FocusVisualSecondaryThickness: XamlPropertyIndex = XamlPropertyIndex(1843i32); pub const FlyoutBase_AllowFocusWhenDisabled: XamlPropertyIndex = XamlPropertyIndex(1846i32); pub const FrameworkElement_AllowFocusWhenDisabled: XamlPropertyIndex = XamlPropertyIndex(1847i32); pub const ComboBox_IsTextSearchEnabled: XamlPropertyIndex = XamlPropertyIndex(1848i32); pub const TextElement_ExitDisplayModeOnAccessKeyInvoked: XamlPropertyIndex = XamlPropertyIndex(1849i32); pub const UIElement_ExitDisplayModeOnAccessKeyInvoked: XamlPropertyIndex = XamlPropertyIndex(1850i32); pub const MediaPlayerPresenter_IsFullWindow: XamlPropertyIndex = XamlPropertyIndex(1851i32); pub const MediaPlayerPresenter_MediaPlayer: XamlPropertyIndex = XamlPropertyIndex(1852i32); pub const MediaPlayerPresenter_Stretch: XamlPropertyIndex = XamlPropertyIndex(1853i32); pub const MediaPlayerElement_AreTransportControlsEnabled: XamlPropertyIndex = XamlPropertyIndex(1854i32); pub const MediaPlayerElement_AutoPlay: XamlPropertyIndex = XamlPropertyIndex(1855i32); pub const MediaPlayerElement_IsFullWindow: XamlPropertyIndex = XamlPropertyIndex(1856i32); pub const MediaPlayerElement_MediaPlayer: XamlPropertyIndex = XamlPropertyIndex(1857i32); pub const MediaPlayerElement_PosterSource: XamlPropertyIndex = XamlPropertyIndex(1858i32); pub const MediaPlayerElement_Source: XamlPropertyIndex = XamlPropertyIndex(1859i32); pub const MediaPlayerElement_Stretch: XamlPropertyIndex = XamlPropertyIndex(1860i32); pub const MediaPlayerElement_TransportControls: XamlPropertyIndex = XamlPropertyIndex(1861i32); pub const MediaTransportControls_FastPlayFallbackBehaviour: XamlPropertyIndex = XamlPropertyIndex(1862i32); pub const MediaTransportControls_IsNextTrackButtonVisible: XamlPropertyIndex = XamlPropertyIndex(1863i32); pub const MediaTransportControls_IsPreviousTrackButtonVisible: XamlPropertyIndex = XamlPropertyIndex(1864i32); pub const MediaTransportControls_IsSkipBackwardButtonVisible: XamlPropertyIndex = XamlPropertyIndex(1865i32); pub const MediaTransportControls_IsSkipBackwardEnabled: XamlPropertyIndex = XamlPropertyIndex(1866i32); pub const MediaTransportControls_IsSkipForwardButtonVisible: XamlPropertyIndex = XamlPropertyIndex(1867i32); pub const MediaTransportControls_IsSkipForwardEnabled: XamlPropertyIndex = XamlPropertyIndex(1868i32); pub const FlyoutBase_ElementSoundMode: XamlPropertyIndex = XamlPropertyIndex(1869i32); pub const Control_ElementSoundMode: XamlPropertyIndex = XamlPropertyIndex(1870i32); pub const Hyperlink_ElementSoundMode: XamlPropertyIndex = XamlPropertyIndex(1871i32); pub const AutomationProperties_FlowsFrom: XamlPropertyIndex = XamlPropertyIndex(1876i32); pub const AutomationProperties_FlowsTo: XamlPropertyIndex = XamlPropertyIndex(1877i32); pub const TextElement_TextDecorations: XamlPropertyIndex = XamlPropertyIndex(1879i32); pub const RichTextBlock_TextDecorations: XamlPropertyIndex = XamlPropertyIndex(1881i32); pub const Control_DefaultStyleResourceUri: XamlPropertyIndex = XamlPropertyIndex(1882i32); pub const ContentDialog_PrimaryButtonStyle: XamlPropertyIndex = XamlPropertyIndex(1884i32); pub const ContentDialog_SecondaryButtonStyle: XamlPropertyIndex = XamlPropertyIndex(1885i32); pub const TextElement_KeyTipHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(1890i32); pub const TextElement_KeyTipPlacementMode: XamlPropertyIndex = XamlPropertyIndex(1891i32); pub const TextElement_KeyTipVerticalOffset: XamlPropertyIndex = XamlPropertyIndex(1892i32); pub const UIElement_KeyTipHorizontalOffset: XamlPropertyIndex = XamlPropertyIndex(1893i32); pub const UIElement_KeyTipPlacementMode: XamlPropertyIndex = XamlPropertyIndex(1894i32); pub const UIElement_KeyTipVerticalOffset: XamlPropertyIndex = XamlPropertyIndex(1895i32); pub const FlyoutBase_OverlayInputPassThroughElement: XamlPropertyIndex = XamlPropertyIndex(1896i32); pub const UIElement_XYFocusKeyboardNavigation: XamlPropertyIndex = XamlPropertyIndex(1897i32); pub const AutomationProperties_Culture: XamlPropertyIndex = XamlPropertyIndex(1898i32); pub const UIElement_XYFocusDownNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(1918i32); pub const UIElement_XYFocusLeftNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(1919i32); pub const UIElement_XYFocusRightNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(1920i32); pub const UIElement_XYFocusUpNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(1921i32); pub const Hyperlink_XYFocusDownNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(1922i32); pub const Hyperlink_XYFocusLeftNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(1923i32); pub const Hyperlink_XYFocusRightNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(1924i32); pub const Hyperlink_XYFocusUpNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(1925i32); pub const TextElement_AccessKeyScopeOwner: XamlPropertyIndex = XamlPropertyIndex(1926i32); pub const TextElement_IsAccessKeyScope: XamlPropertyIndex = XamlPropertyIndex(1927i32); pub const Hyperlink_FocusState: XamlPropertyIndex = XamlPropertyIndex(1934i32); pub const ContentDialog_CloseButtonCommand: XamlPropertyIndex = XamlPropertyIndex(1936i32); pub const ContentDialog_CloseButtonCommandParameter: XamlPropertyIndex = XamlPropertyIndex(1937i32); pub const ContentDialog_CloseButtonStyle: XamlPropertyIndex = XamlPropertyIndex(1938i32); pub const ContentDialog_CloseButtonText: XamlPropertyIndex = XamlPropertyIndex(1939i32); pub const ContentDialog_DefaultButton: XamlPropertyIndex = XamlPropertyIndex(1940i32); pub const RichEditBox_SelectionHighlightColorWhenNotFocused: XamlPropertyIndex = XamlPropertyIndex(1941i32); pub const TextBox_SelectionHighlightColorWhenNotFocused: XamlPropertyIndex = XamlPropertyIndex(1942i32); pub const SvgImageSource_RasterizePixelHeight: XamlPropertyIndex = XamlPropertyIndex(1948i32); pub const SvgImageSource_RasterizePixelWidth: XamlPropertyIndex = XamlPropertyIndex(1949i32); pub const SvgImageSource_UriSource: XamlPropertyIndex = XamlPropertyIndex(1950i32); pub const LoadedImageSurface_DecodedPhysicalSize: XamlPropertyIndex = XamlPropertyIndex(1955i32); pub const LoadedImageSurface_DecodedSize: XamlPropertyIndex = XamlPropertyIndex(1956i32); pub const LoadedImageSurface_NaturalSize: XamlPropertyIndex = XamlPropertyIndex(1957i32); pub const ComboBox_SelectionChangedTrigger: XamlPropertyIndex = XamlPropertyIndex(1958i32); pub const XamlCompositionBrushBase_FallbackColor: XamlPropertyIndex = XamlPropertyIndex(1960i32); pub const UIElement_Lights: XamlPropertyIndex = XamlPropertyIndex(1962i32); pub const MenuFlyoutItem_Icon: XamlPropertyIndex = XamlPropertyIndex(1963i32); pub const MenuFlyoutSubItem_Icon: XamlPropertyIndex = XamlPropertyIndex(1964i32); pub const BitmapIcon_ShowAsMonochrome: XamlPropertyIndex = XamlPropertyIndex(1965i32); pub const UIElement_HighContrastAdjustment: XamlPropertyIndex = XamlPropertyIndex(1967i32); pub const RichEditBox_MaxLength: XamlPropertyIndex = XamlPropertyIndex(1968i32); pub const UIElement_TabFocusNavigation: XamlPropertyIndex = XamlPropertyIndex(1969i32); pub const Control_IsTemplateKeyTipTarget: XamlPropertyIndex = XamlPropertyIndex(1970i32); pub const Hyperlink_IsTabStop: XamlPropertyIndex = XamlPropertyIndex(1972i32); pub const Hyperlink_TabIndex: XamlPropertyIndex = XamlPropertyIndex(1973i32); pub const MediaTransportControls_IsRepeatButtonVisible: XamlPropertyIndex = XamlPropertyIndex(1974i32); pub const MediaTransportControls_IsRepeatEnabled: XamlPropertyIndex = XamlPropertyIndex(1975i32); pub const MediaTransportControls_ShowAndHideAutomatically: XamlPropertyIndex = XamlPropertyIndex(1976i32); pub const RichEditBox_DisabledFormattingAccelerators: XamlPropertyIndex = XamlPropertyIndex(1977i32); pub const RichEditBox_CharacterCasing: XamlPropertyIndex = XamlPropertyIndex(1978i32); pub const TextBox_CharacterCasing: XamlPropertyIndex = XamlPropertyIndex(1979i32); pub const RichTextBlock_IsTextTrimmed: XamlPropertyIndex = XamlPropertyIndex(1980i32); pub const RichTextBlockOverflow_IsTextTrimmed: XamlPropertyIndex = XamlPropertyIndex(1981i32); pub const TextBlock_IsTextTrimmed: XamlPropertyIndex = XamlPropertyIndex(1982i32); pub const TextHighlighter_Background: XamlPropertyIndex = XamlPropertyIndex(1985i32); pub const TextHighlighter_Foreground: XamlPropertyIndex = XamlPropertyIndex(1986i32); pub const TextHighlighter_Ranges: XamlPropertyIndex = XamlPropertyIndex(1987i32); pub const RichTextBlock_TextHighlighters: XamlPropertyIndex = XamlPropertyIndex(1988i32); pub const TextBlock_TextHighlighters: XamlPropertyIndex = XamlPropertyIndex(1989i32); pub const FrameworkElement_ActualTheme: XamlPropertyIndex = XamlPropertyIndex(1992i32); pub const Grid_ColumnSpacing: XamlPropertyIndex = XamlPropertyIndex(1993i32); pub const Grid_RowSpacing: XamlPropertyIndex = XamlPropertyIndex(1994i32); pub const StackPanel_Spacing: XamlPropertyIndex = XamlPropertyIndex(1995i32); pub const Block_HorizontalTextAlignment: XamlPropertyIndex = XamlPropertyIndex(1996i32); pub const RichTextBlock_HorizontalTextAlignment: XamlPropertyIndex = XamlPropertyIndex(1997i32); pub const TextBlock_HorizontalTextAlignment: XamlPropertyIndex = XamlPropertyIndex(1998i32); pub const RichEditBox_HorizontalTextAlignment: XamlPropertyIndex = XamlPropertyIndex(1999i32); pub const TextBox_HorizontalTextAlignment: XamlPropertyIndex = XamlPropertyIndex(2000i32); pub const TextBox_PlaceholderForeground: XamlPropertyIndex = XamlPropertyIndex(2001i32); pub const ComboBox_PlaceholderForeground: XamlPropertyIndex = XamlPropertyIndex(2002i32); pub const KeyboardAccelerator_IsEnabled: XamlPropertyIndex = XamlPropertyIndex(2003i32); pub const KeyboardAccelerator_Key: XamlPropertyIndex = XamlPropertyIndex(2004i32); pub const KeyboardAccelerator_Modifiers: XamlPropertyIndex = XamlPropertyIndex(2005i32); pub const KeyboardAccelerator_ScopeOwner: XamlPropertyIndex = XamlPropertyIndex(2006i32); pub const UIElement_KeyboardAccelerators: XamlPropertyIndex = XamlPropertyIndex(2007i32); pub const ListViewItemPresenter_RevealBackground: XamlPropertyIndex = XamlPropertyIndex(2009i32); pub const ListViewItemPresenter_RevealBackgroundShowsAboveContent: XamlPropertyIndex = XamlPropertyIndex(2010i32); pub const ListViewItemPresenter_RevealBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2011i32); pub const ListViewItemPresenter_RevealBorderThickness: XamlPropertyIndex = XamlPropertyIndex(2012i32); pub const UIElement_KeyTipTarget: XamlPropertyIndex = XamlPropertyIndex(2014i32); pub const AppBarButtonTemplateSettings_KeyboardAcceleratorTextMinWidth: XamlPropertyIndex = XamlPropertyIndex(2015i32); pub const AppBarToggleButtonTemplateSettings_KeyboardAcceleratorTextMinWidth: XamlPropertyIndex = XamlPropertyIndex(2016i32); pub const MenuFlyoutItemTemplateSettings_KeyboardAcceleratorTextMinWidth: XamlPropertyIndex = XamlPropertyIndex(2017i32); pub const MenuFlyoutItem_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(2019i32); pub const AppBarButton_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(2021i32); pub const AppBarToggleButton_TemplateSettings: XamlPropertyIndex = XamlPropertyIndex(2023i32); pub const UIElement_KeyboardAcceleratorPlacementMode: XamlPropertyIndex = XamlPropertyIndex(2028i32); pub const MediaTransportControls_IsCompactOverlayButtonVisible: XamlPropertyIndex = XamlPropertyIndex(2032i32); pub const MediaTransportControls_IsCompactOverlayEnabled: XamlPropertyIndex = XamlPropertyIndex(2033i32); pub const UIElement_KeyboardAcceleratorPlacementTarget: XamlPropertyIndex = XamlPropertyIndex(2061i32); pub const UIElement_CenterPoint: XamlPropertyIndex = XamlPropertyIndex(2062i32); pub const UIElement_Rotation: XamlPropertyIndex = XamlPropertyIndex(2063i32); pub const UIElement_RotationAxis: XamlPropertyIndex = XamlPropertyIndex(2064i32); pub const UIElement_Scale: XamlPropertyIndex = XamlPropertyIndex(2065i32); pub const UIElement_TransformMatrix: XamlPropertyIndex = XamlPropertyIndex(2066i32); pub const UIElement_Translation: XamlPropertyIndex = XamlPropertyIndex(2067i32); pub const TextBox_HandwritingView: XamlPropertyIndex = XamlPropertyIndex(2068i32); pub const AutomationProperties_HeadingLevel: XamlPropertyIndex = XamlPropertyIndex(2069i32); pub const TextBox_IsHandwritingViewEnabled: XamlPropertyIndex = XamlPropertyIndex(2076i32); pub const RichEditBox_ContentLinkProviders: XamlPropertyIndex = XamlPropertyIndex(2078i32); pub const RichEditBox_ContentLinkBackgroundColor: XamlPropertyIndex = XamlPropertyIndex(2079i32); pub const RichEditBox_ContentLinkForegroundColor: XamlPropertyIndex = XamlPropertyIndex(2080i32); pub const HandwritingView_AreCandidatesEnabled: XamlPropertyIndex = XamlPropertyIndex(2081i32); pub const HandwritingView_IsOpen: XamlPropertyIndex = XamlPropertyIndex(2082i32); pub const HandwritingView_PlacementTarget: XamlPropertyIndex = XamlPropertyIndex(2084i32); pub const HandwritingView_PlacementAlignment: XamlPropertyIndex = XamlPropertyIndex(2085i32); pub const RichEditBox_HandwritingView: XamlPropertyIndex = XamlPropertyIndex(2086i32); pub const RichEditBox_IsHandwritingViewEnabled: XamlPropertyIndex = XamlPropertyIndex(2087i32); pub const MenuFlyoutItem_KeyboardAcceleratorTextOverride: XamlPropertyIndex = XamlPropertyIndex(2090i32); pub const AppBarButton_KeyboardAcceleratorTextOverride: XamlPropertyIndex = XamlPropertyIndex(2091i32); pub const AppBarToggleButton_KeyboardAcceleratorTextOverride: XamlPropertyIndex = XamlPropertyIndex(2092i32); pub const ContentLink_Background: XamlPropertyIndex = XamlPropertyIndex(2093i32); pub const ContentLink_Cursor: XamlPropertyIndex = XamlPropertyIndex(2094i32); pub const ContentLink_ElementSoundMode: XamlPropertyIndex = XamlPropertyIndex(2095i32); pub const ContentLink_FocusState: XamlPropertyIndex = XamlPropertyIndex(2096i32); pub const ContentLink_IsTabStop: XamlPropertyIndex = XamlPropertyIndex(2097i32); pub const ContentLink_TabIndex: XamlPropertyIndex = XamlPropertyIndex(2098i32); pub const ContentLink_XYFocusDown: XamlPropertyIndex = XamlPropertyIndex(2099i32); pub const ContentLink_XYFocusDownNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(2100i32); pub const ContentLink_XYFocusLeft: XamlPropertyIndex = XamlPropertyIndex(2101i32); pub const ContentLink_XYFocusLeftNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(2102i32); pub const ContentLink_XYFocusRight: XamlPropertyIndex = XamlPropertyIndex(2103i32); pub const ContentLink_XYFocusRightNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(2104i32); pub const ContentLink_XYFocusUp: XamlPropertyIndex = XamlPropertyIndex(2105i32); pub const ContentLink_XYFocusUpNavigationStrategy: XamlPropertyIndex = XamlPropertyIndex(2106i32); pub const IconSource_Foreground: XamlPropertyIndex = XamlPropertyIndex(2112i32); pub const BitmapIconSource_ShowAsMonochrome: XamlPropertyIndex = XamlPropertyIndex(2113i32); pub const BitmapIconSource_UriSource: XamlPropertyIndex = XamlPropertyIndex(2114i32); pub const FontIconSource_FontFamily: XamlPropertyIndex = XamlPropertyIndex(2115i32); pub const FontIconSource_FontSize: XamlPropertyIndex = XamlPropertyIndex(2116i32); pub const FontIconSource_FontStyle: XamlPropertyIndex = XamlPropertyIndex(2117i32); pub const FontIconSource_FontWeight: XamlPropertyIndex = XamlPropertyIndex(2118i32); pub const FontIconSource_Glyph: XamlPropertyIndex = XamlPropertyIndex(2119i32); pub const FontIconSource_IsTextScaleFactorEnabled: XamlPropertyIndex = XamlPropertyIndex(2120i32); pub const FontIconSource_MirroredWhenRightToLeft: XamlPropertyIndex = XamlPropertyIndex(2121i32); pub const PathIconSource_Data: XamlPropertyIndex = XamlPropertyIndex(2122i32); pub const SymbolIconSource_Symbol: XamlPropertyIndex = XamlPropertyIndex(2123i32); pub const UIElement_Shadow: XamlPropertyIndex = XamlPropertyIndex(2130i32); pub const IconSourceElement_IconSource: XamlPropertyIndex = XamlPropertyIndex(2131i32); pub const PasswordBox_CanPasteClipboardContent: XamlPropertyIndex = XamlPropertyIndex(2137i32); pub const TextBox_CanPasteClipboardContent: XamlPropertyIndex = XamlPropertyIndex(2138i32); pub const TextBox_CanRedo: XamlPropertyIndex = XamlPropertyIndex(2139i32); pub const TextBox_CanUndo: XamlPropertyIndex = XamlPropertyIndex(2140i32); pub const FlyoutBase_ShowMode: XamlPropertyIndex = XamlPropertyIndex(2141i32); pub const FlyoutBase_Target: XamlPropertyIndex = XamlPropertyIndex(2142i32); pub const Control_CornerRadius: XamlPropertyIndex = XamlPropertyIndex(2143i32); pub const AutomationProperties_IsDialog: XamlPropertyIndex = XamlPropertyIndex(2149i32); pub const AppBarElementContainer_DynamicOverflowOrder: XamlPropertyIndex = XamlPropertyIndex(2150i32); pub const AppBarElementContainer_IsCompact: XamlPropertyIndex = XamlPropertyIndex(2151i32); pub const AppBarElementContainer_IsInOverflow: XamlPropertyIndex = XamlPropertyIndex(2152i32); pub const ScrollContentPresenter_CanContentRenderOutsideBounds: XamlPropertyIndex = XamlPropertyIndex(2157i32); pub const ScrollViewer_CanContentRenderOutsideBounds: XamlPropertyIndex = XamlPropertyIndex(2158i32); pub const RichEditBox_SelectionFlyout: XamlPropertyIndex = XamlPropertyIndex(2159i32); pub const TextBox_SelectionFlyout: XamlPropertyIndex = XamlPropertyIndex(2160i32); pub const Border_BackgroundSizing: XamlPropertyIndex = XamlPropertyIndex(2161i32); pub const ContentPresenter_BackgroundSizing: XamlPropertyIndex = XamlPropertyIndex(2162i32); pub const Control_BackgroundSizing: XamlPropertyIndex = XamlPropertyIndex(2163i32); pub const Grid_BackgroundSizing: XamlPropertyIndex = XamlPropertyIndex(2164i32); pub const RelativePanel_BackgroundSizing: XamlPropertyIndex = XamlPropertyIndex(2165i32); pub const StackPanel_BackgroundSizing: XamlPropertyIndex = XamlPropertyIndex(2166i32); pub const ScrollViewer_HorizontalAnchorRatio: XamlPropertyIndex = XamlPropertyIndex(2170i32); pub const ScrollViewer_VerticalAnchorRatio: XamlPropertyIndex = XamlPropertyIndex(2171i32); pub const ComboBox_Text: XamlPropertyIndex = XamlPropertyIndex(2208i32); pub const TextBox_Description: XamlPropertyIndex = XamlPropertyIndex(2217i32); pub const ToolTip_PlacementRect: XamlPropertyIndex = XamlPropertyIndex(2218i32); pub const RichTextBlock_SelectionFlyout: XamlPropertyIndex = XamlPropertyIndex(2219i32); pub const TextBlock_SelectionFlyout: XamlPropertyIndex = XamlPropertyIndex(2220i32); pub const PasswordBox_SelectionFlyout: XamlPropertyIndex = XamlPropertyIndex(2221i32); pub const Border_BackgroundTransition: XamlPropertyIndex = XamlPropertyIndex(2222i32); pub const ContentPresenter_BackgroundTransition: XamlPropertyIndex = XamlPropertyIndex(2223i32); pub const Panel_BackgroundTransition: XamlPropertyIndex = XamlPropertyIndex(2224i32); pub const ColorPaletteResources_Accent: XamlPropertyIndex = XamlPropertyIndex(2227i32); pub const ColorPaletteResources_AltHigh: XamlPropertyIndex = XamlPropertyIndex(2228i32); pub const ColorPaletteResources_AltLow: XamlPropertyIndex = XamlPropertyIndex(2229i32); pub const ColorPaletteResources_AltMedium: XamlPropertyIndex = XamlPropertyIndex(2230i32); pub const ColorPaletteResources_AltMediumHigh: XamlPropertyIndex = XamlPropertyIndex(2231i32); pub const ColorPaletteResources_AltMediumLow: XamlPropertyIndex = XamlPropertyIndex(2232i32); pub const ColorPaletteResources_BaseHigh: XamlPropertyIndex = XamlPropertyIndex(2233i32); pub const ColorPaletteResources_BaseLow: XamlPropertyIndex = XamlPropertyIndex(2234i32); pub const ColorPaletteResources_BaseMedium: XamlPropertyIndex = XamlPropertyIndex(2235i32); pub const ColorPaletteResources_BaseMediumHigh: XamlPropertyIndex = XamlPropertyIndex(2236i32); pub const ColorPaletteResources_BaseMediumLow: XamlPropertyIndex = XamlPropertyIndex(2237i32); pub const ColorPaletteResources_ChromeAltLow: XamlPropertyIndex = XamlPropertyIndex(2238i32); pub const ColorPaletteResources_ChromeBlackHigh: XamlPropertyIndex = XamlPropertyIndex(2239i32); pub const ColorPaletteResources_ChromeBlackLow: XamlPropertyIndex = XamlPropertyIndex(2240i32); pub const ColorPaletteResources_ChromeBlackMedium: XamlPropertyIndex = XamlPropertyIndex(2241i32); pub const ColorPaletteResources_ChromeBlackMediumLow: XamlPropertyIndex = XamlPropertyIndex(2242i32); pub const ColorPaletteResources_ChromeDisabledHigh: XamlPropertyIndex = XamlPropertyIndex(2243i32); pub const ColorPaletteResources_ChromeDisabledLow: XamlPropertyIndex = XamlPropertyIndex(2244i32); pub const ColorPaletteResources_ChromeGray: XamlPropertyIndex = XamlPropertyIndex(2245i32); pub const ColorPaletteResources_ChromeHigh: XamlPropertyIndex = XamlPropertyIndex(2246i32); pub const ColorPaletteResources_ChromeLow: XamlPropertyIndex = XamlPropertyIndex(2247i32); pub const ColorPaletteResources_ChromeMedium: XamlPropertyIndex = XamlPropertyIndex(2248i32); pub const ColorPaletteResources_ChromeMediumLow: XamlPropertyIndex = XamlPropertyIndex(2249i32); pub const ColorPaletteResources_ChromeWhite: XamlPropertyIndex = XamlPropertyIndex(2250i32); pub const ColorPaletteResources_ErrorText: XamlPropertyIndex = XamlPropertyIndex(2252i32); pub const ColorPaletteResources_ListLow: XamlPropertyIndex = XamlPropertyIndex(2253i32); pub const ColorPaletteResources_ListMedium: XamlPropertyIndex = XamlPropertyIndex(2254i32); pub const UIElement_TranslationTransition: XamlPropertyIndex = XamlPropertyIndex(2255i32); pub const UIElement_OpacityTransition: XamlPropertyIndex = XamlPropertyIndex(2256i32); pub const UIElement_RotationTransition: XamlPropertyIndex = XamlPropertyIndex(2257i32); pub const UIElement_ScaleTransition: XamlPropertyIndex = XamlPropertyIndex(2258i32); pub const BrushTransition_Duration: XamlPropertyIndex = XamlPropertyIndex(2261i32); pub const ScalarTransition_Duration: XamlPropertyIndex = XamlPropertyIndex(2262i32); pub const Vector3Transition_Duration: XamlPropertyIndex = XamlPropertyIndex(2263i32); pub const Vector3Transition_Components: XamlPropertyIndex = XamlPropertyIndex(2266i32); pub const FlyoutBase_IsOpen: XamlPropertyIndex = XamlPropertyIndex(2267i32); pub const StandardUICommand_Kind: XamlPropertyIndex = XamlPropertyIndex(2275i32); pub const UIElement_CanBeScrollAnchor: XamlPropertyIndex = XamlPropertyIndex(2276i32); pub const ThemeShadow_Receivers: XamlPropertyIndex = XamlPropertyIndex(2279i32); pub const ScrollContentPresenter_SizesContentToTemplatedParent: XamlPropertyIndex = XamlPropertyIndex(2280i32); pub const ComboBox_TextBoxStyle: XamlPropertyIndex = XamlPropertyIndex(2281i32); pub const Frame_IsNavigationStackEnabled: XamlPropertyIndex = XamlPropertyIndex(2282i32); pub const RichEditBox_ProofingMenuFlyout: XamlPropertyIndex = XamlPropertyIndex(2283i32); pub const TextBox_ProofingMenuFlyout: XamlPropertyIndex = XamlPropertyIndex(2284i32); pub const ScrollViewer_ReduceViewportForCoreInputViewOcclusions: XamlPropertyIndex = XamlPropertyIndex(2295i32); pub const FlyoutBase_AreOpenCloseAnimationsEnabled: XamlPropertyIndex = XamlPropertyIndex(2296i32); pub const FlyoutBase_InputDevicePrefersPrimaryCommands: XamlPropertyIndex = XamlPropertyIndex(2297i32); pub const CalendarDatePicker_Description: XamlPropertyIndex = XamlPropertyIndex(2300i32); pub const PasswordBox_Description: XamlPropertyIndex = XamlPropertyIndex(2308i32); pub const RichEditBox_Description: XamlPropertyIndex = XamlPropertyIndex(2316i32); pub const AutoSuggestBox_Description: XamlPropertyIndex = XamlPropertyIndex(2331i32); pub const ComboBox_Description: XamlPropertyIndex = XamlPropertyIndex(2339i32); pub const XamlUICommand_AccessKey: XamlPropertyIndex = XamlPropertyIndex(2347i32); pub const XamlUICommand_Command: XamlPropertyIndex = XamlPropertyIndex(2348i32); pub const XamlUICommand_Description: XamlPropertyIndex = XamlPropertyIndex(2349i32); pub const XamlUICommand_IconSource: XamlPropertyIndex = XamlPropertyIndex(2350i32); pub const XamlUICommand_KeyboardAccelerators: XamlPropertyIndex = XamlPropertyIndex(2351i32); pub const XamlUICommand_Label: XamlPropertyIndex = XamlPropertyIndex(2352i32); pub const DatePicker_SelectedDate: XamlPropertyIndex = XamlPropertyIndex(2355i32); pub const TimePicker_SelectedTime: XamlPropertyIndex = XamlPropertyIndex(2356i32); pub const AppBarTemplateSettings_NegativeCompactVerticalDelta: XamlPropertyIndex = XamlPropertyIndex(2367i32); pub const AppBarTemplateSettings_NegativeHiddenVerticalDelta: XamlPropertyIndex = XamlPropertyIndex(2368i32); pub const AppBarTemplateSettings_NegativeMinimalVerticalDelta: XamlPropertyIndex = XamlPropertyIndex(2369i32); pub const FlyoutBase_ShouldConstrainToRootBounds: XamlPropertyIndex = XamlPropertyIndex(2378i32); pub const Popup_ShouldConstrainToRootBounds: XamlPropertyIndex = XamlPropertyIndex(2379i32); pub const FlyoutPresenter_IsDefaultShadowEnabled: XamlPropertyIndex = XamlPropertyIndex(2380i32); pub const MenuFlyoutPresenter_IsDefaultShadowEnabled: XamlPropertyIndex = XamlPropertyIndex(2381i32); pub const UIElement_ActualOffset: XamlPropertyIndex = XamlPropertyIndex(2382i32); pub const UIElement_ActualSize: XamlPropertyIndex = XamlPropertyIndex(2383i32); pub const CommandBarTemplateSettings_OverflowContentCompactYTranslation: XamlPropertyIndex = XamlPropertyIndex(2384i32); pub const CommandBarTemplateSettings_OverflowContentHiddenYTranslation: XamlPropertyIndex = XamlPropertyIndex(2385i32); pub const CommandBarTemplateSettings_OverflowContentMinimalYTranslation: XamlPropertyIndex = XamlPropertyIndex(2386i32); pub const HandwritingView_IsCommandBarOpen: XamlPropertyIndex = XamlPropertyIndex(2395i32); pub const HandwritingView_IsSwitchToKeyboardEnabled: XamlPropertyIndex = XamlPropertyIndex(2396i32); pub const ListViewItemPresenter_SelectionIndicatorVisualEnabled: XamlPropertyIndex = XamlPropertyIndex(2399i32); pub const ListViewItemPresenter_SelectionIndicatorBrush: XamlPropertyIndex = XamlPropertyIndex(2400i32); pub const ListViewItemPresenter_SelectionIndicatorMode: XamlPropertyIndex = XamlPropertyIndex(2401i32); pub const ListViewItemPresenter_SelectionIndicatorPointerOverBrush: XamlPropertyIndex = XamlPropertyIndex(2402i32); pub const ListViewItemPresenter_SelectionIndicatorPressedBrush: XamlPropertyIndex = XamlPropertyIndex(2403i32); pub const ListViewItemPresenter_SelectedBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2410i32); pub const ListViewItemPresenter_SelectedInnerBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2411i32); pub const ListViewItemPresenter_CheckBoxCornerRadius: XamlPropertyIndex = XamlPropertyIndex(2412i32); pub const ListViewItemPresenter_SelectionIndicatorCornerRadius: XamlPropertyIndex = XamlPropertyIndex(2413i32); pub const ListViewItemPresenter_SelectedDisabledBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2414i32); pub const ListViewItemPresenter_SelectedPressedBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2415i32); pub const ListViewItemPresenter_SelectedDisabledBackground: XamlPropertyIndex = XamlPropertyIndex(2416i32); pub const ListViewItemPresenter_PointerOverBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2417i32); pub const ListViewItemPresenter_CheckBoxPointerOverBrush: XamlPropertyIndex = XamlPropertyIndex(2418i32); pub const ListViewItemPresenter_CheckBoxPressedBrush: XamlPropertyIndex = XamlPropertyIndex(2419i32); pub const ListViewItemPresenter_CheckDisabledBrush: XamlPropertyIndex = XamlPropertyIndex(2420i32); pub const ListViewItemPresenter_CheckPressedBrush: XamlPropertyIndex = XamlPropertyIndex(2421i32); pub const ListViewItemPresenter_CheckBoxBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2422i32); pub const ListViewItemPresenter_CheckBoxDisabledBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2423i32); pub const ListViewItemPresenter_CheckBoxPressedBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2424i32); pub const ListViewItemPresenter_CheckBoxDisabledBrush: XamlPropertyIndex = XamlPropertyIndex(2425i32); pub const ListViewItemPresenter_CheckBoxSelectedBrush: XamlPropertyIndex = XamlPropertyIndex(2426i32); pub const ListViewItemPresenter_CheckBoxSelectedDisabledBrush: XamlPropertyIndex = XamlPropertyIndex(2427i32); pub const ListViewItemPresenter_CheckBoxSelectedPointerOverBrush: XamlPropertyIndex = XamlPropertyIndex(2428i32); pub const ListViewItemPresenter_CheckBoxSelectedPressedBrush: XamlPropertyIndex = XamlPropertyIndex(2429i32); pub const ListViewItemPresenter_CheckBoxPointerOverBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2430i32); pub const ListViewItemPresenter_SelectionIndicatorDisabledBrush: XamlPropertyIndex = XamlPropertyIndex(2431i32); pub const CalendarView_BlackoutBackground: XamlPropertyIndex = XamlPropertyIndex(2432i32); pub const CalendarView_BlackoutStrikethroughBrush: XamlPropertyIndex = XamlPropertyIndex(2433i32); pub const CalendarView_CalendarItemCornerRadius: XamlPropertyIndex = XamlPropertyIndex(2434i32); pub const CalendarView_CalendarItemDisabledBackground: XamlPropertyIndex = XamlPropertyIndex(2435i32); pub const CalendarView_CalendarItemHoverBackground: XamlPropertyIndex = XamlPropertyIndex(2436i32); pub const CalendarView_CalendarItemPressedBackground: XamlPropertyIndex = XamlPropertyIndex(2437i32); pub const CalendarView_DayItemMargin: XamlPropertyIndex = XamlPropertyIndex(2438i32); pub const CalendarView_FirstOfMonthLabelMargin: XamlPropertyIndex = XamlPropertyIndex(2439i32); pub const CalendarView_FirstOfYearDecadeLabelMargin: XamlPropertyIndex = XamlPropertyIndex(2440i32); pub const CalendarView_MonthYearItemMargin: XamlPropertyIndex = XamlPropertyIndex(2441i32); pub const CalendarView_OutOfScopeHoverForeground: XamlPropertyIndex = XamlPropertyIndex(2442i32); pub const CalendarView_OutOfScopePressedForeground: XamlPropertyIndex = XamlPropertyIndex(2443i32); pub const CalendarView_SelectedDisabledBorderBrush: XamlPropertyIndex = XamlPropertyIndex(2444i32); pub const CalendarView_SelectedDisabledForeground: XamlPropertyIndex = XamlPropertyIndex(2445i32); pub const CalendarView_SelectedHoverForeground: XamlPropertyIndex = XamlPropertyIndex(2446i32); pub const CalendarView_SelectedPressedForeground: XamlPropertyIndex = XamlPropertyIndex(2447i32); pub const CalendarView_TodayBlackoutForeground: XamlPropertyIndex = XamlPropertyIndex(2448i32); pub const CalendarView_TodayDisabledBackground: XamlPropertyIndex = XamlPropertyIndex(2449i32); pub const CalendarView_TodayHoverBackground: XamlPropertyIndex = XamlPropertyIndex(2450i32); pub const CalendarView_TodayPressedBackground: XamlPropertyIndex = XamlPropertyIndex(2451i32); pub const Popup_ActualPlacement: XamlPropertyIndex = XamlPropertyIndex(2452i32); pub const Popup_DesiredPlacement: XamlPropertyIndex = XamlPropertyIndex(2453i32); pub const Popup_PlacementTarget: XamlPropertyIndex = XamlPropertyIndex(2454i32); pub const AutomationProperties_AutomationControlType: XamlPropertyIndex = XamlPropertyIndex(2455i32); } impl ::core::convert::From<i32> for XamlPropertyIndex { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XamlPropertyIndex { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XamlPropertyIndex { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Core.Direct.XamlPropertyIndex;i4)"); } impl ::windows::core::DefaultType for XamlPropertyIndex { type DefaultType = Self; } #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct XamlTypeIndex(pub i32); impl XamlTypeIndex { pub const AutoSuggestBoxSuggestionChosenEventArgs: XamlTypeIndex = XamlTypeIndex(34i32); pub const AutoSuggestBoxTextChangedEventArgs: XamlTypeIndex = XamlTypeIndex(35i32); pub const CollectionViewSource: XamlTypeIndex = XamlTypeIndex(41i32); pub const ColumnDefinition: XamlTypeIndex = XamlTypeIndex(44i32); pub const GradientStop: XamlTypeIndex = XamlTypeIndex(64i32); pub const InputScope: XamlTypeIndex = XamlTypeIndex(74i32); pub const InputScopeName: XamlTypeIndex = XamlTypeIndex(75i32); pub const KeySpline: XamlTypeIndex = XamlTypeIndex(78i32); pub const PathFigure: XamlTypeIndex = XamlTypeIndex(93i32); pub const PrintDocument: XamlTypeIndex = XamlTypeIndex(100i32); pub const RowDefinition: XamlTypeIndex = XamlTypeIndex(106i32); pub const Style: XamlTypeIndex = XamlTypeIndex(114i32); pub const TimelineMarker: XamlTypeIndex = XamlTypeIndex(126i32); pub const VisualState: XamlTypeIndex = XamlTypeIndex(137i32); pub const VisualStateGroup: XamlTypeIndex = XamlTypeIndex(138i32); pub const VisualStateManager: XamlTypeIndex = XamlTypeIndex(139i32); pub const VisualTransition: XamlTypeIndex = XamlTypeIndex(140i32); pub const AddDeleteThemeTransition: XamlTypeIndex = XamlTypeIndex(177i32); pub const ArcSegment: XamlTypeIndex = XamlTypeIndex(178i32); pub const BackEase: XamlTypeIndex = XamlTypeIndex(179i32); pub const BeginStoryboard: XamlTypeIndex = XamlTypeIndex(180i32); pub const BezierSegment: XamlTypeIndex = XamlTypeIndex(181i32); pub const BindingBase: XamlTypeIndex = XamlTypeIndex(182i32); pub const BitmapCache: XamlTypeIndex = XamlTypeIndex(183i32); pub const BounceEase: XamlTypeIndex = XamlTypeIndex(186i32); pub const CircleEase: XamlTypeIndex = XamlTypeIndex(187i32); pub const ColorAnimation: XamlTypeIndex = XamlTypeIndex(188i32); pub const ColorAnimationUsingKeyFrames: XamlTypeIndex = XamlTypeIndex(189i32); pub const ContentThemeTransition: XamlTypeIndex = XamlTypeIndex(190i32); pub const ControlTemplate: XamlTypeIndex = XamlTypeIndex(191i32); pub const CubicEase: XamlTypeIndex = XamlTypeIndex(192i32); pub const DataTemplate: XamlTypeIndex = XamlTypeIndex(194i32); pub const DiscreteColorKeyFrame: XamlTypeIndex = XamlTypeIndex(195i32); pub const DiscreteDoubleKeyFrame: XamlTypeIndex = XamlTypeIndex(196i32); pub const DiscreteObjectKeyFrame: XamlTypeIndex = XamlTypeIndex(197i32); pub const DiscretePointKeyFrame: XamlTypeIndex = XamlTypeIndex(198i32); pub const DoubleAnimation: XamlTypeIndex = XamlTypeIndex(200i32); pub const DoubleAnimationUsingKeyFrames: XamlTypeIndex = XamlTypeIndex(201i32); pub const EasingColorKeyFrame: XamlTypeIndex = XamlTypeIndex(204i32); pub const EasingDoubleKeyFrame: XamlTypeIndex = XamlTypeIndex(205i32); pub const EasingPointKeyFrame: XamlTypeIndex = XamlTypeIndex(206i32); pub const EdgeUIThemeTransition: XamlTypeIndex = XamlTypeIndex(207i32); pub const ElasticEase: XamlTypeIndex = XamlTypeIndex(208i32); pub const EllipseGeometry: XamlTypeIndex = XamlTypeIndex(209i32); pub const EntranceThemeTransition: XamlTypeIndex = XamlTypeIndex(210i32); pub const EventTrigger: XamlTypeIndex = XamlTypeIndex(211i32); pub const ExponentialEase: XamlTypeIndex = XamlTypeIndex(212i32); pub const Flyout: XamlTypeIndex = XamlTypeIndex(213i32); pub const GeometryGroup: XamlTypeIndex = XamlTypeIndex(216i32); pub const ItemsPanelTemplate: XamlTypeIndex = XamlTypeIndex(227i32); pub const LinearColorKeyFrame: XamlTypeIndex = XamlTypeIndex(230i32); pub const LinearDoubleKeyFrame: XamlTypeIndex = XamlTypeIndex(231i32); pub const LinearPointKeyFrame: XamlTypeIndex = XamlTypeIndex(232i32); pub const LineGeometry: XamlTypeIndex = XamlTypeIndex(233i32); pub const LineSegment: XamlTypeIndex = XamlTypeIndex(234i32); pub const Matrix3DProjection: XamlTypeIndex = XamlTypeIndex(236i32); pub const MenuFlyout: XamlTypeIndex = XamlTypeIndex(238i32); pub const ObjectAnimationUsingKeyFrames: XamlTypeIndex = XamlTypeIndex(240i32); pub const PaneThemeTransition: XamlTypeIndex = XamlTypeIndex(241i32); pub const PathGeometry: XamlTypeIndex = XamlTypeIndex(243i32); pub const PlaneProjection: XamlTypeIndex = XamlTypeIndex(244i32); pub const PointAnimation: XamlTypeIndex = XamlTypeIndex(245i32); pub const PointAnimationUsingKeyFrames: XamlTypeIndex = XamlTypeIndex(246i32); pub const PolyBezierSegment: XamlTypeIndex = XamlTypeIndex(248i32); pub const PolyLineSegment: XamlTypeIndex = XamlTypeIndex(249i32); pub const PolyQuadraticBezierSegment: XamlTypeIndex = XamlTypeIndex(250i32); pub const PopupThemeTransition: XamlTypeIndex = XamlTypeIndex(251i32); pub const PowerEase: XamlTypeIndex = XamlTypeIndex(252i32); pub const QuadraticBezierSegment: XamlTypeIndex = XamlTypeIndex(254i32); pub const QuadraticEase: XamlTypeIndex = XamlTypeIndex(255i32); pub const QuarticEase: XamlTypeIndex = XamlTypeIndex(256i32); pub const QuinticEase: XamlTypeIndex = XamlTypeIndex(257i32); pub const RectangleGeometry: XamlTypeIndex = XamlTypeIndex(258i32); pub const RelativeSource: XamlTypeIndex = XamlTypeIndex(259i32); pub const RenderTargetBitmap: XamlTypeIndex = XamlTypeIndex(260i32); pub const ReorderThemeTransition: XamlTypeIndex = XamlTypeIndex(261i32); pub const RepositionThemeTransition: XamlTypeIndex = XamlTypeIndex(262i32); pub const Setter: XamlTypeIndex = XamlTypeIndex(263i32); pub const SineEase: XamlTypeIndex = XamlTypeIndex(264i32); pub const SolidColorBrush: XamlTypeIndex = XamlTypeIndex(265i32); pub const SplineColorKeyFrame: XamlTypeIndex = XamlTypeIndex(266i32); pub const SplineDoubleKeyFrame: XamlTypeIndex = XamlTypeIndex(267i32); pub const SplinePointKeyFrame: XamlTypeIndex = XamlTypeIndex(268i32); pub const BitmapImage: XamlTypeIndex = XamlTypeIndex(285i32); pub const Border: XamlTypeIndex = XamlTypeIndex(286i32); pub const CaptureElement: XamlTypeIndex = XamlTypeIndex(288i32); pub const CompositeTransform: XamlTypeIndex = XamlTypeIndex(295i32); pub const ContentPresenter: XamlTypeIndex = XamlTypeIndex(296i32); pub const DragItemThemeAnimation: XamlTypeIndex = XamlTypeIndex(302i32); pub const DragOverThemeAnimation: XamlTypeIndex = XamlTypeIndex(303i32); pub const DropTargetItemThemeAnimation: XamlTypeIndex = XamlTypeIndex(304i32); pub const FadeInThemeAnimation: XamlTypeIndex = XamlTypeIndex(306i32); pub const FadeOutThemeAnimation: XamlTypeIndex = XamlTypeIndex(307i32); pub const Glyphs: XamlTypeIndex = XamlTypeIndex(312i32); pub const Image: XamlTypeIndex = XamlTypeIndex(326i32); pub const ImageBrush: XamlTypeIndex = XamlTypeIndex(328i32); pub const InlineUIContainer: XamlTypeIndex = XamlTypeIndex(329i32); pub const ItemsPresenter: XamlTypeIndex = XamlTypeIndex(332i32); pub const LinearGradientBrush: XamlTypeIndex = XamlTypeIndex(334i32); pub const LineBreak: XamlTypeIndex = XamlTypeIndex(335i32); pub const MatrixTransform: XamlTypeIndex = XamlTypeIndex(340i32); pub const MediaElement: XamlTypeIndex = XamlTypeIndex(342i32); pub const Paragraph: XamlTypeIndex = XamlTypeIndex(349i32); pub const PointerDownThemeAnimation: XamlTypeIndex = XamlTypeIndex(357i32); pub const PointerUpThemeAnimation: XamlTypeIndex = XamlTypeIndex(359i32); pub const PopInThemeAnimation: XamlTypeIndex = XamlTypeIndex(361i32); pub const PopOutThemeAnimation: XamlTypeIndex = XamlTypeIndex(362i32); pub const Popup: XamlTypeIndex = XamlTypeIndex(363i32); pub const RepositionThemeAnimation: XamlTypeIndex = XamlTypeIndex(370i32); pub const ResourceDictionary: XamlTypeIndex = XamlTypeIndex(371i32); pub const RichTextBlock: XamlTypeIndex = XamlTypeIndex(374i32); pub const RichTextBlockOverflow: XamlTypeIndex = XamlTypeIndex(376i32); pub const RotateTransform: XamlTypeIndex = XamlTypeIndex(378i32); pub const Run: XamlTypeIndex = XamlTypeIndex(380i32); pub const ScaleTransform: XamlTypeIndex = XamlTypeIndex(381i32); pub const SkewTransform: XamlTypeIndex = XamlTypeIndex(389i32); pub const Span: XamlTypeIndex = XamlTypeIndex(390i32); pub const SplitCloseThemeAnimation: XamlTypeIndex = XamlTypeIndex(391i32); pub const SplitOpenThemeAnimation: XamlTypeIndex = XamlTypeIndex(392i32); pub const Storyboard: XamlTypeIndex = XamlTypeIndex(393i32); pub const SwipeBackThemeAnimation: XamlTypeIndex = XamlTypeIndex(394i32); pub const SwipeHintThemeAnimation: XamlTypeIndex = XamlTypeIndex(395i32); pub const TextBlock: XamlTypeIndex = XamlTypeIndex(396i32); pub const TransformGroup: XamlTypeIndex = XamlTypeIndex(411i32); pub const TranslateTransform: XamlTypeIndex = XamlTypeIndex(413i32); pub const Viewbox: XamlTypeIndex = XamlTypeIndex(417i32); pub const WebViewBrush: XamlTypeIndex = XamlTypeIndex(423i32); pub const AppBarSeparator: XamlTypeIndex = XamlTypeIndex(427i32); pub const BitmapIcon: XamlTypeIndex = XamlTypeIndex(429i32); pub const Bold: XamlTypeIndex = XamlTypeIndex(430i32); pub const Canvas: XamlTypeIndex = XamlTypeIndex(432i32); pub const ContentControl: XamlTypeIndex = XamlTypeIndex(435i32); pub const DatePicker: XamlTypeIndex = XamlTypeIndex(436i32); pub const DependencyObjectCollection: XamlTypeIndex = XamlTypeIndex(437i32); pub const Ellipse: XamlTypeIndex = XamlTypeIndex(438i32); pub const FontIcon: XamlTypeIndex = XamlTypeIndex(440i32); pub const Grid: XamlTypeIndex = XamlTypeIndex(442i32); pub const Hub: XamlTypeIndex = XamlTypeIndex(445i32); pub const HubSection: XamlTypeIndex = XamlTypeIndex(446i32); pub const Hyperlink: XamlTypeIndex = XamlTypeIndex(447i32); pub const Italic: XamlTypeIndex = XamlTypeIndex(449i32); pub const ItemsControl: XamlTypeIndex = XamlTypeIndex(451i32); pub const Line: XamlTypeIndex = XamlTypeIndex(452i32); pub const MediaTransportControls: XamlTypeIndex = XamlTypeIndex(458i32); pub const PasswordBox: XamlTypeIndex = XamlTypeIndex(462i32); pub const Path: XamlTypeIndex = XamlTypeIndex(463i32); pub const PathIcon: XamlTypeIndex = XamlTypeIndex(464i32); pub const Polygon: XamlTypeIndex = XamlTypeIndex(465i32); pub const Polyline: XamlTypeIndex = XamlTypeIndex(466i32); pub const ProgressRing: XamlTypeIndex = XamlTypeIndex(468i32); pub const Rectangle: XamlTypeIndex = XamlTypeIndex(470i32); pub const RichEditBox: XamlTypeIndex = XamlTypeIndex(473i32); pub const ScrollContentPresenter: XamlTypeIndex = XamlTypeIndex(476i32); pub const SearchBox: XamlTypeIndex = XamlTypeIndex(477i32); pub const SemanticZoom: XamlTypeIndex = XamlTypeIndex(479i32); pub const StackPanel: XamlTypeIndex = XamlTypeIndex(481i32); pub const SymbolIcon: XamlTypeIndex = XamlTypeIndex(482i32); pub const TextBox: XamlTypeIndex = XamlTypeIndex(483i32); pub const Thumb: XamlTypeIndex = XamlTypeIndex(485i32); pub const TickBar: XamlTypeIndex = XamlTypeIndex(486i32); pub const TimePicker: XamlTypeIndex = XamlTypeIndex(487i32); pub const ToggleSwitch: XamlTypeIndex = XamlTypeIndex(489i32); pub const Underline: XamlTypeIndex = XamlTypeIndex(490i32); pub const UserControl: XamlTypeIndex = XamlTypeIndex(491i32); pub const VariableSizedWrapGrid: XamlTypeIndex = XamlTypeIndex(492i32); pub const WebView: XamlTypeIndex = XamlTypeIndex(494i32); pub const AppBar: XamlTypeIndex = XamlTypeIndex(495i32); pub const AutoSuggestBox: XamlTypeIndex = XamlTypeIndex(499i32); pub const CarouselPanel: XamlTypeIndex = XamlTypeIndex(502i32); pub const ContentDialog: XamlTypeIndex = XamlTypeIndex(506i32); pub const FlyoutPresenter: XamlTypeIndex = XamlTypeIndex(508i32); pub const Frame: XamlTypeIndex = XamlTypeIndex(509i32); pub const GridViewItemPresenter: XamlTypeIndex = XamlTypeIndex(511i32); pub const GroupItem: XamlTypeIndex = XamlTypeIndex(512i32); pub const ItemsStackPanel: XamlTypeIndex = XamlTypeIndex(514i32); pub const ItemsWrapGrid: XamlTypeIndex = XamlTypeIndex(515i32); pub const ListViewItemPresenter: XamlTypeIndex = XamlTypeIndex(520i32); pub const MenuFlyoutItem: XamlTypeIndex = XamlTypeIndex(521i32); pub const MenuFlyoutPresenter: XamlTypeIndex = XamlTypeIndex(522i32); pub const MenuFlyoutSeparator: XamlTypeIndex = XamlTypeIndex(523i32); pub const Page: XamlTypeIndex = XamlTypeIndex(525i32); pub const ProgressBar: XamlTypeIndex = XamlTypeIndex(528i32); pub const ScrollBar: XamlTypeIndex = XamlTypeIndex(530i32); pub const SettingsFlyout: XamlTypeIndex = XamlTypeIndex(533i32); pub const Slider: XamlTypeIndex = XamlTypeIndex(534i32); pub const SwapChainBackgroundPanel: XamlTypeIndex = XamlTypeIndex(535i32); pub const SwapChainPanel: XamlTypeIndex = XamlTypeIndex(536i32); pub const ToolTip: XamlTypeIndex = XamlTypeIndex(538i32); pub const Button: XamlTypeIndex = XamlTypeIndex(540i32); pub const ComboBoxItem: XamlTypeIndex = XamlTypeIndex(541i32); pub const CommandBar: XamlTypeIndex = XamlTypeIndex(542i32); pub const FlipViewItem: XamlTypeIndex = XamlTypeIndex(543i32); pub const GridViewHeaderItem: XamlTypeIndex = XamlTypeIndex(545i32); pub const HyperlinkButton: XamlTypeIndex = XamlTypeIndex(546i32); pub const ListBoxItem: XamlTypeIndex = XamlTypeIndex(547i32); pub const ListViewHeaderItem: XamlTypeIndex = XamlTypeIndex(550i32); pub const RepeatButton: XamlTypeIndex = XamlTypeIndex(551i32); pub const ScrollViewer: XamlTypeIndex = XamlTypeIndex(552i32); pub const ToggleButton: XamlTypeIndex = XamlTypeIndex(553i32); pub const ToggleMenuFlyoutItem: XamlTypeIndex = XamlTypeIndex(554i32); pub const VirtualizingStackPanel: XamlTypeIndex = XamlTypeIndex(555i32); pub const WrapGrid: XamlTypeIndex = XamlTypeIndex(556i32); pub const AppBarButton: XamlTypeIndex = XamlTypeIndex(557i32); pub const AppBarToggleButton: XamlTypeIndex = XamlTypeIndex(558i32); pub const CheckBox: XamlTypeIndex = XamlTypeIndex(559i32); pub const GridViewItem: XamlTypeIndex = XamlTypeIndex(560i32); pub const ListViewItem: XamlTypeIndex = XamlTypeIndex(561i32); pub const RadioButton: XamlTypeIndex = XamlTypeIndex(562i32); pub const Binding: XamlTypeIndex = XamlTypeIndex(564i32); pub const ComboBox: XamlTypeIndex = XamlTypeIndex(566i32); pub const FlipView: XamlTypeIndex = XamlTypeIndex(567i32); pub const ListBox: XamlTypeIndex = XamlTypeIndex(568i32); pub const GridView: XamlTypeIndex = XamlTypeIndex(570i32); pub const ListView: XamlTypeIndex = XamlTypeIndex(571i32); pub const CalendarView: XamlTypeIndex = XamlTypeIndex(707i32); pub const CalendarViewDayItem: XamlTypeIndex = XamlTypeIndex(709i32); pub const CalendarPanel: XamlTypeIndex = XamlTypeIndex(723i32); pub const SplitView: XamlTypeIndex = XamlTypeIndex(728i32); pub const CompositeTransform3D: XamlTypeIndex = XamlTypeIndex(732i32); pub const PerspectiveTransform3D: XamlTypeIndex = XamlTypeIndex(733i32); pub const RelativePanel: XamlTypeIndex = XamlTypeIndex(744i32); pub const InkCanvas: XamlTypeIndex = XamlTypeIndex(748i32); pub const MenuFlyoutSubItem: XamlTypeIndex = XamlTypeIndex(749i32); pub const AdaptiveTrigger: XamlTypeIndex = XamlTypeIndex(757i32); pub const SoftwareBitmapSource: XamlTypeIndex = XamlTypeIndex(761i32); pub const StateTrigger: XamlTypeIndex = XamlTypeIndex(767i32); pub const CalendarDatePicker: XamlTypeIndex = XamlTypeIndex(774i32); pub const AutoSuggestBoxQuerySubmittedEventArgs: XamlTypeIndex = XamlTypeIndex(778i32); pub const CommandBarOverflowPresenter: XamlTypeIndex = XamlTypeIndex(781i32); pub const DrillInThemeAnimation: XamlTypeIndex = XamlTypeIndex(782i32); pub const DrillOutThemeAnimation: XamlTypeIndex = XamlTypeIndex(783i32); pub const AutomationAnnotation: XamlTypeIndex = XamlTypeIndex(789i32); pub const AutomationPeerAnnotation: XamlTypeIndex = XamlTypeIndex(790i32); pub const MediaPlayerPresenter: XamlTypeIndex = XamlTypeIndex(828i32); pub const MediaPlayerElement: XamlTypeIndex = XamlTypeIndex(829i32); pub const XamlLight: XamlTypeIndex = XamlTypeIndex(855i32); pub const SvgImageSource: XamlTypeIndex = XamlTypeIndex(860i32); pub const KeyboardAccelerator: XamlTypeIndex = XamlTypeIndex(897i32); pub const HandwritingView: XamlTypeIndex = XamlTypeIndex(920i32); pub const ContentLink: XamlTypeIndex = XamlTypeIndex(925i32); pub const BitmapIconSource: XamlTypeIndex = XamlTypeIndex(929i32); pub const FontIconSource: XamlTypeIndex = XamlTypeIndex(930i32); pub const PathIconSource: XamlTypeIndex = XamlTypeIndex(931i32); pub const SymbolIconSource: XamlTypeIndex = XamlTypeIndex(933i32); pub const IconSourceElement: XamlTypeIndex = XamlTypeIndex(939i32); pub const AppBarElementContainer: XamlTypeIndex = XamlTypeIndex(945i32); pub const ColorPaletteResources: XamlTypeIndex = XamlTypeIndex(952i32); pub const StandardUICommand: XamlTypeIndex = XamlTypeIndex(961i32); pub const ThemeShadow: XamlTypeIndex = XamlTypeIndex(964i32); pub const XamlUICommand: XamlTypeIndex = XamlTypeIndex(969i32); } impl ::core::convert::From<i32> for XamlTypeIndex { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for XamlTypeIndex { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for XamlTypeIndex { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.UI.Xaml.Core.Direct.XamlTypeIndex;i4)"); } impl ::windows::core::DefaultType for XamlTypeIndex { type DefaultType = Self; }
use proconio::{input, marker::Bytes}; fn main() { input! { s: Bytes, }; let b1 = s.iter().position(|&b| b == b'B').unwrap(); let b2 = s.iter().rposition(|&b| b == b'B').unwrap(); if b1 % 2 == b2 % 2 { println!("No"); return; } let r1 = s.iter().position(|&b| b == b'R').unwrap(); let r2 = s.iter().rposition(|&b| b == b'R').unwrap(); let k = s.iter().rposition(|&b| b == b'K').unwrap(); if r1 < k && k < r2 { println!("Yes"); } else { println!("No"); } }
#[macro_use] extern crate failure; use std::fmt::Debug; use failure::Fail; #[derive(Debug, Fail)] #[fail(display = "An error has occurred.")] pub struct UnboundedGenericTupleError<T: 'static + Debug + Send + Sync>(T); #[test] fn unbounded_generic_tuple_error() { let s = format!("{}", UnboundedGenericTupleError(())); assert_eq!(&s[..], "An error has occurred."); } #[derive(Debug, Fail)] #[fail(display = "An error has occurred: {}", _0)] pub struct FailBoundsGenericTupleError<T: Fail>(T); #[test] fn fail_bounds_generic_tuple_error() { let error = FailBoundsGenericTupleError(UnboundedGenericTupleError(())); let s = format!("{}", error); assert_eq!(&s[..], "An error has occurred: An error has occurred."); } pub trait NoDisplay: 'static + Debug + Send + Sync {} impl NoDisplay for &'static str {} #[derive(Debug, Fail)] #[fail(display = "An error has occurred: {:?}", _0)] pub struct CustomBoundsGenericTupleError<T: NoDisplay>(T); #[test] fn custom_bounds_generic_tuple_error() { let error = CustomBoundsGenericTupleError("more details unavailable."); let s = format!("{}", error); assert_eq!( &s[..], "An error has occurred: \"more details unavailable.\"" ); }
use trust_dns::rr::domain::Name; use trust_dns::rr::dns_class::DNSClass; use trust_dns::rr::record_type::RecordType; use trust_dns::op::{MessageType, OpCode, Query}; use trust_dns::serialize::binary::{BinEncoder, BinDecoder, BinSerializable}; pub use trust_dns::op::Message; pub fn a_query(host: &str) -> Query { let mut query = Query::new(); let root = Name::root(); let name = Name::parse(host, Some(&root)).unwrap(); query.name(name).query_class(DNSClass::IN).query_type(RecordType::A); query } pub fn any_query(host: &str) -> Query { let mut query = Query::new(); let root = Name::root(); let name = Name::parse(host, Some(&root)).unwrap(); query.name(name).query_class(DNSClass::IN).query_type(RecordType::A); query } pub fn build_query_message(query: Query) -> Message { let mut msg: Message = Message::new(); msg.message_type(MessageType::Query).op_code(OpCode::Query).recursion_desired(true); msg.add_query(query); msg } pub fn encode_message(buf: &mut Vec<u8>, msg: &Message) { let mut encoder = BinEncoder::new(buf); msg.emit(&mut encoder).unwrap(); } pub fn decode_message(buf: &mut [u8]) -> Message { let mut decoder = BinDecoder::new(&buf); Message::read(&mut decoder).unwrap() }
//! mhpmcounter, Xuantie performance counter /// mhpmcounter3: L1 I-cache access counter pub fn l1_i_cache_access() -> usize { unsafe { get_csr_value!(0xB03) } } /// mhpmcounter4: L1 I-cache miss counter pub fn l1_i_cache_miss() -> usize { unsafe { get_csr_value!(0xB04) } } /// mhpmcounter5: I-uTLB miss counter pub fn i_utlb_miss() -> usize { unsafe { get_csr_value!(0xB05) } } /// mhpmcounter6: D-uTLB miss counter pub fn d_utlb_miss() -> usize { unsafe { get_csr_value!(0xB06) } } /// mhpmcounter7: jTLB miss counter pub fn jtlb_miss() -> usize { unsafe { get_csr_value!(0xB07) } } /// mhpmcounter8: Conditional branch mispredict counter pub fn conditional_branch_mispredict() -> usize { unsafe { get_csr_value!(0xB08) } } /// mhpmcounter9: Conditional branch instruction counter pub fn conditional_branch_instruction() -> usize { unsafe { get_csr_value!(0xB09) } } /// mhpmcounter13: Store instruction counter pub fn store_instruction() -> usize { unsafe { get_csr_value!(0xB0D) } } /// mhpmcounter14: L1 D-cache read access counter pub fn l1_d_cache_read_access() -> usize { unsafe { get_csr_value!(0xB0E) } } /// mhpmcounter15: L1 D-cache read miss counter pub fn l1_d_cache_read_miss() -> usize { unsafe { get_csr_value!(0xB0F) } } /// mhpmcounter16: L1 D-cache write access counter pub fn l1_d_cache_write_access() -> usize { unsafe { get_csr_value!(0xB10) } } /// mhpmcounter17: L1 D-cache write miss counter pub fn l1_d_cache_write_miss() -> usize { unsafe { get_csr_value!(0xB11) } } // 10..=12, 18..=31: undefined
use crate::Part; #[derive(Debug, Copy, Clone, PartialEq, Eq)] enum Space { Open, Filled, } struct Map { data: Vec<Vec<Space>>, width: usize, height: usize, } impl Map { fn new(map: &str) -> Self { let data: Vec<_> = map.split('\n').filter_map(|l| { if l.trim() != "" { Some(l.chars().map(|c| { match c { '.' => Space::Open, '#' => Space::Filled, _ => panic!("Unexpected input {:?}", c), } }).collect::<Vec<_>>()) } else { None } }).collect(); let height = data.len(); let width = data[0].len(); Map { data, width, height } } fn read(&self, x: usize, y: usize) -> Option<Space> { if y >= self.height { None } else { let idx = x % self.width; Some(self.data[y][idx]) } } } pub fn run(part: Part, input_str: &str) { let input = Map::new(&input_str); match part { Part::First => part1(&input), Part::Second => part2(&input), Part::All => { part1(&input); part2(&input); }, } } fn trees_encountered(map: &Map, dx: usize, dy: usize) -> usize { let mut x = 0; let mut y = 0; let mut num_trees = 0; while let Some(space) = map.read(x, y) { if space == Space::Filled { num_trees += 1; } x += dx; y += dy; } num_trees } fn part1(map: &Map) { let num_trees = trees_encountered(&map, 3, 1); println!("{}", num_trees); } fn part2(map: &Map) { let dirs = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)]; let total = dirs.iter().map(|(x, y)| trees_encountered(&map, *x, *y) as u64).fold(1, |a, b| a*b); println!("{}", total); }
use tui::widgets::{Borders, Block, Paragraph, Table, Row}; use tui::text::Text; use tui::style::{Style, Modifier, Color}; use tui::layout::Constraint; use crate::runtime::data::launches::structures::{Launch, PadLocation, LaunchPad, LSP, RocketConfiguration, Rocket}; pub fn render_missing() -> Paragraph<'static> { Paragraph::new( Text::raw( " Unfortunately, there is not a launch currently available.\n Please check the logs." ) ) .block( Block::default() .title(" Launch Info ") .borders(Borders::ALL) ) } pub fn render_dynamic(launch: Launch) -> Table<'static> { let suc = Text::styled("Launch Successful", Style::default().fg(Color::LightGreen)); let tbd = Text::styled("To Be Determined", Style::default().fg(Color::Yellow)); let tbc = Text::styled("To Be Confirmed", Style::default().fg(Color::LightYellow)); let paf = Text::styled("Partial Failure", Style::default().fg(Color::LightYellow)); let fal = Text::styled("Launch Failure", Style::default().fg(Color::Red)); let g4l = Text::styled("Go For Launch", Style::default().fg(Color::Green)); let inf = Text::styled("In Flight", Style::default().fg(Color::LightGreen)); let hol = Text::styled("On Hold", Style::default().fg(Color::Gray)); let fetching = Text::raw("Fetching..."); let raw_name = launch.name.clone().unwrap_or("Unknown Launch | Unknown Mission".to_string()); let pieces: Vec<&str> = raw_name.split(" | ").collect(); let mission = pieces.last().unwrap_or(&"Unknown Mission").to_string(); let vehicle = launch.rocket.clone().unwrap_or(Rocket { id: None, configuration: None, }).configuration .unwrap_or(RocketConfiguration { id: None, name: None, description: None, family: None, full_name: None, manufacturer: None, variant: None, alias: None, min_stage: None, max_stage: None, length: None, diameter: None, maiden_flight: None, launch_mass: None, leo_capacity: None, gto_capacity: None, to_thrust: None, apogee: None, vehicle_range: None, total_launch_count: None, consecutive_successful_launches: None, successful_launches: None, failed_launches: None, pending_launches: None, }); let lsp = launch.launch_service_provider.clone().unwrap_or(LSP { id: None, name: None, features: None, org: None, country_code: None, abbrev: None, description: None, administrator: None, founding_year: None, launchers: None, spacecraft: None, launch_library_url: None, total_launch_count: None, consecutive_successful_launches: None, successful_launches: None, failed_launches: None, pending_launches: None, consecutive_successful_landings: None, successful_landings: None, failed_landings: None, attempted_landings: None, }); let launchpad = launch.pad.unwrap_or(LaunchPad { id: None, agency_id: None, name: None, latitude: None, longitude: None, location: PadLocation { id: None, name: None, country_code: None, total_launch_count: None, total_landing_count: None, }, total_launch_count: None, }); let status = match launch.status.id.clone() { None => fetching, Some(status) => { match status { 1 => g4l, 2 => tbd, 3 => suc, 4 => fal, 5 => hol, 6 => inf, 7 => paf, 8 => tbc, _ => fetching } } }; Table::new(vec![ Row::new(vec![Text::from(" Name"), Text::styled(launch.name.unwrap_or("Unknown Launch | Unknown Mission".to_string()), Style::default().add_modifier(Modifier::UNDERLINED))]), Row::new(vec![" Provider".to_string(), lsp.name.unwrap_or("Unknown Provider".to_string())]), Row::new(vec![" Vehicle".to_string(), vehicle.name.unwrap_or("Unknown Launch Vehicle".to_string())]), Row::new(vec![" Mission".to_string(), mission.clone()]), Row::new(vec![" Pad".to_string(), launchpad.name.unwrap_or("Unkown Launchpad".to_string())]), Row::new(vec![" Location".to_string(), launchpad.location.name.unwrap_or("Unkown Location".to_string())]), Row::new(vec![Text::from(" Status"), status]), ]) .widths(&[ Constraint::Min(10), Constraint::Min(45) ]) .block(Block::default().title(" Launch Info ").borders(Borders::ALL)) }
#[macro_use] extern crate lazy_static; mod cli; pub mod ward; use cli::WardArgs; use colored::Colorize; use encoding_rs::{Encoding, UTF_8}; use mime::Mime; use regex::Regex; use reqwest::header::{HeaderMap, HeaderName, HeaderValue, LOCATION}; use reqwest::redirect::Policy; use reqwest::{Body, header, Method, Proxy, Response}; use scraper::{Html, Selector}; use serde::{Deserialize, Serialize}; use std::collections::HashMap; use std::collections::HashSet; use std::fs::File; use std::io::Cursor; use std::io::Read; use std::io::{self, BufRead}; use std::iter::FromIterator; use std::path::{Path, PathBuf}; use std::str; use std::str::FromStr; use std::sync::Arc; use std::time::Duration; use std::{env, fmt, process}; use url::Url; use ward::{check, RawData}; use md5::{Digest, Md5}; use std::sync::RwLock; use cached::proc_macro::cached; use cached::SizedCache; #[derive(Debug, Serialize, Deserialize, Clone)] pub struct VerifyWebFingerPrint { name: String, priority: u32, fingerprint: Vec<WebFingerPrint>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct WebFingerPrintRequest { path: String, request_method: String, request_headers: HashMap<String, String>, request_data: String, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct WebFingerPrintMatch { status_code: u16, #[serde(default)] favicon_hash: Vec<String>, headers: HashMap<String, String>, keyword: Vec<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct V3WebFingerPrint { #[serde(default)] name: String, #[serde(default)] priority: u32, request: WebFingerPrintRequest, match_rules: WebFingerPrintMatch, } //TODO 整理lib文件 #[derive(Debug, Serialize, Deserialize, Clone)] pub struct WebFingerPrint { #[serde(default)] name: String, path: String, status_code: u16, headers: HashMap<String, String>, keyword: Vec<String>, #[serde(default)] priority: u32, request_method: String, request_headers: HashMap<String, String>, request_data: String, #[serde(default)] favicon_hash: Vec<String>, } impl WebFingerPrint { pub fn new() -> Self { Self { path: String::from(""), name: String::from(""), status_code: 0, headers: HashMap::new(), keyword: vec![], priority: 1, request_method: String::from(""), request_headers: HashMap::new(), request_data: String::from(""), favicon_hash: vec![], } } } // 将指纹分成首页识别,特殊请求识别和favicon的哈希识别 #[derive(Debug, Serialize, Deserialize, Clone)] pub struct WebFingerPrintLib { index: Vec<V3WebFingerPrint>, special: Vec<V3WebFingerPrint>, favicon: Vec<V3WebFingerPrint>, } impl WebFingerPrintLib { pub fn new() -> Self { Self { index: vec![], special: vec![], favicon: vec![], } } fn read_form_file(&self) -> Vec<WebFingerPrint> { let self_path: PathBuf = env::current_exe().unwrap_or(PathBuf::new()); let path = Path::new(&self_path).parent().unwrap_or(Path::new("")); return if !CONFIG.verify.is_empty() { let mut file = match File::open(CONFIG.verify.clone()) { Err(_) => { println!("The verification file cannot be found in the current directory!"); std::process::exit(0); } Ok(file) => file, }; let mut data = String::new(); file.read_to_string(&mut data).unwrap(); let mut web_fingerprint: Vec<WebFingerPrint> = vec![]; let verify_fingerprints: VerifyWebFingerPrint = serde_yaml::from_str(&data).expect("Bad Yaml"); for mut verify_fingerprint in verify_fingerprints.fingerprint { verify_fingerprint.name = verify_fingerprints.name.clone(); verify_fingerprint.priority = verify_fingerprints.priority.clone(); web_fingerprint.push(verify_fingerprint); } web_fingerprint } else { let mut file = match File::open(path.join("web_fingerprint_v3.json")) { Err(_) => { println!("The fingerprint library cannot be found in the current directory!"); std::process::exit(0); } Ok(file) => file, }; let mut data = String::new(); file.read_to_string(&mut data).unwrap(); let web_fingerprint: Vec<WebFingerPrint> = serde_json::from_str(&data).expect("Bad Json"); web_fingerprint }; } pub fn init(&mut self) { self.index.clear(); self.special.clear(); self.favicon.clear(); let web_fingerprint: Vec<WebFingerPrint> = self.read_form_file(); for f_rule in web_fingerprint { let request = WebFingerPrintRequest { path: f_rule.path.clone(), request_method: f_rule.request_method.clone(), request_headers: f_rule.request_headers.clone(), request_data: f_rule.request_data.clone(), }; let match_rules = WebFingerPrintMatch { status_code: f_rule.status_code, favicon_hash: f_rule.favicon_hash.clone(), headers: f_rule.headers, keyword: f_rule.keyword, }; let v3_web_fingerprint = V3WebFingerPrint { name: f_rule.name, priority: f_rule.priority, request, match_rules, }; if f_rule.path == "/" && f_rule.request_headers.is_empty() && f_rule.request_method == "get" && f_rule.request_data.is_empty() && f_rule.favicon_hash.is_empty() { self.index.push(v3_web_fingerprint); } else if !f_rule.favicon_hash.is_empty() { self.favicon.push(v3_web_fingerprint); } else { self.special.push(v3_web_fingerprint); } } } } // 加载指纹库到常量,防止在文件系统反复加载 lazy_static! { static ref WEB_FINGERPRINT_LIB_DATA: RwLock<WebFingerPrintLib> = RwLock::new({ let mut web_fingerprint_lib = WebFingerPrintLib::new(); web_fingerprint_lib.init(); web_fingerprint_lib }); } pub fn update_fingerprint() { WEB_FINGERPRINT_LIB_DATA.write().unwrap().init(); } lazy_static! { static ref CONFIG: WardArgs = { let config = WardArgs::new(); config }; } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub enum WardError { Fetch(String), Analyze(String), Other(String), } impl fmt::Display for WardError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!( f, "{}", match self { WardError::Fetch(err) => format!("Fetch/{}", err), WardError::Analyze(err) => format!("Analyze/{}", err), WardError::Other(err) => format!("Other/{}", err), } ) } } impl std::convert::From<std::io::Error> for WardError { fn from(err: std::io::Error) -> Self { WardError::Other(err.to_string()) } } impl From<&dyn std::error::Error> for WardError { fn from(err: &dyn std::error::Error) -> Self { WardError::Other(err.to_string()) } } impl From<reqwest::Error> for WardError { fn from(err: reqwest::Error) -> Self { WardError::Other(err.to_string()) } } impl From<std::str::Utf8Error> for WardError { fn from(err: std::str::Utf8Error) -> Self { WardError::Other(err.to_string()) } } impl From<url::ParseError> for WardError { fn from(err: url::ParseError) -> Self { WardError::Other(err.to_string()) } } async fn send_requests( mut url: Url, fingerprint: &WebFingerPrintRequest, ) -> Result<Response, reqwest::Error> { let mut headers = header::HeaderMap::new(); let ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36"; headers.insert(header::USER_AGENT, header::HeaderValue::from_static(ua)); let method = Method::from_str(&fingerprint.request_method.to_uppercase()).unwrap_or(Method::GET); let body_data = Body::from(base64::decode(fingerprint.request_data.clone()).unwrap_or_default()); if !fingerprint.request_headers.is_empty() { for (k, v) in fingerprint.request_headers.clone() { headers.insert( HeaderName::from_str(&k).unwrap(), HeaderValue::from_str(&v).unwrap(), ); } } if fingerprint.path != "/" { url.set_path(fingerprint.path.as_str()); } let client = reqwest::Client::builder() .danger_accept_invalid_certs(true) .default_headers(headers.clone()) .redirect(Policy::none()) .timeout(Duration::new(CONFIG.timeout, 0)); if !CONFIG.proxy.is_empty() { match Url::parse(CONFIG.proxy.clone().as_str()) { Ok(proxy_uri) => { let proxy_obj = Proxy::all(proxy_uri).unwrap(); return client .proxy(proxy_obj) .build() .unwrap() .request(method, url.as_ref()) .body(body_data) .send() .await; } Err(_) => { println!("Invalid Proxy Uri"); process::exit(0); } }; } return client.build() .unwrap() .request(method, url.as_ref()) .body(body_data) .send().await; } lazy_static! { static ref RE_COMPILE_BY_CHARSET: Regex = Regex::new(r#"(?im)charset="(.*?)"|charset=(.*?)""#).unwrap() ; } fn get_default_encoding(byte: &[u8], headers: HeaderMap) -> String { let (html, _, _) = UTF_8.decode(byte); let mut default_encoding = "utf-8"; for charset in RE_COMPILE_BY_CHARSET.captures(&html) { for cs in charset.iter() { if let Some(c) = cs { default_encoding = c.as_str(); } } } let content_type = headers .get(crate::header::CONTENT_TYPE) .and_then(|value| value.to_str().ok()) .and_then(|value| value.parse::<Mime>().ok()); let encoding_name = content_type .as_ref() .and_then(|mime| mime.get_param("charset").map(|charset| charset.as_str())) .unwrap_or(default_encoding); let encoding = Encoding::for_label(encoding_name.as_bytes()).unwrap_or(UTF_8); let (text, _, _) = encoding.decode(byte); text.to_lowercase() } async fn fetch_raw_data(res: Response, is_index: bool) -> Result<Arc<RawData>, WardError> { let path: String = res.url().path().to_string(); let url = res.url().join("/").unwrap(); let status_code = res.status(); let headers = res.headers().clone(); let base_url = res.url().clone(); let text = match res.bytes().await { Ok(byte) => get_default_encoding(&byte, headers.clone()), Err(_) => String::from(""), }; let mut favicon: HashMap<String, String> = HashMap::new(); if is_index && !status_code.is_server_error() { // 只有在首页的时候提取favicon图标链接 favicon = find_favicon_tag(base_url, &text).await; } let lang_set: HashSet<String> = get_lang(&headers); let raw_data = Arc::new(RawData { url, path, headers, status_code, text, favicon, lang_set, }); Ok(raw_data) } // favicon的URL到Hash #[cached( type = "SizedCache<String, String>", create = "{ SizedCache::with_size(100) }", result = true, convert = r#"{ format!("{}", url.as_str().to_owned()) }"# )] async fn get_favicon_hash(url: Url) -> Result<String, WardError> { let default_request = WebFingerPrintRequest { path: "/".to_string(), request_method: "get".to_string(), request_headers: Default::default(), request_data: "".to_string(), }; match send_requests(url, &default_request).await { Ok(res) => { let status_code = res.status(); if !res.status().is_success() { return Err(WardError::Fetch(format!( "Non-200 status code: {}", status_code ))); } let content = res.bytes().await?; let mut hasher = Md5::new(); hasher.update(content); let result = hasher.finalize(); let favicon_md5: String = format!("{:x}", (&result)); Ok(favicon_md5) } Err(err) => { Err(WardError::Fetch(format!("{}", err))) } } } // 从HTML标签中提取favicon的链接 async fn find_favicon_tag( base_url: reqwest::Url, text: &String, ) -> HashMap<String, String> { let parsed_html = Html::parse_fragment(&text); let selector = Selector::parse("link").unwrap(); let mut link_tags = HashMap::new(); let path_list = parsed_html.select(&selector); for link in path_list.into_iter() { if let (Some(href), Some(rel)) = (link.value().attr("href"), link.value().attr("rel")) { if ["icon", "shortcut icon"].contains(&rel) { let favicon_url = base_url.join(href).unwrap(); if let Ok(favicon_md5) = get_favicon_hash(favicon_url.clone()).await { link_tags.insert(String::from(favicon_url.clone()), favicon_md5); }; } } } // 补充默认路径 let favicon_url = base_url.join("/favicon.ico").unwrap(); if !link_tags.contains_key(&String::from(favicon_url.clone())) { if let Ok(favicon_md5) = get_favicon_hash(favicon_url.clone()).await { link_tags.insert(String::from(favicon_url.clone()), favicon_md5); }; } return link_tags; } lazy_static! { static ref RE_COMPILE_BY_JUMP: Vec<Regex> = { let js_reg = vec![r#"[ |.|:]location\.href=['|"](?P<name>.*)['|"]"#, r#"<meta.*?http-equiv=.*?refresh.*?url=(?P<name>.*)['|"]>"#]; let re_list:Vec<Regex> = js_reg.iter().map(|reg|Regex::new(reg).unwrap()).collect(); re_list }; } //首页请求 #[cached( type = "SizedCache<String, Vec<Arc<RawData>>>", create = "{ SizedCache::with_size(100) }", result = true, convert = r#"{ format!("{}{:?}", url_str.to_owned(), special_wfp) }"# )] async fn index_fetch( url_str: &String, special_wfp: &WebFingerPrintRequest, is_index: bool, ) -> Result<Vec<Arc<RawData>>, WardError> { let mut is_index = is_index; let mut raw_data_list: Vec<Arc<RawData>> = vec![]; let schemes: [String; 2] = ["https://".to_string(), "http://".to_string()]; for mut scheme in schemes { //最大重定向跳转次数 let mut max_redirect = 5; let mut is_right_scheme: bool = false; let mut scheme_url = url_str.clone(); if !url_str.to_lowercase().starts_with("http://") && !url_str.to_lowercase().starts_with("https://") { scheme.push_str(url_str.as_str()); scheme_url = scheme; } let mut url = match Url::parse(scheme_url.as_str()) { Ok(url) => url, Err(err) => { return Err(WardError::Other(format!("{:?}", err))); } }; let get_next_url = |headers: &HeaderMap, url: &Url, text: &String, is_index: bool| { let mut next_url = headers .get(LOCATION) .and_then(|location| location.to_str().ok()) .and_then(|location| url.join(location).ok()); if next_url.is_none() && is_index { for reg in RE_COMPILE_BY_JUMP.iter() { if let Some(x) = reg.captures(&text) { next_url = Some(url.join(x.name("name").map_or("", |m| m.as_str())).unwrap()); break; } } } return next_url; }; loop { let mut next_url: Option<Url> = Option::None; if let Ok(res) = send_requests(url.clone(), special_wfp).await { if let Ok(raw_data) = fetch_raw_data(res, is_index).await { next_url = get_next_url(&raw_data.headers, &url, &raw_data.text, is_index); raw_data_list.push(raw_data); }; is_right_scheme = true; is_index = false; }; match next_url.clone() { Some(next_jump_url) => { url = next_jump_url; } None => { break; } } max_redirect -= 1; if max_redirect == 0 { break; } } if is_right_scheme { break; } } return Ok(raw_data_list); } #[derive(Debug, Serialize, Deserialize)] pub struct WhatWebResult { pub url: String, pub what_web_name: HashSet<String>, pub priority: u32, pub length: usize, pub title: String, } impl WhatWebResult { pub fn new(url: String) -> Self { Self { url, what_web_name: HashSet::new(), priority: 0, length: 0, title: String::new(), } } } fn get_title(raw_data: &Arc<RawData>) -> String { let parsed_html = Html::parse_fragment(&raw_data.text); let selector = Selector::parse("title").unwrap(); for title in parsed_html.select(&selector).into_iter() { let title: String = title.inner_html().trim().to_string(); return title; } return String::new(); } fn get_lang(headers: &HeaderMap) -> HashSet<String> { let headers = format!("{:?}", headers.clone()); let cookie_to_lang_map: HashMap<&str, &str> = HashMap::from_iter( [("phpsessid", ".php"), ("jsessionid", ".jsp"), ("aspsession", ".asp"), ] ); let mut lang_set: HashSet<String> = HashSet::new(); for (header_flag, lang) in cookie_to_lang_map.into_iter() { if headers.contains(header_flag) { lang_set.insert(lang.to_string()); } } return lang_set; } pub async fn scan(url: String) -> WhatWebResult { let mut what_web_name: HashSet<String> = HashSet::new(); let mut what_web_result: WhatWebResult = WhatWebResult::new(url.clone()); let default_request = WebFingerPrintRequest { path: "/".to_string(), request_method: "get".to_string(), request_headers: Default::default(), request_data: "".to_string(), }; if let Ok(raw_data_list) = index_fetch(&url, &default_request, true).await { //首页请求允许跳转 for raw_data in raw_data_list { let web_name_set = check(&raw_data, &WEB_FINGERPRINT_LIB_DATA.read().unwrap().to_owned(), false).await; for (k, v) in web_name_set { what_web_name.insert(k); what_web_result.priority = v; } what_web_result.url = String::from(raw_data.url.clone()); what_web_result.title = get_title(&raw_data); what_web_result.length = raw_data.text.len(); } }; for special_wfp in WEB_FINGERPRINT_LIB_DATA.read().unwrap().to_owned().special.iter() { if let Ok(raw_data_list) = index_fetch(&url, &special_wfp.request, false).await { for raw_data in raw_data_list { let web_name_set = check(&raw_data, &WEB_FINGERPRINT_LIB_DATA.read().unwrap().to_owned(), true).await; for (k, v) in web_name_set { what_web_name.insert(k); what_web_result.priority = v; } } } } if what_web_name.len() > 5 { let count = what_web_name.len(); what_web_name.clear(); what_web_name.insert(format!("Honeypot 蜜罐{}", count)); } what_web_result.what_web_name = what_web_name.clone(); let color_web_name: Vec<String> = what_web_name.iter().map(String::from).collect(); if !what_web_name.is_empty() { println!( "[ {} | {} | {} | {} ]", what_web_result.url, format!("{:?}", color_web_name).red(), what_web_result.length, what_web_result.title ); } else { println!( "[ {} | {:?} | {} | {} ]", what_web_result.url, color_web_name, what_web_result.length, what_web_result.title ); } what_web_result } // 去重 pub fn strings_to_urls(domains: String) -> HashSet<String> { let target_list: Vec<String> = domains .split_terminator('\n') .map(|s| s.to_string()) .collect(); HashSet::from_iter(target_list) } pub fn read_file_to_target(file_path: String) -> HashSet<String> { if let Ok(lines) = read_lines(file_path) { let target_list: Vec<String> = lines.filter_map(Result::ok).collect(); return HashSet::from_iter(target_list); } return HashSet::from_iter([]); } fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>, { let file = File::open(filename)?; Ok(io::BufReader::new(file).lines()) } pub async fn download_fingerprints_from_github() { let update_url = "https://0x727.github.io/FingerprintHub/web_fingerprint_v3.json"; match reqwest::get(update_url).await { Ok(response) => { let self_path: PathBuf = env::current_exe().unwrap_or(PathBuf::new()); let path = Path::new(&self_path).parent().unwrap_or(Path::new("")); let mut file = std::fs::File::create(path.join("web_fingerprint_v3.json")).unwrap(); let mut content = Cursor::new(response.bytes().await.unwrap()); std::io::copy(&mut content, &mut file).unwrap(); println!( "Complete fingerprint update: web_fingerprint_v3.json file size => {:?}", file.metadata().unwrap().len() ); } Err(_) => { println!( "Update failed, please download {} to local directory manually.", update_url ); } }; }
mod game; mod game_question; mod question; mod round; mod user; mod user_question; pub use self::game::*; pub use self::game_question::*; pub use self::question::*; pub use self::round::*; pub use self::user::*; pub use self::user_question::*;
//! Memory tracked parquet writer use std::{fmt::Debug, io::Write, sync::Arc}; use arrow::{datatypes::SchemaRef, record_batch::RecordBatch}; use datafusion::{ error::DataFusionError, execution::memory_pool::{MemoryConsumer, MemoryPool, MemoryReservation}, }; use observability_deps::tracing::warn; use parquet::{arrow::ArrowWriter, errors::ParquetError, file::properties::WriterProperties}; use thiserror::Error; /// Errors related to [`TrackedMemoryArrowWriter`] #[derive(Debug, Error)] pub enum Error { /// Writing the parquet file failed with the specified error. #[error("failed to write parquet file: {0}")] Writer(#[from] ParquetError), /// Could not allocate sufficient memory #[error("failed to allocate buffer while writing parquet: {0}")] OutOfMemory(#[from] DataFusionError), } /// Results! pub type Result<T, E = Error> = std::result::Result<T, E>; /// Wraps an [`ArrowWriter`] to track its buffered memory in a /// DataFusion [`MemoryPool`] /// /// If the memory used by the `ArrowWriter` exceeds the memory allowed /// by the `MemoryPool`, subsequent writes will fail. /// /// Note no attempt is made to cap the memory used by the /// `ArrowWriter` (for example by flushing earlier), which might be a /// useful exercise. #[derive(Debug)] pub struct TrackedMemoryArrowWriter<W: Write + Send> { /// The inner ArrowWriter inner: ArrowWriter<W>, /// DataFusion memory reservation with reservation: MemoryReservation, } impl<W: Write + Send> TrackedMemoryArrowWriter<W> { /// create a new `TrackedMemoryArrowWriter<` pub fn try_new( sink: W, schema: SchemaRef, props: WriterProperties, pool: Arc<dyn MemoryPool>, ) -> Result<Self> { let inner = ArrowWriter::try_new(sink, schema, Some(props))?; let consumer = MemoryConsumer::new("IOx ParquetWriter (TrackedMemoryArrowWriter)"); let reservation = consumer.register(&pool); Ok(Self { inner, reservation }) } /// Push a `RecordBatch` into the underlying writer, updating the /// tracked allocation pub fn write(&mut self, batch: RecordBatch) -> Result<()> { // writer encodes the batch into its internal buffers let result = self.inner.write(&batch); // In progress memory, in bytes let in_progress_size = self.inner.in_progress_size(); // update the allocation with the pool. let reservation_result = self .reservation .try_resize(in_progress_size) .map_err(Error::OutOfMemory); // Log any errors if let Err(e) = &reservation_result { warn!( %e, in_progress_size, in_progress_rows = self.inner.in_progress_rows(), existing_allocation = self.reservation.size(), "Could not allocate sufficient buffer memory for writing parquet data" ); } reservation_result?; result?; Ok(()) } /// closes the writer, flushing any remaining data and returning /// the written [`FileMetaData`] /// /// [`FileMetaData`]: parquet::format::FileMetaData pub fn close(self) -> Result<parquet::format::FileMetaData> { // reservation is returned on drop Ok(self.inner.close()?) } } #[cfg(test)] mod test { use super::*; use arrow::array::{ArrayRef, StringArray}; use datafusion::{common::assert_contains, execution::memory_pool::GreedyMemoryPool}; use rand::{distributions::Standard, rngs::StdRng, Rng, SeedableRng}; /// Number of rows to trigger writer flush const TEST_MAX_ROW_GROUP_SIZE: usize = 100; /// Ensure the writer can successfully write when configured with /// a sufficiently sized pool #[tokio::test] async fn test_pool_allocation() { test_helpers::maybe_start_logging(); let props = WriterProperties::builder() .set_max_row_group_size(TEST_MAX_ROW_GROUP_SIZE) .set_data_page_size_limit(10) // ensure each batch is written as a page .build(); let mut data_gen = DataGenerator::new(); let pool_size = 10000; let pool = memory_pool(pool_size); let mut writer = TrackedMemoryArrowWriter::try_new(vec![], data_gen.schema(), props, Arc::clone(&pool)) .unwrap(); // first batch exceeds page limit, so wrote to a page writer.write(data_gen.batch(10)).unwrap(); assert!(writer.reservation.size() > 0); assert_eq!(writer.reservation.size(), writer.inner.in_progress_size()); let previous_reservation = writer.reservation.size(); // Feed in more data to force more data to be written writer.write(data_gen.batch(20)).unwrap(); assert!( writer.reservation.size() > previous_reservation, "reservation_size: {} > {previous_reservation}", writer.reservation.size() ); // Feed in 50 more batches of 5 rows each, and expect that the reservation // continues to match (may not grow as pages are flushed) for _ in 0..50 { writer.write(data_gen.batch(5)).unwrap(); assert_eq!(writer.reservation.size(), writer.inner.in_progress_size()) } println!("Final reservation is {}", pool.reserved()); assert_ne!(pool.reserved(), 0); assert_eq!(pool.reserved(), writer.inner.in_progress_size()); // drop the writer and verify the memory is returned to the pool std::mem::drop(writer); assert_eq!(pool.reserved(), 0); } /// Ensure the writer errors if it needs to buffer more data than /// allowed by pool #[tokio::test] async fn test_pool_memory_pressure() { test_helpers::maybe_start_logging(); let props = WriterProperties::builder() .set_max_row_group_size(TEST_MAX_ROW_GROUP_SIZE) .set_data_page_size_limit(10) // ensure each batch is written as a page .build(); let mut data_gen = DataGenerator::new(); let pool_size = 1000; let pool = memory_pool(pool_size); let mut writer = TrackedMemoryArrowWriter::try_new(vec![], data_gen.schema(), props, Arc::clone(&pool)) .unwrap(); for _ in 0..100 { match writer.write(data_gen.batch(10)) { Err(Error::OutOfMemory(e)) => { println!("Test errored as expected: {e}"); assert_contains!( e.to_string(), "IOx ParquetWriter (TrackedMemoryArrowWriter)" ); return; } Err(e) => { panic!("Unexpected error. Expected OOM, got: {e}"); } Ok(_) => {} } } panic!("Writer did not error when pool limit exceeded"); } /// Ensure the writer can successfully write even after an error #[tokio::test] async fn test_allocation_after_error() { test_helpers::maybe_start_logging(); let props = WriterProperties::builder() .set_max_row_group_size(TEST_MAX_ROW_GROUP_SIZE) .set_data_page_size_limit(10) // ensure each batch is written as a page .build(); let mut data_gen = DataGenerator::new(); let pool_size = 10000; let pool = memory_pool(pool_size); let mut writer = TrackedMemoryArrowWriter::try_new(vec![], data_gen.schema(), props, Arc::clone(&pool)) .unwrap(); writer.write(data_gen.batch(10)).unwrap(); assert_ne!(writer.reservation.size(), 0); assert_eq!(writer.reservation.size(), writer.inner.in_progress_size()); // write a bad batch and accounting should still add up writer.write(data_gen.bad_batch(3)).unwrap(); assert_eq!(writer.reservation.size(), writer.inner.in_progress_size()); // feed more good batches and allocation should still match for _ in 0..15 { writer.write(data_gen.batch(13)).unwrap(); assert_ne!(writer.reservation.size(), 0); assert_eq!(writer.reservation.size(), writer.inner.in_progress_size()); } } /// Creates arrays of psuedo random 16 digit strings. Since /// parquet is excellent at compression, psudo random strings are /// required to make page flusing work in reasonable ways. struct DataGenerator { rng: StdRng, } impl DataGenerator { fn new() -> Self { let seed = 42; Self { rng: SeedableRng::seed_from_u64(seed), } } /// Returns a batch with the specified number of random strings fn batch(&mut self, count: usize) -> RecordBatch { RecordBatch::try_from_iter([("a", self.string_array(count))]).unwrap() } /// Returns a batch with a different scheam fn bad_batch(&mut self, count: usize) -> RecordBatch { RecordBatch::try_from_iter([("b", self.string_array(count))]).unwrap() } /// Makes a string array with `count` entries of data with /// different values (parquet is super efficient at encoding the /// same value) fn string_array(&mut self, count: usize) -> ArrayRef { let array: StringArray = (0..count).map(|_| Some(self.rand_string())).collect(); Arc::new(array) } /// Return the schema of the generated batches fn schema(&mut self) -> SchemaRef { self.batch(1).schema() } /// Make random 16 digit string fn rand_string(&mut self) -> String { // sample_iter consumes the random generator so use // self.rng to seed one let seed: u64 = self.rng.gen_range(0..u64::MAX); let rng: StdRng = SeedableRng::seed_from_u64(seed); rng.sample_iter(&Standard) .filter_map(|c: u8| { if c.is_ascii_digit() { Some(char::from(c)) } else { // discard if out of range None } }) .take(16) .collect() } } /// make a MemoryPool with the specified max size fn memory_pool(max_size: usize) -> Arc<dyn MemoryPool> { Arc::new(GreedyMemoryPool::new(max_size)) } }
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::any::Any; use std::fmt::Debug; use std::fmt::Formatter; use std::sync::Arc; use common_arrow::arrow::chunk::Chunk; use common_arrow::arrow::io::flight::default_ipc_fields; use common_arrow::arrow::io::flight::serialize_batch; use common_arrow::arrow::io::flight::WriteOptions; use common_arrow::arrow::io::ipc::IpcField; use common_exception::ErrorCode; use common_exception::Result; use common_expression::BlockMetaInfo; use common_expression::BlockMetaInfoDowncast; use common_expression::BlockMetaInfoPtr; use common_expression::DataBlock; use common_io::prelude::BinaryWrite; use common_pipeline_core::processors::port::InputPort; use common_pipeline_core::processors::port::OutputPort; use common_pipeline_core::processors::processor::ProcessorPtr; use common_pipeline_transforms::processors::transforms::Transform; use common_pipeline_transforms::processors::transforms::Transformer; use serde::Deserializer; use serde::Serializer; use crate::api::rpc::exchange::exchange_params::MergeExchangeParams; use crate::api::rpc::exchange::exchange_params::ShuffleExchangeParams; use crate::api::rpc::exchange::exchange_transform_shuffle::ExchangeShuffleMeta; use crate::api::DataPacket; use crate::api::ExchangeSorting; use crate::api::FragmentData; pub struct ExchangeSerializeMeta { pub block_number: isize, pub packet: Option<DataPacket>, } impl ExchangeSerializeMeta { pub fn create(block_number: isize, packet: Option<DataPacket>) -> BlockMetaInfoPtr { Box::new(ExchangeSerializeMeta { packet, block_number, }) } } impl Debug for ExchangeSerializeMeta { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { f.debug_struct("ExchangeSerializeMeta").finish() } } impl serde::Serialize for ExchangeSerializeMeta { fn serialize<S>(&self, _: S) -> Result<S::Ok, S::Error> where S: Serializer { unimplemented!("Unimplemented serialize ExchangeSerializeMeta") } } impl<'de> serde::Deserialize<'de> for ExchangeSerializeMeta { fn deserialize<D>(_: D) -> Result<Self, D::Error> where D: Deserializer<'de> { unimplemented!("Unimplemented deserialize ExchangeSerializeMeta") } } #[typetag::serde(name = "exchange_serialize")] impl BlockMetaInfo for ExchangeSerializeMeta { fn as_any(&self) -> &dyn Any { self } fn equals(&self, _: &Box<dyn BlockMetaInfo>) -> bool { unimplemented!("Unimplemented equals ExchangeSerializeMeta") } fn clone_self(&self) -> Box<dyn BlockMetaInfo> { unimplemented!("Unimplemented clone ExchangeSerializeMeta") } } pub struct TransformExchangeSerializer { options: WriteOptions, ipc_fields: Vec<IpcField>, sorting: Option<Arc<dyn ExchangeSorting>>, } impl TransformExchangeSerializer { pub fn create( input: Arc<InputPort>, output: Arc<OutputPort>, params: &MergeExchangeParams, sorting: Option<Arc<dyn ExchangeSorting>>, ) -> Result<ProcessorPtr> { let arrow_schema = params.schema.to_arrow(); let ipc_fields = default_ipc_fields(&arrow_schema.fields); Ok(ProcessorPtr::create(Transformer::create( input, output, TransformExchangeSerializer { sorting, ipc_fields, options: WriteOptions { compression: None }, }, ))) } } impl Transform for TransformExchangeSerializer { const NAME: &'static str = "ExchangeSerializerTransform"; fn transform(&mut self, data_block: DataBlock) -> Result<DataBlock> { let mut block_num = 0; if let Some(sorting) = &self.sorting { block_num = sorting.block_number(&data_block)?; } serialize_block(block_num, data_block, &self.ipc_fields, &self.options) } } pub struct TransformScatterExchangeSerializer { local_pos: usize, options: WriteOptions, ipc_fields: Vec<IpcField>, sorting: Option<Arc<dyn ExchangeSorting>>, } impl TransformScatterExchangeSerializer { pub fn create( input: Arc<InputPort>, output: Arc<OutputPort>, params: &ShuffleExchangeParams, sorting: Option<Arc<dyn ExchangeSorting>>, ) -> Result<ProcessorPtr> { let local_id = &params.executor_id; let arrow_schema = params.schema.to_arrow(); let ipc_fields = default_ipc_fields(&arrow_schema.fields); Ok(ProcessorPtr::create(Transformer::create( input, output, TransformScatterExchangeSerializer { sorting, ipc_fields, options: WriteOptions { compression: None }, local_pos: params .destination_ids .iter() .position(|x| x == local_id) .unwrap(), }, ))) } } impl Transform for TransformScatterExchangeSerializer { const NAME: &'static str = "TransformScatterExchangeSerializer"; fn transform(&mut self, mut data_block: DataBlock) -> Result<DataBlock> { if let Some(block_meta) = data_block.take_meta() { if let Some(shuffle_meta) = ExchangeShuffleMeta::downcast_from(block_meta) { let mut new_blocks = Vec::with_capacity(shuffle_meta.blocks.len()); for (index, block) in shuffle_meta.blocks.into_iter().enumerate() { if block.is_empty() { new_blocks.push(block); continue; } new_blocks.push(match self.local_pos == index { true => block, false => match &self.sorting { None => serialize_block(0, block, &self.ipc_fields, &self.options)?, Some(sorting) => serialize_block( sorting.block_number(&data_block)?, block, &self.ipc_fields, &self.options, )?, }, }); } return Ok(DataBlock::empty_with_meta(ExchangeShuffleMeta::create( new_blocks, ))); } } Err(ErrorCode::Internal( "Internal, TransformScatterExchangeSerializer only recv ExchangeShuffleMeta.", )) } } pub fn serialize_block( block_num: isize, data_block: DataBlock, ipc_field: &[IpcField], options: &WriteOptions, ) -> Result<DataBlock> { if data_block.is_empty() && data_block.get_meta().is_none() { return Ok(DataBlock::empty_with_meta(ExchangeSerializeMeta::create( block_num, None, ))); } let mut meta = vec![]; meta.write_scalar_own(data_block.num_rows() as u32)?; bincode::serialize_into(&mut meta, &data_block.get_meta()) .map_err(|_| ErrorCode::BadBytes("block meta serialize error when exchange"))?; let values = match data_block.is_empty() { true => serialize_batch(&Chunk::new(vec![]), &[], options)?.1, false => { let chunks = data_block.try_into()?; let (dicts, values) = serialize_batch(&chunks, ipc_field, options)?; if !dicts.is_empty() { return Err(ErrorCode::Unimplemented( "DatabendQuery does not implement dicts.", )); } values } }; Ok(DataBlock::empty_with_meta(ExchangeSerializeMeta::create( block_num, Some(DataPacket::FragmentData(FragmentData::create(meta, values))), ))) }
#[path = "integer_to_list_1/with_integer.rs"] pub mod with_integer; // `without_integer_errors_badarg` in unit tests
// Copyright 2023 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::fmt::Debug; use std::fmt::Formatter; use std::sync::Arc; use common_expression::TableSchema; use common_expression::TableSchemaRef; use common_meta_app::principal::StageInfo; use common_storage::StageFileInfo; use common_storage::StageFilesInfo; #[derive(serde::Serialize, serde::Deserialize, Clone, PartialEq, Eq)] pub struct StageTableInfo { pub schema: TableSchemaRef, pub files_info: StageFilesInfo, pub stage_info: StageInfo, pub files_to_copy: Option<Vec<StageFileInfo>>, } impl StageTableInfo { pub fn schema(&self) -> Arc<TableSchema> { self.schema.clone() } pub fn desc(&self) -> String { self.stage_info.stage_name.clone() } } impl Debug for StageTableInfo { // Ignore the schema. fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{:?}", self.stage_info) } }
use game_lib::rand::Rng; use std::{f32::consts::TAU, ops::RangeInclusive}; #[derive(Clone, Copy, PartialEq, Debug)] pub struct Wave { amplitude: f32, wavelength: f32, phase: f32, } #[derive(Clone, PartialEq, Debug)] pub struct Waves(Vec<Wave>); #[derive(Clone, PartialEq, Debug)] pub struct WavesConfig { pub waves: RangeInclusive<usize>, pub amplitude: RangeInclusive<f32>, pub wavelength: RangeInclusive<f32>, pub phase: RangeInclusive<f32>, } impl Waves { pub fn new() -> Self { Vec::new().into() } pub fn new_rand<R: Rng>(rand: &mut R, config: WavesConfig) -> Self { let WavesConfig { waves, amplitude, wavelength, phase, } = config; waves .map(|_| Wave { amplitude: rand.gen_range(amplitude.clone()), wavelength: rand.gen_range(wavelength.clone()), phase: rand.gen_range(phase.clone()), }) .collect::<Vec<_>>() .into() } pub fn get(&self, x: f32) -> f32 { self.0.iter().fold(0.0, |acc, wave| { let Wave { amplitude, wavelength, phase, } = wave; let x = x as f32; let offset = amplitude * f32::sin(TAU / wavelength * x + phase); acc + offset }) } } impl From<Vec<Wave>> for Waves { fn from(value: Vec<Wave>) -> Self { Waves(value) } }
use serde::{de, Deserialize, Deserializer}; use std::str::FromStr; pub(crate) fn opt_bool_de_from_str<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error> where D: Deserializer<'de>, { let s = String::deserialize(deserializer)?.to_ascii_lowercase(); let value = (bool::from_str(&s).map_err(de::Error::custom))?; Ok(Some(value)) }
/* 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 1/8, 1/7, 1/6, 1/5, 2/8, 2/7, 2/6, 3/8, 2/5, 3/7, 4/8, 4/7, 3/5, 5/8, 4/6, 5/7, 6/8, 4/5, 5/6, 6/7, 7/8 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 1,5,8,11,14,17,21 x/8 und x/6 teilen sich genau einen bruch, 8 und 6 haben auch genau einen gemeinsamen primfaktor. Zufall? Ich denke nicht :P */ /* wie viele brüche teilen sich x/8 und x/12? 8 = 2*2*2 12 = 2*2*3 1,2,3,4,5,6,7 / 8 1/12,1/6,1/4,1/3,5/12,1/2,7/12,2/6,3/4,5/6,11/12 */ use projecteuler::helper; use projecteuler::primes; fn main() { dbg!(solve(8)); helper::time_it( || { solve(1_000_000); }, 100, ); } fn solve(d: usize) -> usize { primes::euler_phi_list(d + 1).iter().skip(2).sum() }
#[doc = "Reader of register HB16TIME3"] pub type R = crate::R<u32, super::HB16TIME3>; #[doc = "Writer for register HB16TIME3"] pub type W = crate::W<u32, super::HB16TIME3>; #[doc = "Register HB16TIME3 `reset()`'s with value 0"] impl crate::ResetValue for super::HB16TIME3 { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `RDWSM`"] pub type RDWSM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RDWSM`"] pub struct RDWSM_W<'a> { w: &'a mut W, } impl<'a> RDWSM_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 `WRWSM`"] pub type WRWSM_R = crate::R<bool, bool>; #[doc = "Write proxy for field `WRWSM`"] pub struct WRWSM_W<'a> { w: &'a mut W, } impl<'a> WRWSM_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 `CAPWIDTH`"] pub type CAPWIDTH_R = crate::R<u8, u8>; #[doc = "Write proxy for field `CAPWIDTH`"] pub struct CAPWIDTH_W<'a> { w: &'a mut W, } impl<'a> CAPWIDTH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 12)) | (((value as u32) & 0x03) << 12); self.w } } #[doc = "PSRAM Row Size\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum PSRAMSZ_A { #[doc = "0: No row size limitation"] _0 = 0, #[doc = "1: 128 B"] _128B = 1, #[doc = "2: 256 B"] _256B = 2, #[doc = "3: 512 B"] _512B = 3, #[doc = "4: 1024 B"] _1KB = 4, #[doc = "5: 2048 B"] _2KB = 5, #[doc = "6: 4096 B"] _4KB = 6, #[doc = "7: 8192 B"] _8KB = 7, } impl From<PSRAMSZ_A> for u8 { #[inline(always)] fn from(variant: PSRAMSZ_A) -> Self { variant as _ } } #[doc = "Reader of field `PSRAMSZ`"] pub type PSRAMSZ_R = crate::R<u8, PSRAMSZ_A>; impl PSRAMSZ_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> PSRAMSZ_A { match self.bits { 0 => PSRAMSZ_A::_0, 1 => PSRAMSZ_A::_128B, 2 => PSRAMSZ_A::_256B, 3 => PSRAMSZ_A::_512B, 4 => PSRAMSZ_A::_1KB, 5 => PSRAMSZ_A::_2KB, 6 => PSRAMSZ_A::_4KB, 7 => PSRAMSZ_A::_8KB, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `_0`"] #[inline(always)] pub fn is_0(&self) -> bool { *self == PSRAMSZ_A::_0 } #[doc = "Checks if the value of the field is `_128B`"] #[inline(always)] pub fn is_128b(&self) -> bool { *self == PSRAMSZ_A::_128B } #[doc = "Checks if the value of the field is `_256B`"] #[inline(always)] pub fn is_256b(&self) -> bool { *self == PSRAMSZ_A::_256B } #[doc = "Checks if the value of the field is `_512B`"] #[inline(always)] pub fn is_512b(&self) -> bool { *self == PSRAMSZ_A::_512B } #[doc = "Checks if the value of the field is `_1KB`"] #[inline(always)] pub fn is_1kb(&self) -> bool { *self == PSRAMSZ_A::_1KB } #[doc = "Checks if the value of the field is `_2KB`"] #[inline(always)] pub fn is_2kb(&self) -> bool { *self == PSRAMSZ_A::_2KB } #[doc = "Checks if the value of the field is `_4KB`"] #[inline(always)] pub fn is_4kb(&self) -> bool { *self == PSRAMSZ_A::_4KB } #[doc = "Checks if the value of the field is `_8KB`"] #[inline(always)] pub fn is_8kb(&self) -> bool { *self == PSRAMSZ_A::_8KB } } #[doc = "Write proxy for field `PSRAMSZ`"] pub struct PSRAMSZ_W<'a> { w: &'a mut W, } impl<'a> PSRAMSZ_W<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: PSRAMSZ_A) -> &'a mut W { { self.bits(variant.into()) } } #[doc = "No row size limitation"] #[inline(always)] pub fn _0(self) -> &'a mut W { self.variant(PSRAMSZ_A::_0) } #[doc = "128 B"] #[inline(always)] pub fn _128b(self) -> &'a mut W { self.variant(PSRAMSZ_A::_128B) } #[doc = "256 B"] #[inline(always)] pub fn _256b(self) -> &'a mut W { self.variant(PSRAMSZ_A::_256B) } #[doc = "512 B"] #[inline(always)] pub fn _512b(self) -> &'a mut W { self.variant(PSRAMSZ_A::_512B) } #[doc = "1024 B"] #[inline(always)] pub fn _1kb(self) -> &'a mut W { self.variant(PSRAMSZ_A::_1KB) } #[doc = "2048 B"] #[inline(always)] pub fn _2kb(self) -> &'a mut W { self.variant(PSRAMSZ_A::_2KB) } #[doc = "4096 B"] #[inline(always)] pub fn _4kb(self) -> &'a mut W { self.variant(PSRAMSZ_A::_4KB) } #[doc = "8192 B"] #[inline(always)] pub fn _8kb(self) -> &'a mut W { self.variant(PSRAMSZ_A::_8KB) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x07 << 16)) | (((value as u32) & 0x07) << 16); self.w } } #[doc = "Reader of field `IRDYDLY`"] pub type IRDYDLY_R = crate::R<u8, u8>; #[doc = "Write proxy for field `IRDYDLY`"] pub struct IRDYDLY_W<'a> { w: &'a mut W, } impl<'a> IRDYDLY_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x03 << 24)) | (((value as u32) & 0x03) << 24); self.w } } impl R { #[doc = "Bit 0 - CS2n Read Wait State Minus One"] #[inline(always)] pub fn rdwsm(&self) -> RDWSM_R { RDWSM_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 4 - CS2n Write Wait State Minus One"] #[inline(always)] pub fn wrwsm(&self) -> WRWSM_R { WRWSM_R::new(((self.bits >> 4) & 0x01) != 0) } #[doc = "Bits 12:13 - CS2n Inter-transfer Capture Width"] #[inline(always)] pub fn capwidth(&self) -> CAPWIDTH_R { CAPWIDTH_R::new(((self.bits >> 12) & 0x03) as u8) } #[doc = "Bits 16:18 - PSRAM Row Size"] #[inline(always)] pub fn psramsz(&self) -> PSRAMSZ_R { PSRAMSZ_R::new(((self.bits >> 16) & 0x07) as u8) } #[doc = "Bits 24:25 - CS2n Input Ready Delay"] #[inline(always)] pub fn irdydly(&self) -> IRDYDLY_R { IRDYDLY_R::new(((self.bits >> 24) & 0x03) as u8) } } impl W { #[doc = "Bit 0 - CS2n Read Wait State Minus One"] #[inline(always)] pub fn rdwsm(&mut self) -> RDWSM_W { RDWSM_W { w: self } } #[doc = "Bit 4 - CS2n Write Wait State Minus One"] #[inline(always)] pub fn wrwsm(&mut self) -> WRWSM_W { WRWSM_W { w: self } } #[doc = "Bits 12:13 - CS2n Inter-transfer Capture Width"] #[inline(always)] pub fn capwidth(&mut self) -> CAPWIDTH_W { CAPWIDTH_W { w: self } } #[doc = "Bits 16:18 - PSRAM Row Size"] #[inline(always)] pub fn psramsz(&mut self) -> PSRAMSZ_W { PSRAMSZ_W { w: self } } #[doc = "Bits 24:25 - CS2n Input Ready Delay"] #[inline(always)] pub fn irdydly(&mut self) -> IRDYDLY_W { IRDYDLY_W { w: self } } }
use super::*; use proptest::strategy::Strategy; #[test] fn with_number_atom_reference_function_port_pid_tuple_map_or_list_second_returns_second() { run!( |arc_process| { ( strategy::term::binary::heap(arc_process.clone()), strategy::term(arc_process.clone()).prop_filter( "Second must be number, atom, reference, function, port, pid, tuple, map, or list", |second| { second.is_number() || second.is_atom() || second.is_reference() || second.is_boxed_function() || second.is_port() || second.is_pid() || second.is_boxed_tuple() || second.is_list() }), ) }, |(first, second)| { prop_assert_eq!(result(first, second), second); Ok(()) }, ); } #[test] fn with_prefix_heap_binary_second_returns_second() { min(|_, process| process.binary_from_bytes(&[1]), Second); } #[test] fn with_same_length_heap_binary_with_lesser_byte_second_returns_second() { min(|_, process| process.binary_from_bytes(&[0]), Second); } #[test] fn with_longer_heap_binary_with_lesser_byte_second_returns_second() { min(|_, process| process.binary_from_bytes(&[0, 1, 2]), Second); } #[test] fn with_same_value_heap_binary_second_returns_first() { super::min( |process| { let original = process.binary_from_bytes(&[1]); process.subbinary_from_original(original, 0, 0, 1, 0) }, |_, process| process.binary_from_bytes(&[1]), First, ) } #[test] fn with_shorter_heap_binary_with_greater_byte_second_returns_first() { min(|_, process| process.binary_from_bytes(&[2]), First); } #[test] fn with_heap_binary_with_greater_byte_second_returns_first() { min(|_, process| process.binary_from_bytes(&[2, 1]), First); } #[test] fn with_heap_binary_with_greater_byte_than_bits_second_returns_first() { min( |_, process| process.binary_from_bytes(&[1, 0b1000_0000]), First, ); } #[test] fn with_prefix_subbinary_second_returns_second() { min( |_, process| { let original = process.binary_from_bytes(&[1]); process.subbinary_from_original(original, 0, 0, 1, 0) }, Second, ); } #[test] fn with_same_length_subbinary_with_lesser_byte_second_returns_second() { min( |_, process| { let original = process.binary_from_bytes(&[0, 1]); process.subbinary_from_original(original, 0, 0, 2, 0) }, Second, ); } #[test] fn with_longer_subbinary_with_lesser_byte_second_returns_second() { min(|_, process| bitstring!(0, 1, 0b10 :: 2, &process), Second); } #[test] fn with_same_subbinary_second_returns_first() { min(|first, _| first, First); } #[test] fn with_same_value_subbinary_second_returns_first() { min(|_, process| bitstring!(1, 1 :: 2, &process), First); } #[test] fn with_shorter_subbinary_with_greater_byte_second_returns_first() { min( |_, process| { let original = process.binary_from_bytes(&[2]); process.subbinary_from_original(original, 0, 0, 1, 0) }, First, ); } #[test] fn with_subbinary_with_greater_byte_second_returns_first() { min( |_, process| { let original = process.binary_from_bytes(&[2, 1]); process.subbinary_from_original(original, 0, 0, 2, 0) }, First, ); } #[test] fn with_subbinary_with_different_greater_byte_second_returns_first() { min( |_, process| { let original = process.binary_from_bytes(&[1, 2]); process.subbinary_from_original(original, 0, 0, 2, 0) }, First, ); } #[test] fn with_subbinary_with_value_with_shorter_length_returns_first() { min(|_, process| bitstring!(1, 1 :: 1, &process), First) } fn min<R>(second: R, which: FirstSecond) where R: FnOnce(Term, &Process) -> Term, { super::min(|process| bitstring!(1, 1 :: 2, &process), second, which); }
#[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::LOCK { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = "Possible values of the field `WDT_LOCK`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum WDT_LOCKR { #[doc = "Unlocked"] WDT_LOCK_UNLOCKED, #[doc = "Locked"] WDT_LOCK_LOCKED, #[doc = r"Reserved"] _Reserved(u32), } impl WDT_LOCKR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { match *self { WDT_LOCKR::WDT_LOCK_UNLOCKED => 0, WDT_LOCKR::WDT_LOCK_LOCKED => 1, WDT_LOCKR::_Reserved(bits) => bits, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u32) -> WDT_LOCKR { match value { 0 => WDT_LOCKR::WDT_LOCK_UNLOCKED, 1 => WDT_LOCKR::WDT_LOCK_LOCKED, i => WDT_LOCKR::_Reserved(i), } } #[doc = "Checks if the value of the field is `WDT_LOCK_UNLOCKED`"] #[inline(always)] pub fn is_wdt_lock_unlocked(&self) -> bool { *self == WDT_LOCKR::WDT_LOCK_UNLOCKED } #[doc = "Checks if the value of the field is `WDT_LOCK_LOCKED`"] #[inline(always)] pub fn is_wdt_lock_locked(&self) -> bool { *self == WDT_LOCKR::WDT_LOCK_LOCKED } } #[doc = "Values that can be written to the field `WDT_LOCK`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum WDT_LOCKW { #[doc = "Unlocked"] WDT_LOCK_UNLOCKED, #[doc = "Locked"] WDT_LOCK_LOCKED, } impl WDT_LOCKW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u32 { match *self { WDT_LOCKW::WDT_LOCK_UNLOCKED => 0, WDT_LOCKW::WDT_LOCK_LOCKED => 1, } } } #[doc = r"Proxy"] pub struct _WDT_LOCKW<'a> { w: &'a mut W, } impl<'a> _WDT_LOCKW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: WDT_LOCKW) -> &'a mut W { unsafe { self.bits(variant._bits()) } } #[doc = "Unlocked"] #[inline(always)] pub fn wdt_lock_unlocked(self) -> &'a mut W { self.variant(WDT_LOCKW::WDT_LOCK_UNLOCKED) } #[doc = "Locked"] #[inline(always)] pub fn wdt_lock_locked(self) -> &'a mut W { self.variant(WDT_LOCKW::WDT_LOCK_LOCKED) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u32) -> &'a mut W { self.w.bits &= !(4294967295 << 0); self.w.bits |= ((value as u32) & 4294967295) << 0; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bits 0:31 - Watchdog Lock"] #[inline(always)] pub fn wdt_lock(&self) -> WDT_LOCKR { WDT_LOCKR::_from(((self.bits >> 0) & 4294967295) as u32) } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bits 0:31 - Watchdog Lock"] #[inline(always)] pub fn wdt_lock(&mut self) -> _WDT_LOCKW { _WDT_LOCKW { w: self } } }
use datafrog; use datafrog::Iteration; use std::collections::HashMap; #[cfg(test)] mod test; type Row = usize; type Col = usize; type Label = usize; /// A board cell #[derive(Copy, Clone, Debug, Ord, PartialOrd, PartialEq, Eq)] enum Square { /// Covered cell Empty, /// Mine cell Mine, /// Mine-free cell Safe, /// Move to check Probe, /// Cell labeled with number of mines around Number(Label), } impl Square { fn from(s: &str) -> Square { match s { "_" => Square::Empty, "*" => Square::Mine, "s" => Square::Safe, "?" => Square::Probe, _ => match s.parse::<Label>() { Ok(num) if num <= 8 => Square::Number(num), Ok(_) => panic!("Invalid number of mines: {}", s), Err(_) => panic!("Invalid square label: {}", s), }, } } } pub struct Configuration { board: Vec<Vec<Square>>, } impl Configuration { pub fn from(raw_conf: String) -> Configuration { let board: Vec<Vec<_>> = raw_conf .lines() .map(|line| line.split_whitespace().collect::<Vec<_>>()) .map(|row| row.iter().map(|square| Square::from(square)).collect()) .collect(); Configuration { board } } fn is_mine(&self, row: Row, col: Col) -> bool { match self.board[row][col] { Square::Mine => true, _ => false, } } fn is_empty(&self, row: Row, col: Col) -> bool { match self.board[row][col] { Square::Empty => true, Square::Probe => true, _ => false, } } fn neighbours(&self, row: Row, col: Col) -> Vec<(Row, Col)> { let mut result = vec![]; let size = self.board.len(); // Previous row if row > 1 { let prev_row = row - 1; if col > 1 { result.push((prev_row, col - 1)); } result.push((prev_row, col)); if col + 1 < size { result.push((prev_row, col + 1)); } } // This row if col > 1 { result.push((row, col - 1)); } if col + 1 < size { result.push((row, col + 1)); } // Next row let next_row = row + 1; if next_row < size { if col > 1 { result.push((next_row, col - 1)); } result.push((next_row, col)); if col + 1 < size { result.push((next_row, col + 1)); } } result } } #[derive(Eq, PartialEq, Debug)] pub enum ProbeResult { Safe, Unsafe, Unknown, } pub fn check_configuration(conf: Configuration) -> ProbeResult { // `bool` means safety of the square let mut verified: HashMap<(Row, Col), bool> = HashMap::new(); let mut iteration = Iteration::new(); let squares = iteration.variable::<(Row, Col, Square)>("board"); // flatten all cells with their indices let mut enumerated_squares: Vec<(Row, Col, Square)> = vec![]; for (i, row) in conf.board.iter().enumerate() { let row_squares = row.iter().enumerate().map(|(j, square)| (i, j, *square)); enumerated_squares.extend(row_squares); } // find a probe, i.e. a move to check let probe: (Row, Col) = enumerated_squares .iter() .find(|(_, _, square)| match square { Square::Probe => true, _ => false, }) .map(|(i, j, _)| (*i, *j)).expect("No probe provided"); // add all board cells into `squares` squares.extend(enumerated_squares); while iteration.changed() { for (row, col, square) in squares.recent.borrow().elements.clone() { let neighbours = conf.neighbours(row, col); let neighbours_mines: Vec<(Row, Col)> = neighbours .clone() .into_iter() .filter(|(r, c)| conf.is_mine(*r, *c)) .collect(); let neighbours_empty: Vec<(Row, Col)> = neighbours .clone() .into_iter() .filter(|(r, c)| conf.is_empty(*r, *c)) .collect(); if neighbours_empty.is_empty() { continue; } match square { // All empty neighbours are safe if `n == neighbours_mines.len()` Square::Number(n) if n == neighbours_mines.len() => { for (row, col) in neighbours_empty { verified.insert((row, col), true); } } // All empty neighbours are unsafe if `n == neighbours_mines.len() + neighbours_empty.len()` Square::Number(n) if n == neighbours_mines.len() + neighbours_empty.len() => { for (row, col) in neighbours_empty { verified.insert((row, col), false); } } // Uncertain _ => {} } } // Update the board squares.from_map(&squares, |(row, col, square)| { match verified.get(&(*row, *col)) { None => (*row, *col, *square), Some(true) => (*row, *col, Square::Safe), Some(false) => (*row, *col, Square::Mine), } }); } squares.complete(); match verified.get(&probe) { Some(true) => ProbeResult::Safe, Some(false) => ProbeResult::Unsafe, None => ProbeResult::Unknown, } }
#[doc = "Reader of register MISC"] pub type R = crate::R<u32, super::MISC>; #[doc = "Writer for register MISC"] pub type W = crate::W<u32, super::MISC>; #[doc = "Register MISC `reset()`'s with value 0"] impl crate::ResetValue for super::MISC { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `BOR1MIS`"] pub type BOR1MIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BOR1MIS`"] pub struct BOR1MIS_W<'a> { w: &'a mut W, } impl<'a> BOR1MIS_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 `MOFMIS`"] pub type MOFMIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MOFMIS`"] pub struct MOFMIS_W<'a> { w: &'a mut W, } impl<'a> MOFMIS_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 `PLLLMIS`"] pub type PLLLMIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `PLLLMIS`"] pub struct PLLLMIS_W<'a> { w: &'a mut W, } impl<'a> PLLLMIS_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 `USBPLLLMIS`"] pub type USBPLLLMIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USBPLLLMIS`"] pub struct USBPLLLMIS_W<'a> { w: &'a mut W, } impl<'a> USBPLLLMIS_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 `MOSCPUPMIS`"] pub type MOSCPUPMIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `MOSCPUPMIS`"] pub struct MOSCPUPMIS_W<'a> { w: &'a mut W, } impl<'a> MOSCPUPMIS_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 `VDDAMIS`"] pub type VDDAMIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `VDDAMIS`"] pub struct VDDAMIS_W<'a> { w: &'a mut W, } impl<'a> VDDAMIS_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 `BOR0MIS`"] pub type BOR0MIS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `BOR0MIS`"] pub struct BOR0MIS_W<'a> { w: &'a mut W, } impl<'a> BOR0MIS_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 } } impl R { #[doc = "Bit 1 - VDD under BOR1 Masked Interrupt Status"] #[inline(always)] pub fn bor1mis(&self) -> BOR1MIS_R { BOR1MIS_R::new(((self.bits >> 1) & 0x01) != 0) } #[doc = "Bit 3 - Main Oscillator Failure Masked Interrupt Status"] #[inline(always)] pub fn mofmis(&self) -> MOFMIS_R { MOFMIS_R::new(((self.bits >> 3) & 0x01) != 0) } #[doc = "Bit 6 - PLL Lock Masked Interrupt Status"] #[inline(always)] pub fn plllmis(&self) -> PLLLMIS_R { PLLLMIS_R::new(((self.bits >> 6) & 0x01) != 0) } #[doc = "Bit 7 - USB PLL Lock Masked Interrupt Status"] #[inline(always)] pub fn usbplllmis(&self) -> USBPLLLMIS_R { USBPLLLMIS_R::new(((self.bits >> 7) & 0x01) != 0) } #[doc = "Bit 8 - MOSC Power Up Masked Interrupt Status"] #[inline(always)] pub fn moscpupmis(&self) -> MOSCPUPMIS_R { MOSCPUPMIS_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 10 - VDDA Power OK Masked Interrupt Status"] #[inline(always)] pub fn vddamis(&self) -> VDDAMIS_R { VDDAMIS_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - VDD under BOR0 Masked Interrupt Status"] #[inline(always)] pub fn bor0mis(&self) -> BOR0MIS_R { BOR0MIS_R::new(((self.bits >> 11) & 0x01) != 0) } } impl W { #[doc = "Bit 1 - VDD under BOR1 Masked Interrupt Status"] #[inline(always)] pub fn bor1mis(&mut self) -> BOR1MIS_W { BOR1MIS_W { w: self } } #[doc = "Bit 3 - Main Oscillator Failure Masked Interrupt Status"] #[inline(always)] pub fn mofmis(&mut self) -> MOFMIS_W { MOFMIS_W { w: self } } #[doc = "Bit 6 - PLL Lock Masked Interrupt Status"] #[inline(always)] pub fn plllmis(&mut self) -> PLLLMIS_W { PLLLMIS_W { w: self } } #[doc = "Bit 7 - USB PLL Lock Masked Interrupt Status"] #[inline(always)] pub fn usbplllmis(&mut self) -> USBPLLLMIS_W { USBPLLLMIS_W { w: self } } #[doc = "Bit 8 - MOSC Power Up Masked Interrupt Status"] #[inline(always)] pub fn moscpupmis(&mut self) -> MOSCPUPMIS_W { MOSCPUPMIS_W { w: self } } #[doc = "Bit 10 - VDDA Power OK Masked Interrupt Status"] #[inline(always)] pub fn vddamis(&mut self) -> VDDAMIS_W { VDDAMIS_W { w: self } } #[doc = "Bit 11 - VDD under BOR0 Masked Interrupt Status"] #[inline(always)] pub fn bor0mis(&mut self) -> BOR0MIS_W { BOR0MIS_W { w: self } } }
fn trees(lines: &[Vec<bool>], hstride: usize, vstride: usize) -> usize { let width = lines[0].len(); let (mut x, mut y, mut trees) = (0, 0, 0); loop { trees += lines[y][x] as usize; x += hstride; y += vstride; if x >= width { x -= width; } if y >= lines.len() { return trees; } } } fn main() { let lines: Vec<Vec<bool>> = std::fs::read_to_string("input") .unwrap() .lines() .map(|s| s.trim().bytes().map(|c| c == b'#').collect()) .collect(); dbg!(trees(&lines, 3, 1)); let part_2 = [(1, 1), (3, 1), (5, 1), (7, 1), (1, 2)] .iter() .map(|(h, v)| trees(&lines, *h, *v)) .product::<usize>(); dbg!(part_2); }
use std::collections::HashMap; use proconio::input; fn main() { input! { n: usize, a: [u32; n], }; let mut f = HashMap::new(); for x in a { *f.entry(x).or_insert(0) += 1; } let mut ans = 0; for (_, v) in f { ans += v / 2; } println!("{}", ans); }
pub mod payoffs; pub mod products; pub mod parameters; pub mod stats_collectors; pub mod random; #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }
use crate::prelude::*; use std::ffi::CStr; use std::fmt; use std::marker::PhantomData; use std::os::raw::{c_char, c_void}; use std::ptr; use std::slice; #[repr(C)] pub struct VkInstanceCreateInfo<'a> { lt: PhantomData<&'a ()>, pub sType: VkStructureType, pub pNext: *const c_void, pub flags: VkInstanceCreateFlagBits, pub pApplicationInfo: *const VkApplicationInfo<'a>, pub enabledLayerCount: u32, pub ppEnabledLayerNames: *const *const c_char, pub enabledExtensionCount: u32, pub ppEnabledExtensionNames: *const *const c_char, } impl<'a> VkInstanceCreateInfo<'a> { pub fn new<T>( flags: T, application_info: &VkApplicationInfo<'a>, enabled_layer_names: &VkNames, enabled_extension_names: &VkNames, ) -> Self where T: Into<VkInstanceCreateFlagBits>, { VkInstanceCreateInfo { lt: PhantomData, sType: VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO, pNext: ptr::null(), flags: flags.into(), pApplicationInfo: application_info as *const _, enabledLayerCount: enabled_layer_names.c_names().len() as u32, ppEnabledLayerNames: enabled_layer_names.c_names().as_ptr(), enabledExtensionCount: enabled_extension_names.c_names().len() as u32, ppEnabledExtensionNames: enabled_extension_names.c_names().as_ptr(), } } } impl<'a> fmt::Debug for VkInstanceCreateInfo<'a> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut enabled_layers_string = String::from("{{"); let layers_slice: &[*const c_char] = unsafe { slice::from_raw_parts(self.ppEnabledLayerNames, self.enabledLayerCount as usize) }; for layer in layers_slice { let cstr_layer = unsafe { CStr::from_ptr(*layer) }; if let Ok(layer) = cstr_layer.to_str() { enabled_layers_string = format!("{} {},", enabled_layers_string, layer); } } enabled_layers_string = format!("{} }}", enabled_layers_string); let enabled_extensions_string = String::new(); write!( f, "{{ sType: {:?}, pNext: {:?}, flags: {:?}, pApplicationInfo: {:?}, enabledLayers: {}, enabledExtensions: {} }}", self.sType, self.pNext, self.flags, self.pApplicationInfo, enabled_layers_string, enabled_extensions_string ) } }
use std::marker::PhantomData; use futures::{Async, Future, Poll}; use super::{NewService, Service}; /// Service for the `map_err` combinator, changing the type of a service's /// error. /// /// This is created by the `ServiceExt::map_err` method. pub struct MapErr<A, F, E> { service: A, f: F, _t: PhantomData<E>, } impl<A, F, E> MapErr<A, F, E> { /// Create new `MapErr` combinator pub fn new(service: A, f: F) -> Self where A: Service, F: Fn(A::Error) -> E, { Self { service, f, _t: PhantomData, } } } impl<A, F, E> Clone for MapErr<A, F, E> where A: Clone, F: Clone, { fn clone(&self) -> Self { MapErr { service: self.service.clone(), f: self.f.clone(), _t: PhantomData, } } } impl<A, F, E> Service for MapErr<A, F, E> where A: Service, F: Fn(A::Error) -> E + Clone, { type Request = A::Request; type Response = A::Response; type Error = E; type Future = MapErrFuture<A, F, E>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { self.service.poll_ready().map_err(&self.f) } fn call(&mut self, req: A::Request) -> Self::Future { MapErrFuture::new(self.service.call(req), self.f.clone()) } } pub struct MapErrFuture<A, F, E> where A: Service, F: Fn(A::Error) -> E, { f: F, fut: A::Future, } impl<A, F, E> MapErrFuture<A, F, E> where A: Service, F: Fn(A::Error) -> E, { fn new(fut: A::Future, f: F) -> Self { MapErrFuture { f, fut } } } impl<A, F, E> Future for MapErrFuture<A, F, E> where A: Service, F: Fn(A::Error) -> E, { type Item = A::Response; type Error = E; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { self.fut.poll().map_err(&self.f) } } /// NewService for the `map_err` combinator, changing the type of a new /// service's error. /// /// This is created by the `NewServiceExt::map_err` method. pub struct MapErrNewService<A, F, E, C> { a: A, f: F, e: PhantomData<(E, C)>, } impl<A, F, E, C> MapErrNewService<A, F, E, C> { /// Create new `MapErr` new service instance pub fn new(a: A, f: F) -> Self where A: NewService<C>, F: Fn(A::Error) -> E, { Self { a, f, e: PhantomData, } } } impl<A, F, E, C> Clone for MapErrNewService<A, F, E, C> where A: Clone, F: Clone, { fn clone(&self) -> Self { Self { a: self.a.clone(), f: self.f.clone(), e: PhantomData, } } } impl<A, F, E, C> NewService<C> for MapErrNewService<A, F, E, C> where A: NewService<C>, F: Fn(A::Error) -> E + Clone, { type Request = A::Request; type Response = A::Response; type Error = E; type Service = MapErr<A::Service, F, E>; type InitError = A::InitError; type Future = MapErrNewServiceFuture<A, F, E, C>; fn new_service(&self, cfg: &C) -> Self::Future { MapErrNewServiceFuture::new(self.a.new_service(cfg), self.f.clone()) } } pub struct MapErrNewServiceFuture<A, F, E, C> where A: NewService<C>, F: Fn(A::Error) -> E, { fut: A::Future, f: F, } impl<A, F, E, C> MapErrNewServiceFuture<A, F, E, C> where A: NewService<C>, F: Fn(A::Error) -> E, { fn new(fut: A::Future, f: F) -> Self { MapErrNewServiceFuture { f, fut } } } impl<A, F, E, C> Future for MapErrNewServiceFuture<A, F, E, C> where A: NewService<C>, F: Fn(A::Error) -> E + Clone, { type Item = MapErr<A::Service, F, E>; type Error = A::InitError; fn poll(&mut self) -> Poll<Self::Item, Self::Error> { if let Async::Ready(service) = self.fut.poll()? { Ok(Async::Ready(MapErr::new(service, self.f.clone()))) } else { Ok(Async::NotReady) } } } #[cfg(test)] mod tests { use futures::future::{err, FutureResult}; use super::*; use crate::{IntoNewService, NewService, Service, ServiceExt}; struct Srv; impl Service for Srv { type Request = (); type Response = (); type Error = (); type Future = FutureResult<(), ()>; fn poll_ready(&mut self) -> Poll<(), Self::Error> { Err(()) } fn call(&mut self, _: ()) -> Self::Future { err(()) } } #[test] fn test_poll_ready() { let mut srv = Srv.map_err(|_| "error"); let res = srv.poll_ready(); assert!(res.is_err()); assert_eq!(res.err().unwrap(), "error"); } #[test] fn test_call() { let mut srv = Srv.map_err(|_| "error"); let res = srv.call(()).poll(); assert!(res.is_err()); assert_eq!(res.err().unwrap(), "error"); } #[test] fn test_new_service() { let blank = || Ok::<_, ()>(Srv); let new_srv = blank.into_new_service().map_err(|_| "error"); if let Async::Ready(mut srv) = new_srv.new_service(&()).poll().unwrap() { let res = srv.call(()).poll(); assert!(res.is_err()); assert_eq!(res.err().unwrap(), "error"); } else { panic!() } } }
/* * Open Service Cloud API * * Open Service Cloud API to manage different backend cloud services. * * The version of the OpenAPI document: 0.0.3 * Contact: wanghui71leon@gmail.com * Generated by: https://openapi-generator.tech */ #[derive(Debug, PartialEq, Serialize, Deserialize)] pub struct CloudServerRequestFragmentPublicipEip { #[serde(rename = "ip_type")] pub ip_type: IpType, #[serde(rename = "bandwidth")] pub bandwidth: crate::models::BandwidthResource, } impl CloudServerRequestFragmentPublicipEip { pub fn new( ip_type: IpType, bandwidth: crate::models::BandwidthResource, ) -> CloudServerRequestFragmentPublicipEip { CloudServerRequestFragmentPublicipEip { ip_type: ip_type, bandwidth: bandwidth, } } } /// #[derive(Debug, PartialEq, Serialize, Deserialize)] pub enum IpType { #[serde(rename = "5_bgp")] Bgp, #[serde(rename = "5_sbgp")] Sbgp, }
//! Extensions and types for the standard networking primitives. //! //! This module contains a number of extension traits for the types in //! `std::net` for Windows-specific functionality. use std::cmp; use std::io; use std::mem; use std::sync::atomic::{AtomicUsize, Ordering, ATOMIC_USIZE_INIT}; use std::net::{TcpStream, UdpSocket, SocketAddr, TcpListener}; use std::net::{SocketAddrV4, Ipv4Addr, SocketAddrV6, Ipv6Addr}; use std::os::windows::prelude::*; use net2::TcpBuilder; use winapi::*; use ws2_32::*; /// A type to represent a buffer in which a socket address will be stored. /// /// This type is used with the `recv_from_overlapped` function on the /// `UdpSocketExt` trait to provide space for the overlapped I/O operation to /// fill in the address upon completion. #[derive(Clone, Copy)] pub struct SocketAddrBuf { buf: SOCKADDR_STORAGE, len: c_int, } /// A type to represent a buffer in which an accepted socket's address will be /// stored. /// /// This type is used with the `accept_overlapped` method on the /// `TcpListenerExt` trait to provide space for the overlapped I/O operation to /// fill in the socket addresses upon completion. #[repr(C)] pub struct AcceptAddrsBuf { // For AcceptEx we've got the restriction that the addresses passed in that // buffer need to be at least 16 bytes more than the maximum address length // for the protocol in question, so add some extra here and there local: SOCKADDR_STORAGE, _pad1: [u8; 16], remote: SOCKADDR_STORAGE, _pad2: [u8; 16], } /// The parsed return value of `AcceptAddrsBuf`. pub struct AcceptAddrs<'a> { local: LPSOCKADDR, local_len: c_int, remote: LPSOCKADDR, remote_len: c_int, _data: &'a AcceptAddrsBuf, } struct WsaExtension { guid: GUID, val: AtomicUsize, } /// Additional methods for the `TcpStream` type in the standard library. pub trait TcpStreamExt { /// Execute an overlapped read I/O operation on this TCP stream. /// /// This function will issue an overlapped I/O read (via `WSARecv`) on this /// socket. The provided buffer will be filled in when the operation /// completes and the given `OVERLAPPED` instance is used to track the /// overlapped operation. /// /// If the operation succeeds, `Ok(Some(n))` is returned indicating how /// many bytes were read. If the operation returns an error indicating that /// the I/O is currently pending, `Ok(None)` is returned. Otherwise, the /// error associated with the operation is returned and no overlapped /// operation is enqueued. /// /// The number of bytes read will be returned as part of the completion /// notification when the I/O finishes. /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the `buf` and /// `overlapped` pointers are valid until the end of the I/O operation. The /// kernel also requires that `overlapped` is unique for this I/O operation /// and is not in use for any other I/O. /// /// To safely use this function callers must ensure that these two input /// pointers are valid until the I/O operation is completed, typically via /// completion ports and waiting to receive the completion notification on /// the port. unsafe fn read_overlapped(&self, buf: &mut [u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>>; /// Execute an overlapped write I/O operation on this TCP stream. /// /// This function will issue an overlapped I/O write (via `WSASend`) on this /// socket. The provided buffer will be written when the operation completes /// and the given `OVERLAPPED` instance is used to track the overlapped /// operation. /// /// If the operation succeeds, `Ok(Some(n))` is returned where `n` is the /// number of bytes that were written. If the operation returns an error /// indicating that the I/O is currently pending, `Ok(None)` is returned. /// Otherwise, the error associated with the operation is returned and no /// overlapped operation is enqueued. /// /// The number of bytes written will be returned as part of the completion /// notification when the I/O finishes. /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the `buf` and /// `overlapped` pointers are valid until the end of the I/O operation. The /// kernel also requires that `overlapped` is unique for this I/O operation /// and is not in use for any other I/O. /// /// To safely use this function callers must ensure that these two input /// pointers are valid until the I/O operation is completed, typically via /// completion ports and waiting to receive the completion notification on /// the port. unsafe fn write_overlapped(&self, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>>; /// Execute a connection operation for this socket. /// /// For more information about this method, see the /// [`TcpBuilderExt::connect_overlapped`][link] documentation. /// /// [link]: trait.TcpBuilderExt.html#tymethod.connect_overlapped unsafe fn connect_overlapped(&self, addr: &SocketAddr, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>>; /// Once a `connect_overlapped` has finished, this function needs to be /// called to finish the connect operation. /// /// Currently this just calls `setsockopt` with `SO_UPDATE_CONNECT_CONTEXT` /// to ensure that further functions like `getpeername` and `getsockname` /// work correctly. fn connect_complete(&self) -> io::Result<()>; /// Calls the `GetOverlappedResult` function to get the result of an /// overlapped operation for this handle. /// /// This function takes the `OVERLAPPED` argument which must have been used /// to initiate an overlapped I/O operation, and returns either the /// successful number of bytes transferred during the operation or an error /// if one occurred, along with the results of the `lpFlags` parameter of /// the relevant operation, if applicable. /// /// # Unsafety /// /// This function is unsafe as `overlapped` must have previously been used /// to execute an operation for this handle, and it must also be a valid /// pointer to an `OVERLAPPED` instance. /// /// # Panics /// /// This function will panic unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<(usize, u32)>; } /// Additional methods for the `UdpSocket` type in the standard library. pub trait UdpSocketExt { /// Execute an overlapped receive I/O operation on this UDP socket. /// /// This function will issue an overlapped I/O read (via `WSARecvFrom`) on /// this socket. The provided buffer will be filled in when the operation /// completes, the source from where the data came from will be written to /// `addr`, and the given `OVERLAPPED` instance is used to track the /// overlapped operation. /// /// If the operation succeeds, `Ok(Some(n))` is returned where `n` is the /// number of bytes that were read. If the operation returns an error /// indicating that the I/O is currently pending, `Ok(None)` is returned. /// Otherwise, the error associated with the operation is returned and no /// overlapped operation is enqueued. /// /// The number of bytes read will be returned as part of the completion /// notification when the I/O finishes. /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the `buf`, /// `addr`, and `overlapped` pointers are valid until the end of the I/O /// operation. The kernel also requires that `overlapped` is unique for this /// I/O operation and is not in use for any other I/O. /// /// To safely use this function callers must ensure that these two input /// pointers are valid until the I/O operation is completed, typically via /// completion ports and waiting to receive the completion notification on /// the port. unsafe fn recv_from_overlapped(&self, buf: &mut [u8], addr: *mut SocketAddrBuf, overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>>; /// Execute an overlapped receive I/O operation on this UDP socket. /// /// This function will issue an overlapped I/O read (via `WSARecv`) on /// this socket. The provided buffer will be filled in when the operation /// completes, the source from where the data came from will be written to /// `addr`, and the given `OVERLAPPED` instance is used to track the /// overlapped operation. /// /// If the operation succeeds, `Ok(Some(n))` is returned where `n` is the /// number of bytes that were read. If the operation returns an error /// indicating that the I/O is currently pending, `Ok(None)` is returned. /// Otherwise, the error associated with the operation is returned and no /// overlapped operation is enqueued. /// /// The number of bytes read will be returned as part of the completion /// notification when the I/O finishes. /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the `buf`, /// and `overlapped` pointers are valid until the end of the I/O /// operation. The kernel also requires that `overlapped` is unique for this /// I/O operation and is not in use for any other I/O. /// /// To safely use this function callers must ensure that these two input /// pointers are valid until the I/O operation is completed, typically via /// completion ports and waiting to receive the completion notification on /// the port. unsafe fn recv_overlapped(&self, buf: &mut [u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>>; /// Execute an overlapped send I/O operation on this UDP socket. /// /// This function will issue an overlapped I/O write (via `WSASendTo`) on /// this socket to the address specified by `addr`. The provided buffer will /// be written when the operation completes and the given `OVERLAPPED` /// instance is used to track the overlapped operation. /// /// If the operation succeeds, `Ok(Some(n0)` is returned where `n` byte /// were written. If the operation returns an error indicating that the I/O /// is currently pending, `Ok(None)` is returned. Otherwise, the error /// associated with the operation is returned and no overlapped operation /// is enqueued. /// /// The number of bytes written will be returned as part of the completion /// notification when the I/O finishes. /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the `buf` and /// `overlapped` pointers are valid until the end of the I/O operation. The /// kernel also requires that `overlapped` is unique for this I/O operation /// and is not in use for any other I/O. /// /// To safely use this function callers must ensure that these two input /// pointers are valid until the I/O operation is completed, typically via /// completion ports and waiting to receive the completion notification on /// the port. unsafe fn send_to_overlapped(&self, buf: &[u8], addr: &SocketAddr, overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>>; /// Execute an overlapped send I/O operation on this UDP socket. /// /// This function will issue an overlapped I/O write (via `WSASend`) on /// this socket to the address it was previously connected to. The provided /// buffer will be written when the operation completes and the given `OVERLAPPED` /// instance is used to track the overlapped operation. /// /// If the operation succeeds, `Ok(Some(n0)` is returned where `n` byte /// were written. If the operation returns an error indicating that the I/O /// is currently pending, `Ok(None)` is returned. Otherwise, the error /// associated with the operation is returned and no overlapped operation /// is enqueued. /// /// The number of bytes written will be returned as part of the completion /// notification when the I/O finishes. /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the `buf` and /// `overlapped` pointers are valid until the end of the I/O operation. The /// kernel also requires that `overlapped` is unique for this I/O operation /// and is not in use for any other I/O. /// /// To safely use this function callers must ensure that these two input /// pointers are valid until the I/O operation is completed, typically via /// completion ports and waiting to receive the completion notification on /// the port. unsafe fn send_overlapped(&self, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>>; /// Calls the `GetOverlappedResult` function to get the result of an /// overlapped operation for this handle. /// /// This function takes the `OVERLAPPED` argument which must have been used /// to initiate an overlapped I/O operation, and returns either the /// successful number of bytes transferred during the operation or an error /// if one occurred, along with the results of the `lpFlags` parameter of /// the relevant operation, if applicable. /// /// # Unsafety /// /// This function is unsafe as `overlapped` must have previously been used /// to execute an operation for this handle, and it must also be a valid /// pointer to an `OVERLAPPED` instance. /// /// # Panics /// /// This function will panic unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<(usize, u32)>; } /// Additional methods for the `TcpBuilder` type in the `net2` library. pub trait TcpBuilderExt { /// Attempt to consume the internal socket in this builder by executing an /// overlapped connect operation. /// /// This function will issue a connect operation to the address specified on /// the underlying socket, flagging it as an overlapped operation which will /// complete asynchronously. If successful this function will return the /// corresponding TCP stream. /// /// The `buf` argument provided is an initial buffer of data that should be /// sent after the connection is initiated. It's acceptable to /// pass an empty slice here. /// /// This function will also return whether the connect immediately /// succeeded or not. If `None` is returned then the I/O operation is still /// pending and will complete at a later date, and if `Some(bytes)` is /// returned then that many bytes were transferred. /// /// Note that to succeed this requires that the underlying socket has /// previously been bound via a call to `bind` to a local address. /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the /// `overlapped` and `buf` pointers to be valid until the end of the I/O /// operation. The kernel also requires that `overlapped` is unique for /// this I/O operation and is not in use for any other I/O. /// /// To safely use this function callers must ensure that this pointer is /// valid until the I/O operation is completed, typically via completion /// ports and waiting to receive the completion notification on the port. unsafe fn connect_overlapped(&self, addr: &SocketAddr, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<(TcpStream, Option<usize>)>; /// Calls the `GetOverlappedResult` function to get the result of an /// overlapped operation for this handle. /// /// This function takes the `OVERLAPPED` argument which must have been used /// to initiate an overlapped I/O operation, and returns either the /// successful number of bytes transferred during the operation or an error /// if one occurred, along with the results of the `lpFlags` parameter of /// the relevant operation, if applicable. /// /// # Unsafety /// /// This function is unsafe as `overlapped` must have previously been used /// to execute an operation for this handle, and it must also be a valid /// pointer to an `OVERLAPPED` instance. /// /// # Panics /// /// This function will panic unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<(usize, u32)>; } /// Additional methods for the `TcpListener` type in the standard library. pub trait TcpListenerExt { /// Perform an accept operation on this listener, accepting a connection in /// an overlapped fashion. /// /// This function will issue an I/O request to accept an incoming connection /// with the specified overlapped instance. The `socket` provided must be a /// configured but not bound or connected socket, and if successful this /// will consume the internal socket of the builder to return a TCP stream. /// /// The `addrs` buffer provided will be filled in with the local and remote /// addresses of the connection upon completion. /// /// If the accept succeeds immediately, `Ok(stream, true)` is returned. If /// the connect indicates that the I/O is currently pending, `Ok(stream, /// false)` is returned. Otherwise, the error associated with the operation /// is returned and no overlapped operation is enqueued. /// /// # Unsafety /// /// This function is unsafe because the kernel requires that the /// `addrs` and `overlapped` pointers are valid until the end of the I/O /// operation. The kernel also requires that `overlapped` is unique for this /// I/O operation and is not in use for any other I/O. /// /// To safely use this function callers must ensure that the pointers are /// valid until the I/O operation is completed, typically via completion /// ports and waiting to receive the completion notification on the port. unsafe fn accept_overlapped(&self, socket: &TcpBuilder, addrs: &mut AcceptAddrsBuf, overlapped: *mut OVERLAPPED) -> io::Result<(TcpStream, bool)>; /// Once an `accept_overlapped` has finished, this function needs to be /// called to finish the accept operation. /// /// Currently this just calls `setsockopt` with `SO_UPDATE_ACCEPT_CONTEXT` /// to ensure that further functions like `getpeername` and `getsockname` /// work correctly. fn accept_complete(&self, socket: &TcpStream) -> io::Result<()>; /// Calls the `GetOverlappedResult` function to get the result of an /// overlapped operation for this handle. /// /// This function takes the `OVERLAPPED` argument which must have been used /// to initiate an overlapped I/O operation, and returns either the /// successful number of bytes transferred during the operation or an error /// if one occurred, along with the results of the `lpFlags` parameter of /// the relevant operation, if applicable. /// /// # Unsafety /// /// This function is unsafe as `overlapped` must have previously been used /// to execute an operation for this handle, and it must also be a valid /// pointer to an `OVERLAPPED` instance. /// /// # Panics /// /// This function will panic unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<(usize, u32)>; } #[doc(hidden)] trait NetInt { fn from_be(i: Self) -> Self; fn to_be(&self) -> Self; } macro_rules! doit { ($($t:ident)*) => ($(impl NetInt for $t { fn from_be(i: Self) -> Self { <$t>::from_be(i) } fn to_be(&self) -> Self { <$t>::to_be(*self) } })*) } doit! { i8 i16 i32 i64 isize u8 u16 u32 u64 usize } // fn hton<I: NetInt>(i: I) -> I { i.to_be() } fn ntoh<I: NetInt>(i: I) -> I { I::from_be(i) } fn last_err() -> io::Result<Option<usize>> { let err = unsafe { WSAGetLastError() }; if err == WSA_IO_PENDING as i32 { Ok(None) } else { Err(io::Error::from_raw_os_error(err)) } } fn cvt(i: c_int, size: DWORD) -> io::Result<Option<usize>> { if i == SOCKET_ERROR { last_err() } else { Ok(Some(size as usize)) } } fn socket_addr_to_ptrs(addr: &SocketAddr) -> (*const SOCKADDR, c_int) { match *addr { SocketAddr::V4(ref a) => { (a as *const _ as *const _, mem::size_of::<SOCKADDR_IN>() as c_int) } SocketAddr::V6(ref a) => { (a as *const _ as *const _, mem::size_of::<sockaddr_in6>() as c_int) } } } unsafe fn ptrs_to_socket_addr(ptr: *const SOCKADDR, len: c_int) -> Option<SocketAddr> { if (len as usize) < mem::size_of::<c_int>() { return None } match (*ptr).sa_family as i32 { AF_INET if len as usize >= mem::size_of::<SOCKADDR_IN>() => { let b = &*(ptr as *const SOCKADDR_IN); let ip = ntoh(b.sin_addr.S_un); let ip = Ipv4Addr::new((ip >> 24) as u8, (ip >> 16) as u8, (ip >> 8) as u8, (ip >> 0) as u8); Some(SocketAddr::V4(SocketAddrV4::new(ip, ntoh(b.sin_port)))) } AF_INET6 if len as usize >= mem::size_of::<sockaddr_in6>() => { let b = &*(ptr as *const sockaddr_in6); let arr = &b.sin6_addr.s6_addr; let ip = Ipv6Addr::new( ((arr[0] as u16) << 8) | (arr[1] as u16), ((arr[2] as u16) << 8) | (arr[3] as u16), ((arr[4] as u16) << 8) | (arr[5] as u16), ((arr[6] as u16) << 8) | (arr[7] as u16), ((arr[8] as u16) << 8) | (arr[9] as u16), ((arr[10] as u16) << 8) | (arr[11] as u16), ((arr[12] as u16) << 8) | (arr[13] as u16), ((arr[14] as u16) << 8) | (arr[15] as u16)); let addr = SocketAddrV6::new(ip, ntoh(b.sin6_port), ntoh(b.sin6_flowinfo), ntoh(b.sin6_scope_id)); Some(SocketAddr::V6(addr)) } _ => None } } unsafe fn slice2buf(slice: &[u8]) -> WSABUF { WSABUF { len: cmp::min(slice.len(), <u_long>::max_value() as usize) as u_long, buf: slice.as_ptr() as *mut _, } } unsafe fn result(socket: SOCKET, overlapped: *mut OVERLAPPED) -> io::Result<(usize, u32)> { let mut transferred = 0; let mut flags = 0; let r = WSAGetOverlappedResult(socket, overlapped, &mut transferred, FALSE, &mut flags); if r == 0 { Err(io::Error::last_os_error()) } else { Ok((transferred as usize, flags)) } } impl TcpStreamExt for TcpStream { unsafe fn read_overlapped(&self, buf: &mut [u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { let mut buf = slice2buf(buf); let mut flags = 0; let mut bytes_read: DWORD = 0; let r = WSARecv(self.as_raw_socket(), &mut buf, 1, &mut bytes_read, &mut flags, overlapped, None); cvt(r, bytes_read) } unsafe fn write_overlapped(&self, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { let mut buf = slice2buf(buf); let mut bytes_written = 0; // Note here that we capture the number of bytes written. The // documentation on MSDN, however, states: // // > Use NULL for this parameter if the lpOverlapped parameter is not // > NULL to avoid potentially erroneous results. This parameter can be // > NULL only if the lpOverlapped parameter is not NULL. // // If we're not passing a null overlapped pointer here, then why are we // then capturing the number of bytes! Well so it turns out that this is // clearly faster to learn the bytes here rather than later calling // `WSAGetOverlappedResult`, and in practice almost all implementations // use this anyway [1]. // // As a result we use this to and report back the result. // // [1]: https://github.com/carllerche/mio/pull/520#issuecomment-273983823 let r = WSASend(self.as_raw_socket(), &mut buf, 1, &mut bytes_written, 0, overlapped, None); cvt(r, bytes_written) } unsafe fn connect_overlapped(&self, addr: &SocketAddr, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { connect_overlapped(self.as_raw_socket(), addr, buf, overlapped) } fn connect_complete(&self) -> io::Result<()> { const SO_UPDATE_CONNECT_CONTEXT: c_int = 0x7010; let result = unsafe { setsockopt(self.as_raw_socket(), SOL_SOCKET, SO_UPDATE_CONNECT_CONTEXT, 0 as *const _, 0) }; if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<(usize, u32)> { result(self.as_raw_socket(), overlapped) } } unsafe fn connect_overlapped(socket: SOCKET, addr: &SocketAddr, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { static CONNECTEX: WsaExtension = WsaExtension { guid: GUID { Data1: 0x25a207b9, Data2: 0xddf3, Data3: 0x4660, Data4: [0x8e, 0xe9, 0x76, 0xe5, 0x8c, 0x74, 0x06, 0x3e], }, val: ATOMIC_USIZE_INIT, }; type ConnectEx = unsafe extern "system" fn(SOCKET, *const SOCKADDR, c_int, PVOID, DWORD, LPDWORD, LPOVERLAPPED) -> BOOL; let ptr = try!(CONNECTEX.get(socket)); assert!(ptr != 0); let connect_ex = mem::transmute::<_, ConnectEx>(ptr); let (addr_buf, addr_len) = socket_addr_to_ptrs(addr); let mut bytes_sent: DWORD = 0; let r = connect_ex(socket, addr_buf, addr_len, buf.as_ptr() as *mut _, buf.len() as u32, &mut bytes_sent, overlapped); if r == TRUE { Ok(Some(bytes_sent as usize)) } else { last_err() } } impl UdpSocketExt for UdpSocket { unsafe fn recv_from_overlapped(&self, buf: &mut [u8], addr: *mut SocketAddrBuf, overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { let mut buf = slice2buf(buf); let mut flags = 0; let mut received_bytes: DWORD = 0; let r = WSARecvFrom(self.as_raw_socket(), &mut buf, 1, &mut received_bytes, &mut flags, &mut (*addr).buf as *mut _ as *mut _, &mut (*addr).len, overlapped, None); cvt(r, received_bytes) } unsafe fn recv_overlapped(&self, buf: &mut [u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { let mut buf = slice2buf(buf); let mut flags = 0; let mut received_bytes: DWORD = 0; let r = WSARecv(self.as_raw_socket(), &mut buf, 1, &mut received_bytes, &mut flags, overlapped, None); cvt(r, received_bytes) } unsafe fn send_to_overlapped(&self, buf: &[u8], addr: &SocketAddr, overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { let (addr_buf, addr_len) = socket_addr_to_ptrs(addr); let mut buf = slice2buf(buf); let mut sent_bytes = 0; let r = WSASendTo(self.as_raw_socket(), &mut buf, 1, &mut sent_bytes, 0, addr_buf as *const _, addr_len, overlapped, None); cvt(r, sent_bytes) } unsafe fn send_overlapped(&self, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<Option<usize>> { let mut buf = slice2buf(buf); let mut sent_bytes = 0; let r = WSASend(self.as_raw_socket(), &mut buf, 1, &mut sent_bytes, 0, overlapped, None); cvt(r, sent_bytes) } unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<(usize, u32)> { result(self.as_raw_socket(), overlapped) } } impl TcpBuilderExt for TcpBuilder { unsafe fn connect_overlapped(&self, addr: &SocketAddr, buf: &[u8], overlapped: *mut OVERLAPPED) -> io::Result<(TcpStream, Option<usize>)> { connect_overlapped(self.as_raw_socket(), addr, buf, overlapped).map(|s| { (self.to_tcp_stream().unwrap(), s) }) } unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<(usize, u32)> { result(self.as_raw_socket(), overlapped) } } impl TcpListenerExt for TcpListener { unsafe fn accept_overlapped(&self, socket: &TcpBuilder, addrs: &mut AcceptAddrsBuf, overlapped: *mut OVERLAPPED) -> io::Result<(TcpStream, bool)> { static ACCEPTEX: WsaExtension = WsaExtension { guid: GUID { Data1: 0xb5367df1, Data2: 0xcbac, Data3: 0x11cf, Data4: [0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92], }, val: ATOMIC_USIZE_INIT, }; type AcceptEx = unsafe extern "system" fn(SOCKET, SOCKET, PVOID, DWORD, DWORD, DWORD, LPDWORD, LPOVERLAPPED) -> BOOL; let ptr = try!(ACCEPTEX.get(self.as_raw_socket())); assert!(ptr != 0); let accept_ex = mem::transmute::<_, AcceptEx>(ptr); let mut bytes = 0; let (a, b, c, d) = (*addrs).args(); let r = accept_ex(self.as_raw_socket(), socket.as_raw_socket(), a, b, c, d, &mut bytes, overlapped); let succeeded = if r == TRUE { true } else { try!(last_err()); false }; // NB: this unwrap() should be guaranteed to succeed, and this is an // assert that it does indeed succeed. Ok((socket.to_tcp_stream().unwrap(), succeeded)) } fn accept_complete(&self, socket: &TcpStream) -> io::Result<()> { const SO_UPDATE_ACCEPT_CONTEXT: c_int = 0x700B; let me = self.as_raw_socket(); let result = unsafe { setsockopt(socket.as_raw_socket(), SOL_SOCKET, SO_UPDATE_ACCEPT_CONTEXT, &me as *const _ as *const _, mem::size_of_val(&me) as c_int) }; if result == 0 { Ok(()) } else { Err(io::Error::last_os_error()) } } unsafe fn result(&self, overlapped: *mut OVERLAPPED) -> io::Result<(usize, u32)> { result(self.as_raw_socket(), overlapped) } } impl SocketAddrBuf { /// Creates a new blank socket address buffer. /// /// This should be used before a call to `recv_from_overlapped` overlapped /// to create an instance to pass down. pub fn new() -> SocketAddrBuf { SocketAddrBuf { buf: unsafe { mem::zeroed() }, len: mem::size_of::<SOCKADDR_STORAGE>() as c_int, } } /// Parses this buffer to return a standard socket address. /// /// This function should be called after the buffer has been filled in with /// a call to `recv_from_overlapped` being completed. It will interpret the /// address filled in and return the standard socket address type. /// /// If an error is encountered then `None` is returned. pub fn to_socket_addr(&self) -> Option<SocketAddr> { unsafe { ptrs_to_socket_addr(&self.buf as *const _ as *const _, self.len) } } } static GETACCEPTEXSOCKADDRS: WsaExtension = WsaExtension { guid: GUID { Data1: 0xb5367df2, Data2: 0xcbac, Data3: 0x11cf, Data4: [0x95, 0xca, 0x00, 0x80, 0x5f, 0x48, 0xa1, 0x92], }, val: ATOMIC_USIZE_INIT, }; type GetAcceptExSockaddrs = unsafe extern "system" fn(PVOID, DWORD, DWORD, DWORD, *mut LPSOCKADDR, LPINT, *mut LPSOCKADDR, LPINT); impl AcceptAddrsBuf { /// Creates a new blank buffer ready to be passed to a call to /// `accept_overlapped`. pub fn new() -> AcceptAddrsBuf { unsafe { mem::zeroed() } } /// Parses the data contained in this address buffer, returning the parsed /// result if successful. /// /// This function can be called after a call to `accept_overlapped` has /// succeeded to parse out the data that was written in. pub fn parse(&self, socket: &TcpListener) -> io::Result<AcceptAddrs> { let mut ret = AcceptAddrs { local: 0 as *mut _, local_len: 0, remote: 0 as *mut _, remote_len: 0, _data: self, }; let ptr = try!(GETACCEPTEXSOCKADDRS.get(socket.as_raw_socket())); assert!(ptr != 0); unsafe { let get_sockaddrs = mem::transmute::<_, GetAcceptExSockaddrs>(ptr); let (a, b, c, d) = self.args(); get_sockaddrs(a, b, c, d, &mut ret.local, &mut ret.local_len, &mut ret.remote, &mut ret.remote_len); Ok(ret) } } fn args(&self) -> (PVOID, DWORD, DWORD, DWORD) { let remote_offset = unsafe { &(*(0 as *const AcceptAddrsBuf)).remote as *const _ as usize }; (self as *const _ as *mut _, 0, remote_offset as DWORD, (mem::size_of_val(self) - remote_offset) as DWORD) } } impl<'a> AcceptAddrs<'a> { /// Returns the local socket address contained in this buffer. pub fn local(&self) -> Option<SocketAddr> { unsafe { ptrs_to_socket_addr(self.local, self.local_len) } } /// Returns the remote socket address contained in this buffer. pub fn remote(&self) -> Option<SocketAddr> { unsafe { ptrs_to_socket_addr(self.remote, self.remote_len) } } } impl WsaExtension { fn get(&self, socket: SOCKET) -> io::Result<usize> { let prev = self.val.load(Ordering::SeqCst); if prev != 0 && !cfg!(debug_assertions) { return Ok(prev) } let mut ret = 0 as usize; let mut bytes = 0; let r = unsafe { WSAIoctl(socket, SIO_GET_EXTENSION_FUNCTION_POINTER, &self.guid as *const _ as *mut _, mem::size_of_val(&self.guid) as DWORD, &mut ret as *mut _ as *mut _, mem::size_of_val(&ret) as DWORD, &mut bytes, 0 as *mut _, None) }; cvt(r, 0).map(|_| { debug_assert_eq!(bytes as usize, mem::size_of_val(&ret)); debug_assert!(prev == 0 || prev == ret); self.val.store(ret, Ordering::SeqCst); ret }) } } #[cfg(test)] mod tests { use std::net::{TcpListener, UdpSocket, TcpStream, SocketAddr}; use std::thread; use std::io::prelude::*; use Overlapped; use iocp::CompletionPort; use net::{TcpStreamExt, UdpSocketExt, SocketAddrBuf}; use net::{TcpBuilderExt, TcpListenerExt, AcceptAddrsBuf}; use net2::TcpBuilder; fn each_ip(f: &mut FnMut(SocketAddr)) { f(t!("127.0.0.1:0".parse())); f(t!("[::1]:0".parse())); } #[test] fn tcp_read() { each_ip(&mut |addr| { let l = t!(TcpListener::bind(addr)); let addr = t!(l.local_addr()); let t = thread::spawn(move || { let mut a = t!(l.accept()).0; t!(a.write_all(&[1, 2, 3])); }); let cp = t!(CompletionPort::new(1)); let s = t!(TcpStream::connect(addr)); t!(cp.add_socket(1, &s)); let mut b = [0; 10]; let a = Overlapped::zero(); unsafe { t!(s.read_overlapped(&mut b, a.raw())); } let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 3); assert_eq!(status.token(), 1); assert_eq!(status.overlapped(), a.raw()); assert_eq!(&b[0..3], &[1, 2, 3]); t!(t.join()); }) } #[test] fn tcp_write() { each_ip(&mut |addr| { let l = t!(TcpListener::bind(addr)); let addr = t!(l.local_addr()); let t = thread::spawn(move || { let mut a = t!(l.accept()).0; let mut b = [0; 10]; let n = t!(a.read(&mut b)); assert_eq!(n, 3); assert_eq!(&b[0..3], &[1, 2, 3]); }); let cp = t!(CompletionPort::new(1)); let s = t!(TcpStream::connect(addr)); t!(cp.add_socket(1, &s)); let b = [1, 2, 3]; let a = Overlapped::zero(); unsafe { t!(s.write_overlapped(&b, a.raw())); } let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 3); assert_eq!(status.token(), 1); assert_eq!(status.overlapped(), a.raw()); t!(t.join()); }) } #[test] fn tcp_connect() { each_ip(&mut |addr_template| { let l = t!(TcpListener::bind(addr_template)); let addr = t!(l.local_addr()); let t = thread::spawn(move || { t!(l.accept()); }); let cp = t!(CompletionPort::new(1)); let builder = match addr { SocketAddr::V4(..) => t!(TcpBuilder::new_v4()), SocketAddr::V6(..) => t!(TcpBuilder::new_v6()), }; t!(cp.add_socket(1, &builder)); let a = Overlapped::zero(); t!(builder.bind(addr_template)); let (s, _) = unsafe { t!(builder.connect_overlapped(&addr, &[], a.raw())) }; let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 0); assert_eq!(status.token(), 1); assert_eq!(status.overlapped(), a.raw()); t!(s.connect_complete()); t!(t.join()); }) } #[test] fn udp_recv_from() { each_ip(&mut |addr| { let a = t!(UdpSocket::bind(addr)); let b = t!(UdpSocket::bind(addr)); let a_addr = t!(a.local_addr()); let b_addr = t!(b.local_addr()); let t = thread::spawn(move || { t!(a.send_to(&[1, 2, 3], b_addr)); }); let cp = t!(CompletionPort::new(1)); t!(cp.add_socket(1, &b)); let mut buf = [0; 10]; let a = Overlapped::zero(); let mut addr = SocketAddrBuf::new(); unsafe { t!(b.recv_from_overlapped(&mut buf, &mut addr, a.raw())); } let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 3); assert_eq!(status.token(), 1); assert_eq!(status.overlapped(), a.raw()); assert_eq!(&buf[..3], &[1, 2, 3]); assert_eq!(addr.to_socket_addr(), Some(a_addr)); t!(t.join()); }) } #[test] fn udp_recv() { each_ip(&mut |addr| { let a = t!(UdpSocket::bind(addr)); let b = t!(UdpSocket::bind(addr)); let a_addr = t!(a.local_addr()); let b_addr = t!(b.local_addr()); assert!(b.connect(a_addr).is_ok()); assert!(a.connect(b_addr).is_ok()); let t = thread::spawn(move || { t!(a.send_to(&[1, 2, 3], b_addr)); }); let cp = t!(CompletionPort::new(1)); t!(cp.add_socket(1, &b)); let mut buf = [0; 10]; let a = Overlapped::zero(); unsafe { t!(b.recv_overlapped(&mut buf, a.raw())); } let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 3); assert_eq!(status.token(), 1); assert_eq!(status.overlapped(), a.raw()); assert_eq!(&buf[..3], &[1, 2, 3]); t!(t.join()); }) } #[test] fn udp_send_to() { each_ip(&mut |addr| { let a = t!(UdpSocket::bind(addr)); let b = t!(UdpSocket::bind(addr)); let a_addr = t!(a.local_addr()); let b_addr = t!(b.local_addr()); let t = thread::spawn(move || { let mut b = [0; 100]; let (n, addr) = t!(a.recv_from(&mut b)); assert_eq!(n, 3); assert_eq!(addr, b_addr); assert_eq!(&b[..3], &[1, 2, 3]); }); let cp = t!(CompletionPort::new(1)); t!(cp.add_socket(1, &b)); let a = Overlapped::zero(); unsafe { t!(b.send_to_overlapped(&[1, 2, 3], &a_addr, a.raw())); } let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 3); assert_eq!(status.token(), 1); assert_eq!(status.overlapped(), a.raw()); t!(t.join()); }) } #[test] fn udp_send() { each_ip(&mut |addr| { let a = t!(UdpSocket::bind(addr)); let b = t!(UdpSocket::bind(addr)); let a_addr = t!(a.local_addr()); let b_addr = t!(b.local_addr()); assert!(b.connect(a_addr).is_ok()); assert!(a.connect(b_addr).is_ok()); let t = thread::spawn(move || { let mut b = [0; 100]; let (n, addr) = t!(a.recv_from(&mut b)); assert_eq!(n, 3); assert_eq!(addr, b_addr); assert_eq!(&b[..3], &[1, 2, 3]); }); let cp = t!(CompletionPort::new(1)); t!(cp.add_socket(1, &b)); let a = Overlapped::zero(); unsafe { t!(b.send_overlapped(&[1, 2, 3], a.raw())); } let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 3); assert_eq!(status.token(), 1); assert_eq!(status.overlapped(), a.raw()); t!(t.join()); }) } #[test] fn tcp_accept() { each_ip(&mut |addr_template| { let l = t!(TcpListener::bind(addr_template)); let addr = t!(l.local_addr()); let t = thread::spawn(move || { let socket = t!(TcpStream::connect(addr)); (socket.local_addr().unwrap(), socket.peer_addr().unwrap()) }); let cp = t!(CompletionPort::new(1)); let builder = match addr { SocketAddr::V4(..) => t!(TcpBuilder::new_v4()), SocketAddr::V6(..) => t!(TcpBuilder::new_v6()), }; t!(cp.add_socket(1, &l)); let a = Overlapped::zero(); let mut addrs = AcceptAddrsBuf::new(); let (s, _) = unsafe { t!(l.accept_overlapped(&builder, &mut addrs, a.raw())) }; let status = t!(cp.get(None)); assert_eq!(status.bytes_transferred(), 0); assert_eq!(status.token(), 1); assert_eq!(status.overlapped(), a.raw()); t!(l.accept_complete(&s)); let (remote, local) = t!(t.join()); let addrs = addrs.parse(&l).unwrap(); assert_eq!(addrs.local(), Some(local)); assert_eq!(addrs.remote(), Some(remote)); }) } }
use std::fmt::{self, Display, Formatter}; use std::default::Default; use rlua::{self, Table, Lua, UserData, ToLua, Value, AnyUserData, UserDataMethods}; use super::object::{self, Object, Objectable}; use super::signal; use super::property::Property; use super::class::{self, Class}; use rustwlc::types::KeyMod; use xcb::ffi::xproto::xcb_button_t; #[derive(Clone, Debug)] pub struct ButtonState { button: xcb_button_t, modifiers: KeyMod } #[derive(Clone, Debug)] pub struct Button<'lua>(Object<'lua>); impl Display for ButtonState { fn fmt(&self, f: &mut Formatter) -> fmt::Result { write!(f, "Button: {:p}", self) } } impl Default for ButtonState { fn default() -> Self { ButtonState { button: xcb_button_t::default(), modifiers: KeyMod::empty() } } } impl UserData for ButtonState { fn add_methods(methods: &mut UserDataMethods<Self>) { object::default_add_methods(methods); } } impl <'lua> Button<'lua> { fn new(lua: &'lua Lua, args: rlua::Table) -> rlua::Result<Object<'lua>> { let class = class::class_setup(lua, "button")?; Ok(Button::allocate(lua, class)? .handle_constructor_argument(args)? .build()) } pub fn button(&self) -> rlua::Result<Value<'lua>> { let button = self.state()?; Ok(Value::Integer(button.button as _)) } pub fn set_button(&mut self, new_val: xcb_button_t) -> rlua::Result<()> { let mut button = self.get_object_mut()?; button.button = new_val; Ok(()) } pub fn modifiers(&self) -> rlua::Result<KeyMod> { let button = self.state()?; Ok(button.modifiers) } pub fn set_modifiers(&mut self, mods: Table<'lua>) -> rlua::Result<()> { use ::lua::mods_to_rust; let mut button = self.get_object_mut()?; button.modifiers = mods_to_rust(mods)?; Ok(()) } } impl <'lua> ToLua<'lua> for Button<'lua> { fn to_lua(self, lua: &'lua Lua) -> rlua::Result<Value<'lua>> { self.0.to_lua(lua) } } impl_objectable!(Button, ButtonState); pub fn init(lua: &Lua) -> rlua::Result<Class> { Class::builder(lua, "button", None)? .method("__call".into(), lua.create_function(|lua, args: rlua::Table| Button::new(lua, args))?)? .property(Property::new("button".into(), Some(lua.create_function(set_button)?), Some(lua.create_function(get_button)?), Some(lua.create_function(set_button)?)))? .property(Property::new("modifiers".into(), Some(lua.create_function(set_modifiers)?), Some(lua.create_function(get_modifiers)?), Some(lua.create_function(set_modifiers)?)))? .save_class("button")? .build() } fn set_button<'lua>(lua: &'lua Lua, (obj, val): (AnyUserData<'lua>, Value<'lua>)) -> rlua::Result<Value<'lua>> { use rlua::Value::*; let mut button = Button::cast(obj.clone().into())?; match val { Number(num) => button.set_button(num as _)?, Integer(num) => button.set_button(num as _)?, _ => button.set_button(xcb_button_t::default())? } signal::emit_object_signal(lua, obj.into(), "property::button".into(), val)?; Ok(Value::Nil) } fn get_button<'lua>(_: &'lua Lua, obj: AnyUserData<'lua>) -> rlua::Result<Value<'lua>> { Button::cast(obj.into())?.button() } fn set_modifiers<'lua>(lua: &'lua Lua, (obj, modifiers): (AnyUserData<'lua>, Table<'lua>)) -> rlua::Result<Value<'lua>> { let mut button = Button::cast(obj.clone().into())?; button.set_modifiers(modifiers.clone())?; signal::emit_object_signal(lua, obj.into(), "property::modifiers".into(), modifiers)?; Ok(Value::Nil) } fn get_modifiers<'lua>(lua: &'lua Lua, obj: AnyUserData<'lua>) -> rlua::Result<Value<'lua>> { use ::lua::mods_to_lua; mods_to_lua(lua, Button::cast(obj.into())?.modifiers()?).map(Value::Table) } #[cfg(test)] mod test { use rlua::{AnyUserData, Lua}; use super::super::button::{self, Button}; use super::super::object; #[test] fn button_object_test() { let lua = Lua::new(); button::init(&lua).unwrap(); lua.globals().set("button0", Button::new(&lua, lua.create_table().unwrap()).unwrap()) .unwrap(); lua.globals().set("button1", Button::new(&lua, lua.create_table().unwrap()).unwrap()) .unwrap(); lua.eval(r#" assert(button0.button == 0) assert(button1.button == 0) button0:connect_signal("test", function(button) button.button = 3 end) button0:emit_signal("test") assert(button1.button == 0) assert(button0.button == 3) "#, None).unwrap() } #[test] fn button_class_test() { let lua = Lua::new(); button::init(&lua).unwrap(); lua.eval(r#" a_button = button{} assert(a_button.button == 0) a_button:connect_signal("test", function(button) button.button = 2 end) a_button:emit_signal("test") assert(a_button.button == 2) "#, None).unwrap() } #[test] fn button_property_test() { let lua = Lua::new(); let button_class = button::init(&lua).unwrap(); use rlua::{self, Table, ToLua}; let mut count = -1; if let rlua::Value::UserData(any) = button_class.to_lua(&lua).unwrap() { count = any.get_user_value::<Table>().unwrap().get::<_, Table>("properties").unwrap().len().unwrap(); } assert_eq!(count, 2); lua.eval(r#" a_button = button{} assert(a_button.button == 0) a_button.button = 5 assert(a_button.button == 5) "#, None).unwrap() } #[test] fn button_remove_signal_test() { let lua = Lua::new(); button::init(&lua).unwrap(); lua.eval(r#" button0 = button{} assert(button0.button == 0) button0:connect_signal("test", function(button) button.button = 3 end) button0:emit_signal("test") assert(button0.button == 3) button0.button = 0 button0:disconnect_signal("test") button0:emit_signal("test") assert(button0.button == 0) "#, None).unwrap() } #[test] fn button_emit_signal_multiple_args() { let lua = Lua::new(); button::init(&lua).unwrap(); lua.globals().set("a_button", Button::new(&lua, lua.create_table().unwrap()).unwrap()) .unwrap(); lua.eval(r#" assert(a_button.button == 0) a_button:connect_signal("test", function(button, num) button.button = num end) a_button:emit_signal("test", 5) assert(a_button.button == 5) a_button:emit_signal("test", 0) assert(a_button.button == 0) "#, None).unwrap() } #[test] fn button_modifiers_test() { use rustwlc::*; use self::button::Button; use self::object::Objectable; let lua = Lua::new(); button::init(&lua).unwrap(); lua.globals().set("a_button", Button::new(&lua, lua.create_table().unwrap()).unwrap()) .unwrap(); let button = Button::cast(lua.globals().get::<_, AnyUserData>("a_button") .unwrap().into()).unwrap(); assert_eq!(button.modifiers().unwrap(), KeyMod::empty()); lua.eval::<()>(r#" a_button.modifiers = { "Caps" } "#, None).unwrap(); assert_eq!(button.modifiers().unwrap(), MOD_CAPS); } #[test] fn button_multiple_modifiers_test() { use rustwlc::*; use self::button::Button; use self::object::Objectable; let lua = Lua::new(); button::init(&lua).unwrap(); lua.globals().set("a_button", Button::new(&lua, lua.create_table().unwrap()).unwrap()) .unwrap(); let button = Button::cast(lua.globals().get::<_, AnyUserData>("a_button") .unwrap().into()).unwrap(); assert_eq!(button.modifiers().unwrap(), KeyMod::empty()); lua.eval::<()>(r#" a_button.modifiers = { "Caps", "Mod2" } "#, None).unwrap(); assert_eq!(button.modifiers().unwrap(), MOD_CAPS | MOD_MOD2); } #[test] /// Tests that setting the button index property updates the /// callback for all instances of button fn button_index_property() { let lua = Lua::new(); button::init(&lua).unwrap(); lua.globals().set("a_button", Button::new(&lua, lua.create_table().unwrap()).unwrap()) .unwrap(); lua.eval::<()>(r#" hit = false button.set_index_miss_handler(function(button) hit = true return 5 end) assert(not hit) a = button.button assert(a ~= 5) assert(not hit) a = a_button.aoeu assert(hit) assert(a == 5) a = nil hit = false a = button{}.aoeu assert(hit) assert(a == 5) "#, None).unwrap() } #[test] fn button_modifiers_signal_test() { let lua = Lua::new(); button::init(&lua).unwrap(); lua.eval::<()>(r#" a_button = button{} hit = false a_button:connect_signal("property::modifiers", function(button) hit = true end) a_button:emit_signal("property::modifiers") assert(hit) hit = false assert(not hit) a_button.button = nil assert(not hit) a_button.modifiers = { "Caps", "Mod2" } assert(hit) "#, None).unwrap() } #[test] fn button_button_signal_test() { let lua = Lua::new(); button::init(&lua).unwrap(); lua.eval::<()>(r#" a_button = button{} hit = false a_button:connect_signal("property::button", function(button) hit = true end) a_button:emit_signal("property::button") assert(hit) hit = false assert(not hit) a_button.button = nil assert(hit) "#, None).unwrap() } #[test] fn button_test_valid() { let lua = Lua::new(); button::init(&lua).unwrap(); lua.eval::<()>(r#" a_button = button{} assert(a_button.valid) "#, None).unwrap(); } }
/* Project Euler Problem 15: Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner. https://projecteuler.net/project/images/p015.gif How many such routes are there through a 20×20 grid? */ fn main() { let s = 20; let mut n: i64 = 1; for i in 0..20 { n *= 2*s - i; n /= i + 1; } println!("{:?}", n); } // I cheated. :(
use crate::{self as basic_token, Config, Error}; use frame_support::{assert_noop, assert_ok, construct_runtime, parameter_types}; use frame_system as system; use sp_core::H256; use sp_io::TestExternalities; use sp_runtime::{ testing::Header, traits::{BlakeTwo256, IdentityLookup}, }; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic<TestRuntime>; type Block = frame_system::mocking::MockBlock<TestRuntime>; construct_runtime!( pub enum TestRuntime where Block = Block, NodeBlock = Block, UncheckedExtrinsic = UncheckedExtrinsic, { System: frame_system::{Module, Call, Config, Storage, Event<T>}, BasicToken: basic_token::{Module, Call, Storage, Event<T>}, } ); parameter_types! { pub const BlockHashCount: u64 = 250; pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights::simple_max(1024); } impl frame_system::Config for TestRuntime { type BaseCallFilter = (); type BlockWeights = (); type BlockLength = (); type Origin = Origin; type Index = u64; type Call = Call; type BlockNumber = u64; type Hash = H256; type Hashing = BlakeTwo256; type AccountId = u64; type Lookup = IdentityLookup<Self::AccountId>; type Header = Header; type Event = (); type BlockHashCount = BlockHashCount; type DbWeight = (); type Version = (); type PalletInfo = PalletInfo; type AccountData = (); type OnNewAccount = (); type OnKilledAccount = (); type SystemWeightInfo = (); type SS58Prefix = (); } impl Config for TestRuntime { type Event = (); } struct ExternalityBuilder; impl ExternalityBuilder { pub fn build() -> TestExternalities { let storage = system::GenesisConfig::default() .build_storage::<TestRuntime>() .unwrap(); TestExternalities::from(storage) } } #[test] fn init_works() { ExternalityBuilder::build().execute_with(|| { assert_ok!(BasicToken::init(Origin::signed(1))); assert_eq!(BasicToken::get_balance(1), 21000000); }) } #[test] fn cant_double_init() { ExternalityBuilder::build().execute_with(|| { assert_ok!(BasicToken::init(Origin::signed(1))); assert_noop!( BasicToken::init(Origin::signed(1)), Error::<TestRuntime>::AlreadyInitialized ); }) } #[test] fn transfer_works() { ExternalityBuilder::build().execute_with(|| { assert_ok!(BasicToken::init(Origin::signed(1))); // Transfer 100 tokens from user 1 to user 2 assert_ok!(BasicToken::transfer(Origin::signed(1), 2, 100)); assert_eq!(BasicToken::get_balance(1), 20999900); assert_eq!(BasicToken::get_balance(2), 100); }) } #[test] fn cant_spend_more_than_you_have() { ExternalityBuilder::build().execute_with(|| { assert_ok!(BasicToken::init(Origin::signed(1))); assert_noop!( BasicToken::transfer(Origin::signed(1), 2, 21000001), Error::<TestRuntime>::InsufficientFunds ); }) }
use octocrab::{self, models::Repository, Octocrab, Page}; use serde_json::Value; fn build_octocrab() -> Octocrab { let access_token = std::env::var("GITHUB_PERSONAL_ACCESS_TOKEN") .expect("GITHUB_PERSONAL_ACCESS_TOKEN env var must be set"); Octocrab::builder() .personal_token(access_token) .build() .expect("Failed to build Octocrab") } async fn find_org_repo(octo: &Octocrab, organization: &str, repo_name: &str) -> Option<Repository> { match octo.orgs(organization).list_repos().send().await { Ok(p) => find_repo_in_pages(octo, p, repo_name).await, Err(e) => { eprintln!("Error: {}", e); None } } } async fn check_codeowners(octo: &Octocrab, org: &str) { let mut repo_page = match octo.orgs(org).list_repos().send().await { Ok(p) => p, Err(e) => { eprintln!("Error: {}", e); return; } }; loop { for repo in repo_page.items.iter() { println!("{}", repo.name); match get_content(octo, repo, "CODEOWNERS").await { Ok(Some(s)) => { let mut res: Vec<String> = vec![]; for line in s.split("\\n") { let decoded = base64::decode(line).unwrap(); let owner = std::str::from_utf8(&decoded).unwrap(); res.push(owner.to_string()); } println!("codeowners:\n{}", res.join("")); } Ok(None) => { println!("No codeowner"); } Err(s) => { eprintln!("Error {}", s); continue; } }; println!(); } if let Some(p) = octo.get_page(&repo_page.next).await.unwrap() { repo_page = p; } else { return; } } } async fn find_repo_in_pages( octo: &Octocrab, page: Page<Repository>, repo_name: &str, ) -> Option<Repository> { let mut repo_page = page; loop { let mut res = None; for repo in repo_page.items { if repo.name == repo_name || repo.full_name == repo_name { res = Some(repo); break; } } if res.is_some() { return res; } else if let Some(p) = octo.get_page(&repo_page.next).await.unwrap() { repo_page = p; } else { return None; } } } use std::collections::hash_map::HashMap; async fn get_content( octo: &Octocrab, repo: &Repository, path: &str, ) -> Result<Option<String>, String> { let h: HashMap<String, String> = HashMap::new(); match repo.contents_url.join(path) { Ok(content_url) => octo ._get(content_url, Some(&h)) .await .unwrap() .json() .await .map(|resp: Value| match resp["content"].to_string().trim() { "null" => None, s => Some( s.trim_start_matches('\"') .trim_end_matches('\"') .to_string(), ), }) .map_err(|e| e.to_string()), Err(e) => Err(e.to_string()), } } #[tokio::main] async fn main() { dotenv::dotenv().ok(); let octo = build_octocrab(); check_codeowners(&octo, "<some-org-here>").await; println!("Searching for repo."); let r = find_org_repo(&octo, "<some-org-here>", "<some-repo-name-here>").await; println!("Found: {:?}", r); println!("Searching for non-existent repo."); let r2 = find_org_repo(&octo, "<some-org-here>", "this_does_not_exist").await; println!("Found: {:?}", r2); }
// 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 { failure::{Error, ResultExt}, fuchsia_async as fasync, futures::Future, std::io::Write, }; #[macro_use] pub mod expect; // Test harnesses pub mod control; pub mod emulator; pub mod host_driver; pub mod low_energy_central; pub mod low_energy_peripheral; pub mod profile; /// Trait for a Harness that we can run tests with pub trait TestHarness: Sized { fn run_with_harness<F, Fut>(test_func: F) -> Result<(), Error> where F: FnOnce(Self) -> Fut, Fut: Future<Output = Result<(), Error>>; } pub fn run_test<F, H, Fut>(test_func: F) -> Result<(), Error> where F: FnOnce(H) -> Fut, Fut: Future<Output = Result<(), Error>>, H: TestHarness, { let result = H::run_with_harness(test_func); if let Err(err) = &result { println!("\x1b[31mFAILED\x1b[0m"); println!("Error running test: {}", err); } else { println!("\x1b[32mPASSED\x1b[0m"); } result } /// Trait for a Harness that we can run tests with impl TestHarness for () { fn run_with_harness<F, Fut>(test_func: F) -> Result<(), Error> where F: FnOnce(Self) -> Fut, Fut: Future<Output = Result<(), Error>>, { let mut executor = fasync::Executor::new().context("error creating event loop")?; executor.run_singlethreaded(test_func(())) } } pub fn print_test_name(name: &str) { print!(" {}...", name); std::io::stdout().flush().unwrap(); } // Prints out the test name and runs the test. macro_rules! run_test { ($name:ident) => {{ crate::harness::print_test_name(stringify!($name)); crate::harness::run_test($name) }}; } /// Collect a Vector of Results into a Result of a Vector. If all results are /// `Ok`, then return `Ok` of the results. Otherwise return the first `Err`. pub fn collect_results<T, E>(results: Vec<Result<T, E>>) -> Result<Vec<T>, E> { results.into_iter().collect() } macro_rules! run_suite { ($name:tt, [$($test:ident),+]) => {{ println!(">>> Running {} tests:", $name); crate::harness::collect_results(vec![$( run_test!($test), )*])?; println!(); Ok(()) }} }
#[doc = "Reader of register ITLINE10"] pub type R = crate::R<u32, super::ITLINE10>; #[doc = "Reader of field `DMA1_CH2`"] pub type DMA1_CH2_R = crate::R<bool, bool>; #[doc = "Reader of field `DMA1_CH3`"] pub type DMA1_CH3_R = crate::R<bool, bool>; impl R { #[doc = "Bit 0 - DMA1_CH1"] #[inline(always)] pub fn dma1_ch2(&self) -> DMA1_CH2_R { DMA1_CH2_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - DMA1_CH3"] #[inline(always)] pub fn dma1_ch3(&self) -> DMA1_CH3_R { DMA1_CH3_R::new(((self.bits >> 1) & 0x01) != 0) } }
fn main() { assert_eq!(2_203_160, sum_of_multiples(10_000, &[43, 47])); } fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 { let mut res = 0; for i in 1..=10 { if i % 3 == 0 || i % 5 == 0 { res += i; } else { continue; } } }
extern crate rand; extern crate rustbox; use rand::Rng; use rustbox::{Color, RustBox}; use rustbox::Event::KeyEvent; use rustbox::Key; use std::thread; use std::fs::File; use std::time::Duration; use std::time::Instant; use std::default::Default; use std::io::prelude::*; const PROC_FREQ_HZ: u64 = 500; const CYCLE_TIME_MS: u64 = 1000 / PROC_FREQ_HZ; const RAM_SIZE: usize = 0x1000 * 2; const STACK_SIZE: usize = 16; const NUM_REGISTERS: usize = 16; const DISP_WIDTH: usize = 64; const DISP_HEIGHT: usize = 32; const PROGRAM_START: usize = 0x200; const ROM_NAME: &'static str = "roms/breakout.rom"; const TIMER_DELAY_MS: u64 = 17; const FONTS: [u8; 80] = [ 0xF0,0x90,0x90,0x90,0xF0, // 0 0x20,0x60,0x20,0x20,0x70, // 1 0xF0,0x10,0xF0,0x80,0xF0, // 2 0xF0,0x10,0xF0,0x10,0xF0, // 3 0x90,0x90,0xF0,0x10,0x10, // 4 0xF0,0x80,0xF0,0x10,0xF0, // 5 0xF0,0x80,0xF0,0x90,0xF0, // 6 0xF0,0x10,0x20,0x40,0x40, // 7 0xF0,0x90,0xF0,0x90,0xF0, // 8 0xF0,0x90,0xF0,0x10,0xF0, // 9 0xF0,0x90,0xF0,0x90,0x90, // A 0xE0,0x90,0xE0,0x90,0xE0, // B 0xF0,0x80,0x80,0x80,0xF0, // C 0xE0,0x90,0x90,0x90,0xE0, // D 0xF0,0x80,0xF0,0x80,0xF0, // E 0xF0,0x80,0xF0,0x80,0x80 // F ]; fn convert_to_16bit (high_bits: &u8, low_bits: &u8) -> u16 { (*high_bits as u16) << 8 | *low_bits as u16 } fn get_nibble(bits: &u16) -> u16 { *bits & 0x000F } fn get_byte(bits: &u16) -> u16 { *bits & 0x00FF } fn get_reg_x(op: &u16) -> usize { get_nibble(&(*op >> 8)) as usize } fn get_reg_y(op: &u16) -> usize { get_nibble(&(*op >> 4)) as usize } fn get_byte_value(op: &u16) -> u8 { get_byte(op) as u8 } fn get_jump_addr(op: &u16) -> usize { (*op & 0x0FFF) as usize } struct Core { memory: [u8; RAM_SIZE], stack: [usize; STACK_SIZE], registers: [u8; NUM_REGISTERS], pc: usize, sp: usize, i_register: usize, inputs: [u8; NUM_REGISTERS], display: [[u8; DISP_WIDTH]; DISP_HEIGHT], update_display: bool, delay_timer: u8, sound_timer: u8, timer_60_hz: Instant, } impl Core { fn new() -> Core { Core { memory: [0; RAM_SIZE], stack: [0; STACK_SIZE], registers: [0; NUM_REGISTERS], pc: PROGRAM_START, sp: 0, i_register: 0, inputs: [0; NUM_REGISTERS], display: [[0; DISP_WIDTH]; DISP_HEIGHT], update_display: false, timer_60_hz: Instant::now(), delay_timer: 0, sound_timer: 0, } } fn read_program(&mut self, rom_name: &str) { let file = File::open(rom_name).expect("File not found."); for (i, byte) in file.bytes().enumerate() { self.memory[PROGRAM_START + i] = byte.unwrap(); } } fn read_font(&mut self) { for (i, byte) in FONTS.iter().enumerate() { self.memory[i] = *byte; } } fn print_display(&self, rustbox: &RustBox) { for i in 0..DISP_HEIGHT { for j in 0..DISP_WIDTH { let pixel = self.display[i][j]; if pixel == 1 { rustbox.print(j, i, rustbox::RB_BOLD, Color::White, Color::White, "\u{2588}"); } else { rustbox.print(j, i, rustbox::RB_BOLD, Color::Black, Color::Black, "\u{2588}"); } } } rustbox.present(); } fn run_next(&mut self) { let op: u16 = convert_to_16bit(&self.memory[self.pc], &self.memory[self.pc + 1]); match op { 0x0000 ... 0x0FFF => { match get_byte(&op) { 0xE0 => self.clear_screen(), 0xEE => self.ret(), _ => self.not_implemented(op), // Ignore instruction 0nnn - SYS addr } }, 0x1000 ... 0x1FFF => { self.jump(op) }, 0x2000 ... 0x2FFF => { self.call(op) }, 0x3000 ... 0x3FFF => { self.inc_pc_eq(op) }, 0x4000 ... 0x4FFF => { self.inc_pc_ne(op) }, 0x5000 ... 0x5FF0 => { self.inc_pc_reg_eq(op) }, 0x6000 ... 0x6FFF => { self.set_register(op) }, 0x7000 ... 0x7FFF => { self.add_val_to_reg(op) } 0x8000 ... 0x8FF0 => { match get_nibble(&op) { 0x0 => self.set_reg_to_reg(op), 0x1 => self.or(op), 0x2 => self.and(op), 0x3 => self.xor(op), 0x4 => self.add(op), 0x5 => self.sub(op), 0x6 => self.shr(op), 0x7 => self.subn(op), 0xE => self.shl(op), _ => self.not_implemented(op), } }, 0x9000 ... 0x9FF0 => { self.inc_pc_reg_ne(op) }, 0xA000 ... 0xAFFF => { self.load_reg_i(op) }, 0xC000 ... 0xCFFF => { self.get_rand_byte(op) }, 0xD000 ... 0xDFFF => { self.display_sprite(op) }, 0xE000 ... 0xEFFF => { match get_byte(&op) { 0x9E => self.skip_if_pressed(op), 0xA1 => self.skip_if_not_pressed(op), _ => self.not_implemented(op), } }, 0xF000 ... 0xFFFF => { match get_byte(&op) { 0x07 => self.load_delay_timer(op), 0x33 => self.store_bcd(op), 0x15 => self.set_delay_timer(op), 0x18 => self.set_sound_timer(op), 0x1E => self.add_reg_to_i(op), 0x29 => self.set_digit_addr(op), 0x55 => self.store_registers(op), 0x65 => self.load_registers(op), _ => self.not_implemented(op), } }, _ => { self.not_implemented(op) } }; if self.timer_60_hz.elapsed() >= Duration::from_millis(TIMER_DELAY_MS) { self.timer_60_hz = Instant::now(); if self.delay_timer > 0 { self.delay_timer -= 1; } if self.sound_timer > 0 { self.sound_timer -= 1; } // Make BEEP when sound_timer > 0 - Not implemented! } } fn shl(&mut self, op: u16) { let x_reg = get_reg_x(&op); let val = self.registers[x_reg]; self.registers[0xF] = (val & 80 != 0) as u8; self.registers[x_reg] <<= 1; self.inc_pc(); } fn shr(&mut self, op: u16) { let x_reg = get_reg_x(&op); let val = self.registers[x_reg]; self.registers[0xF] = val & 1; self.registers[x_reg] >>= 1; self.inc_pc(); } fn store_registers(&mut self, op: u16) { let x_reg = get_reg_x(&op); for i in 0..x_reg+1 { self.memory[self.i_register + i] = self.registers[i]; } self.inc_pc(); } fn add_reg_to_i(&mut self, op: u16) { let x_reg = get_reg_x(&op); self.i_register += self.registers[x_reg] as usize; self.inc_pc(); } fn sub(&mut self, op: u16) { let x_reg = get_reg_x(&op); let y_reg = get_reg_y(&op); let x_term = self.registers[x_reg] as i16; let y_term = self.registers[y_reg] as i16; self.registers[0xF] = (x_term > y_term) as u8; let sum: i16 = x_term - y_term; self.registers[x_reg] = (sum & 0xFF) as u8; self.inc_pc(); } fn subn(&mut self, op: u16) { let x_reg = get_reg_x(&op); let y_reg = get_reg_y(&op); let x_term = self.registers[x_reg] as i16; let y_term = self.registers[y_reg] as i16; self.registers[0xF] = (y_term > x_term) as u8; let sum: i16 = y_term - x_term; self.registers[x_reg] = (sum & 0xFF) as u8; self.inc_pc(); } fn add(&mut self, op: u16) { let x_reg = get_reg_x(&op); let y_reg = get_reg_y(&op); let sum: u16 = self.registers[x_reg] as u16 + self.registers[y_reg] as u16 ; if sum > 255 { self.registers[0xF] = 1; } else { self.registers[0xF] = 0; } self.registers[x_reg] = (sum & 0xFF) as u8; self.inc_pc(); } fn and(&mut self, op: u16) { let x_reg = get_reg_x(&op); let y_reg = get_reg_y(&op); self.registers[x_reg] = self.registers[x_reg] & self.registers[y_reg]; self.inc_pc(); } fn or(&mut self, op: u16) { let x_reg = get_reg_x(&op); let y_reg = get_reg_y(&op); self.registers[x_reg] = self.registers[x_reg] | self.registers[y_reg]; self.inc_pc(); } fn xor(&mut self, op: u16) { let x_reg = get_reg_x(&op); let y_reg = get_reg_y(&op); self.registers[x_reg] = self.registers[x_reg] ^ self.registers[y_reg]; self.inc_pc(); } fn set_sound_timer(&mut self, op: u16) { let x_reg = get_reg_x(&op); self.sound_timer = self.registers[x_reg]; self.inc_pc(); } fn skip_if_pressed(&mut self, op: u16) { let x_reg = get_reg_x(&op); let input = self.inputs[self.registers[x_reg] as usize]; if input == 1 { self.inputs[self.registers[x_reg] as usize] = 0; self.inc_pc(); } self.inc_pc(); } fn skip_if_not_pressed(&mut self, op: u16) { let x_reg = get_reg_x(&op); let input = self.inputs[self.registers[x_reg] as usize]; if input == 0 { self.inc_pc(); } else { self.inputs[self.registers[x_reg] as usize] = 0; } self.inc_pc(); } fn get_rand_byte(&mut self, op: u16) { let x_reg = get_reg_x(&op); let bit_mask = get_byte_value(&op); let mut rng = rand::thread_rng(); let rand_val = rng.gen::<u8>(); self.registers[x_reg] = rand_val & bit_mask; self.inc_pc(); } fn set_digit_addr(&mut self, op: u16) { let x_reg = get_reg_x(&op); self.i_register = self.registers[x_reg] as usize * 5; self.inc_pc(); } fn load_registers(&mut self, op: u16) { let x_reg = get_reg_x(&op); for i in 0..x_reg+1 { self.registers[i] = self.memory[self.i_register + i]; } self.inc_pc(); } fn load_delay_timer(&mut self, op: u16) { let x_reg = get_reg_x(&op); self.registers[x_reg] = self.delay_timer; self.inc_pc(); } fn set_delay_timer(&mut self, op: u16) { let x_reg = get_reg_x(&op); self.delay_timer = self.registers[x_reg]; self.inc_pc(); } fn store_bcd(&mut self, op: u16) { let x_reg = get_reg_x(&op); let value = self.registers[x_reg]; let one_digit = value % 10; let tens_digit = value % 100 / 10; let hundreds_digit = value / 100; self.memory[self.i_register] = hundreds_digit; self.memory[self.i_register + 1] = tens_digit; self.memory[self.i_register + 2] = one_digit; self.inc_pc(); } fn ret(&mut self) { self.pc = self.stack[self.sp] as usize; self.sp -= 1; } fn jump(&mut self, op: u16) { let addr = op & 0x0FFF; self.pc = addr as usize; } fn load_reg_i(&mut self, op: u16) { self.i_register = (op & 0x0FFF) as usize; self.inc_pc(); } fn call(&mut self, op: u16) { self.inc_pc(); self.sp += 1; self.stack[self.sp] = self.pc; self.pc = get_jump_addr(&op); } fn inc_pc_reg_eq(&mut self, op: u16) { let reg_x = get_reg_x(&op); let reg_y = get_reg_y(&op); if self.registers[reg_x] == self.registers[reg_y] { self.inc_pc(); } self.inc_pc(); } fn inc_pc_reg_ne(&mut self, op: u16) { let reg_x = get_reg_x(&op); let reg_y = get_reg_y(&op); if self.registers[reg_x] != self.registers[reg_y] { self.inc_pc(); } self.inc_pc(); } fn inc_pc_eq(&mut self, op: u16) { let reg_x = get_reg_x(&op); let reg_val = self.registers[reg_x]; let op_val = get_byte_value(&op); if reg_val == op_val { self.inc_pc(); } self.inc_pc(); } fn inc_pc_ne(&mut self, op: u16) { let reg_x = get_reg_x(&op); let reg_val = self.registers[reg_x]; let op_val = get_byte_value(&op); if reg_val != op_val { self.inc_pc(); } self.inc_pc(); } fn clear_screen(&mut self) { self.display = [[0; DISP_WIDTH]; DISP_HEIGHT]; self.inc_pc(); } fn set_register(&mut self, op: u16) { let reg_x = get_reg_x(&op); let val = get_byte_value(&op); self.registers[reg_x] = val; self.inc_pc(); } fn set_reg_to_reg(&mut self, op: u16) { let reg_x = get_reg_x(&op); let reg_y = get_reg_y(&op); self.registers[reg_x] = self.registers[reg_y]; self.inc_pc(); } fn display_sprite(&mut self, op: u16) { let reg_x = get_reg_x(&op); let reg_y = get_reg_y(&op); let x_start = self.registers[reg_x] as usize; let y_start = self.registers[reg_y] as usize; self.registers[0xF] = 0; // Reset collision flag let bytes = get_nibble(&op) as usize; for i in 0..bytes { let mem_byte = self.memory[self.i_register + i]; for b in 0..8 { let old_bit = self.display[(y_start + i) % DISP_HEIGHT][(x_start + b) % DISP_WIDTH]; let new_bit = (mem_byte >> (7-b) & 1) ^ old_bit; if old_bit == 1 && new_bit == 0 { self.registers[0xF] = 1; } self.display[(y_start + i) % DISP_HEIGHT][(x_start + b) % DISP_WIDTH] = new_bit; } } self.update_display = true; self.inc_pc(); } fn add_val_to_reg(&mut self, op: u16) { let reg_x = get_reg_x(&op); let val = get_byte_value(&op) as u16; self.registers[reg_x] = (self.registers[reg_x] as u16 + val) as u8; self.inc_pc(); } fn not_implemented(&self, op: u16) { panic!("Instruction 0x{:04x} is not implemented yet.", op) } fn inc_pc(&mut self) { self.pc += 2; } } fn init_rustbox() -> RustBox { match RustBox::init(Default::default()) { Result::Ok(v) => v, Result::Err(_) => panic!("Couldn't init rustbox"), } } fn read_input(processor: &mut Core, rustbox: &RustBox) -> bool { let key_event = rustbox.peek_event(Duration::from_millis(0), false).expect("Couldn't read input"); match key_event { KeyEvent(key) => { match key { Key::Char('q') => return exit_program(rustbox), Key::Char('2') => processor.inputs[0x0] = 1, Key::Char('3') => processor.inputs[0x1] = 1, Key::Char('4') => processor.inputs[0x2] = 1, Key::Char('5') => processor.inputs[0x3] = 1, Key::Char('w') => processor.inputs[0x4] = 1, Key::Char('e') => processor.inputs[0x5] = 1, Key::Char('r') => processor.inputs[0x6] = 1, Key::Char('t') => processor.inputs[0x7] = 1, Key::Char('s') => processor.inputs[0x8] = 1, Key::Char('d') => processor.inputs[0x9] = 1, Key::Char('f') => processor.inputs[0xA] = 1, Key::Char('g') => processor.inputs[0xB] = 1, Key::Char('x') => processor.inputs[0xC] = 1, Key::Char('c') => processor.inputs[0xD] = 1, Key::Char('v') => processor.inputs[0xE] = 1, Key::Char('b') => processor.inputs[0xF] = 1, _ => {}, } } _ => {}, } true } fn exit_program(rustbox: &RustBox) -> bool { rustbox.print(0, DISP_HEIGHT, rustbox::RB_BOLD, Color::Blue, Color::Default, "q pressed, exiting program..."); rustbox.present(); thread::sleep(Duration::from_secs(1)); false } fn main() { let mut processor = Core::new(); processor.read_font(); processor.read_program(ROM_NAME); let rustbox = init_rustbox(); let mut running = true; while running { running = read_input(&mut processor, &rustbox); processor.run_next(); if processor.update_display { processor.print_display(&rustbox); processor.update_display = false; } thread::sleep(Duration::from_millis(CYCLE_TIME_MS)); } }
use super::symbol::*; use super::script_type_description::*; use futures::*; use futures::stream; use futures::executor; /// /// Represents an edit to a script /// #[derive(Clone, PartialEq, Debug)] pub enum ScriptEdit { /// Removes all inputs and scripts from the editor Clear, /// Remove the current definition of a single symbol from the editor UndefineSymbol(FloScriptSymbol), /// Specifies that a particular symbol is used for input and receives values of the specified type SetInputType(FloScriptSymbol, ScriptTypeDescription), /// Specifies that a particular symbol is used as a script, and the contents of the script that it should evaluate /// /// This script will be a streaming script. It receives any inputs as streams and produces its output as a stream. /// Streaming scripts will stall when nothing is reading from their output. Only the first script to read from the /// output is guaranteed to receive all of the symbols the script produces. SetStreamingScript(FloScriptSymbol, String), /// Specifies that a particular symbol is used as a script, and the contents of the script that it should evaluate /// /// This script will be a 'computing' script. Inputs are treated as streams of states. When this script reads one, /// the most recent symbol from the input is passed in. The value will be recomputed, producing a stream of output, /// in the event that any of the input values it previously computed change. /// /// These scripts essentially act like a cell in a spreadsheet, producing a stream of states from a set of input /// values. /// /// Nothing will be computed until the first value is 'pulled' from the resulting stream. SetComputingScript(FloScriptSymbol, String), /// Performs one or more edits in a namespace (names declared in this namespace are only visible from scripts that are /// also in that namespace) WithNamespace(FloScriptSymbol, Vec<ScriptEdit>) } /// /// The script editor provides a way to change and update a script notebook. /// pub trait FloScriptEditor : Send+Sync { /// /// Waits for edits from the specified stream and performs them as they arrive. Returns a future that indicates when the stream /// has been consumed. /// /// Multiple edits can be sent at once to the script editor if needed: if this occurs, the streams are multiplexed and they are /// performed in any order. /// fn send_edits<Edits: 'static+Send+Stream<Item=ScriptEdit, Error=()>>(&self, edits: Edits) -> Box<dyn Future<Item=(), Error=()>>; /// /// Sends a single edit to a script editor /// fn edit(&self, edit: ScriptEdit) { let edit = stream::once(Ok(edit)); let edit_task = self.send_edits(edit); executor::spawn(edit_task).wait_future().unwrap(); } /// /// Removes all scripts from the editor /// fn clear(&self) { self.edit(ScriptEdit::Clear); } /// /// Marks a symbol that has previously been declared as an input or an output symbol as undefined /// fn undefine_symbol(&self, symbol: FloScriptSymbol) { self.edit(ScriptEdit::UndefineSymbol(symbol)); } /// /// Sets the type of the data sent to a particular input symbol /// fn set_input_type<InputType: ScriptType>(&self, input_symbol: FloScriptSymbol) { self.edit(ScriptEdit::SetInputType(input_symbol, InputType::description())); } /// /// Defines a streaming script, which will produce an output stream on the specified symbol /// fn set_streaming_script(&self, output_symbol: FloScriptSymbol, script: &str) { self.edit(ScriptEdit::SetStreamingScript(output_symbol, String::from(script))); } /// /// Defines a state computing script which will produce an output stream on the specified symbol /// fn set_computing_script(&self, output_symbol: FloScriptSymbol, script: &str) { self.edit(ScriptEdit::SetComputingScript(output_symbol, String::from(script))); } }
pub use chip::arm::noop; pub use chip::arm::interrupts; #[path="../arm.rs"] mod arm; #[path="../tm4c123x/gpio.rs"] pub mod gpio; #[path="../tm4c123x/usb.rs"] pub mod usb; #[allow(non_snake_case)] #[path="../tm4c123x/rom/lib.rs"] pub mod rom; pub mod pinmap; //***************************************************************************** // // The following are defines for the base address of the memories and // peripherals. // //***************************************************************************** pub const FLASH_BASE: u32 = 0x00000000; // FLASH memory pub const SRAM_BASE: u32 = 0x20000000; // SRAM memory pub const WATCHDOG0_BASE: u32 = 0x40000000; // Watchdog0 pub const WATCHDOG1_BASE: u32 = 0x40001000; // Watchdog1 pub const GPIO_PORTA_BASE: u32 = 0x40004000; // GPIO Port A pub const GPIO_PORTB_BASE: u32 = 0x40005000; // GPIO Port B pub const GPIO_PORTC_BASE: u32 = 0x40006000; // GPIO Port C pub const GPIO_PORTD_BASE: u32 = 0x40007000; // GPIO Port D pub const SSI0_BASE: u32 = 0x40008000; // SSI0 pub const SSI1_BASE: u32 = 0x40009000; // SSI1 pub const SSI2_BASE: u32 = 0x4000A000; // SSI2 pub const SSI3_BASE: u32 = 0x4000B000; // SSI3 pub const UART0_BASE: u32 = 0x4000C000; // UART0 pub const UART1_BASE: u32 = 0x4000D000; // UART1 pub const UART2_BASE: u32 = 0x4000E000; // UART2 pub const UART3_BASE: u32 = 0x4000F000; // UART3 pub const UART4_BASE: u32 = 0x40010000; // UART4 pub const UART5_BASE: u32 = 0x40011000; // UART5 pub const UART6_BASE: u32 = 0x40012000; // UART6 pub const UART7_BASE: u32 = 0x40013000; // UART7 pub const I2C0_BASE: u32 = 0x40020000; // I2C0 pub const I2C1_BASE: u32 = 0x40021000; // I2C1 pub const I2C2_BASE: u32 = 0x40022000; // I2C2 pub const I2C3_BASE: u32 = 0x40023000; // I2C3 pub const GPIO_PORTE_BASE: u32 = 0x40024000; // GPIO Port E pub const GPIO_PORTF_BASE: u32 = 0x40025000; // GPIO Port F pub const GPIO_PORTG_BASE: u32 = 0x40026000; // GPIO Port G pub const GPIO_PORTH_BASE: u32 = 0x40027000; // GPIO Port H pub const PWM0_BASE: u32 = 0x40028000; // Pulse Width Modulator (PWM) pub const PWM1_BASE: u32 = 0x40029000; // Pulse Width Modulator (PWM) pub const QEI0_BASE: u32 = 0x4002C000; // QEI0 pub const QEI1_BASE: u32 = 0x4002D000; // QEI1 pub const TIMER0_BASE: u32 = 0x40030000; // Timer0 pub const TIMER1_BASE: u32 = 0x40031000; // Timer1 pub const TIMER2_BASE: u32 = 0x40032000; // Timer2 pub const TIMER3_BASE: u32 = 0x40033000; // Timer3 pub const TIMER4_BASE: u32 = 0x40034000; // Timer4 pub const TIMER5_BASE: u32 = 0x40035000; // Timer5 pub const WTIMER0_BASE: u32 = 0x40036000; // Wide Timer0 pub const WTIMER1_BASE: u32 = 0x40037000; // Wide Timer1 pub const ADC0_BASE: u32 = 0x40038000; // ADC0 pub const ADC1_BASE: u32 = 0x40039000; // ADC1 pub const COMP_BASE: u32 = 0x4003C000; // Analog comparators pub const GPIO_PORTJ_BASE: u32 = 0x4003D000; // GPIO Port J pub const CAN0_BASE: u32 = 0x40040000; // CAN0 pub const CAN1_BASE: u32 = 0x40041000; // CAN1 pub const WTIMER2_BASE: u32 = 0x4004C000; // Wide Timer2 pub const WTIMER3_BASE: u32 = 0x4004D000; // Wide Timer3 pub const WTIMER4_BASE: u32 = 0x4004E000; // Wide Timer4 pub const WTIMER5_BASE: u32 = 0x4004F000; // Wide Timer5 pub const USB0_BASE: u32 = 0x40050000; // USB 0 Controller pub const GPIO_PORTA_AHB_BASE: u32 = 0x40058000; // GPIO Port A (high speed) pub const GPIO_PORTB_AHB_BASE: u32 = 0x40059000; // GPIO Port B (high speed) pub const GPIO_PORTC_AHB_BASE: u32 = 0x4005A000; // GPIO Port C (high speed) pub const GPIO_PORTD_AHB_BASE: u32 = 0x4005B000; // GPIO Port D (high speed) pub const GPIO_PORTE_AHB_BASE: u32 = 0x4005C000; // GPIO Port E (high speed) pub const GPIO_PORTF_AHB_BASE: u32 = 0x4005D000; // GPIO Port F (high speed) pub const GPIO_PORTG_AHB_BASE: u32 = 0x4005E000; // GPIO Port G (high speed) pub const GPIO_PORTH_AHB_BASE: u32 = 0x4005F000; // GPIO Port H (high speed) pub const GPIO_PORTJ_AHB_BASE: u32 = 0x40060000; // GPIO Port J (high speed) pub const GPIO_PORTK_BASE: u32 = 0x40061000; // GPIO Port K pub const GPIO_PORTL_BASE: u32 = 0x40062000; // GPIO Port L pub const GPIO_PORTM_BASE: u32 = 0x40063000; // GPIO Port M pub const GPIO_PORTN_BASE: u32 = 0x40064000; // GPIO Port N pub const GPIO_PORTP_BASE: u32 = 0x40065000; // GPIO Port P pub const GPIO_PORTQ_BASE: u32 = 0x40066000; // GPIO Port Q pub const GPIO_PORTR_BASE: u32 = 0x40067000; // General-Purpose Input/Outputs // (GPIOs) pub const GPIO_PORTS_BASE: u32 = 0x40068000; // General-Purpose Input/Outputs // (GPIOs) pub const GPIO_PORTT_BASE: u32 = 0x40069000; // General-Purpose Input/Outputs // (GPIOs) pub const EEPROM_BASE: u32 = 0x400AF000; // EEPROM memory pub const ONEWIRE0_BASE: u32 = 0x400B6000; // 1-Wire Master Module pub const I2C8_BASE: u32 = 0x400B8000; // I2C8 pub const I2C9_BASE: u32 = 0x400B9000; // I2C9 pub const I2C4_BASE: u32 = 0x400C0000; // I2C4 pub const I2C5_BASE: u32 = 0x400C1000; // I2C5 pub const I2C6_BASE: u32 = 0x400C2000; // I2C6 pub const I2C7_BASE: u32 = 0x400C3000; // I2C7 pub const EPI0_BASE: u32 = 0x400D0000; // EPI0 pub const TIMER6_BASE: u32 = 0x400E0000; // General-Purpose Timers pub const TIMER7_BASE: u32 = 0x400E1000; // General-Purpose Timers pub const EMAC0_BASE: u32 = 0x400EC000; // Ethernet Controller pub const SYSEXC_BASE: u32 = 0x400F9000; // System Exception Module pub const HIB_BASE: u32 = 0x400FC000; // Hibernation Module pub const FLASH_CTRL_BASE: u32 = 0x400FD000; // FLASH Controller pub const SYSCTL_BASE: u32 = 0x400FE000; // System Control pub const UDMA_BASE: u32 = 0x400FF000; // uDMA Controller pub const CCM0_BASE: u32 = 0x44030000; // Cyclical Redundancy Check (CRC) pub const SHAMD5_BASE: u32 = 0x44034000; // SHA/MD5 Accelerator pub const AES_BASE: u32 = 0x44036000; // Advance Encryption // Hardware-Accelerated Module pub const DES_BASE: u32 = 0x44038000; // Data Encryption Standard // Accelerator (DES) pub const LCD0_BASE: u32 = 0x44050000; // LCD Controller pub const ITM_BASE: u32 = 0xE0000000; // Instrumentation Trace Macrocell pub const DWT_BASE: u32 = 0xE0001000; // Data Watchpoint and Trace pub const FPB_BASE: u32 = 0xE0002000; // FLASH Patch and Breakpoint pub const NVIC_BASE: u32 = 0xE000E000; // Nested Vectored Interrupt Ctrl pub const TPIU_BASE: u32 = 0xE0040000; // Trace Port Interface Unit
use core::alloc::{AllocError, Layout}; use core::ptr::{self, NonNull}; use crate::alloc::realloc_fallback; use crate::sys::MIN_ALIGN; #[inline] pub fn alloc(layout: Layout) -> Result<MemoryBlock, AllocError> { let layout_size = layout.size(); let ptr = if layout.align() <= MIN_ALIGN && layout.align() <= layout_size { libc::malloc(layout_size) as *mut u8 } else { libc::aligned_alloc(layout_size, layout.align()) as *mut u8 }; NonNull::new(ptr).ok_or(AllocError).map(|ptr| MemoryBlock { ptr, size: layout_size, }) } #[inline] pub fn alloc_zeroed(layout: Layout) -> Result<MemoryBlock, AllocError> { let layout_size = layout.size(); let ptr = if layout.align() <= MIN_ALIGN && layout.align() <= layout_size { libc::calloc(layout.size(), 1) as *mut u8 } else { let ptr = libc::aligned_alloc(layout_size, layout.align()) as *mut u8; if !ptr.is_null() { ptr::write_bytes(ptr, 0, layout_size); } ptr }; NonNull::new(ptr).ok_or(AllocError).map(|ptr| MemoryBlock { ptr, size: layout_size, }) } #[inline] pub unsafe fn grow( ptr: *mut u8, layout: Layout, new_size: usize, ) -> Result<MemoryBlock, AllocError> { let old_size = layout.size(); let block = self::realloc(ptr, layout, new_size)?; AllocInit::init_offset(init, block, old_size); Ok(block) } #[inline] pub unsafe fn shrink( ptr: *mut u8, layout: Layout, new_size: usize, ) -> Result<MemoryBlock, AllocError> { self::realloc(ptr, layout, new_size) } #[inline] unsafe fn realloc( ptr: *mut u8, layout: Layout, new_size: usize, ) -> Result<MemoryBlock, AllocError> { if layout.align() <= MIN_ALIGN && layout.align() <= new_size { NonNull::new(libc::realloc(ptr as *mut libc::c_void, new_size) as *mut u8) .ok_or(AllocError) .map(|ptr| MemoryBlock { ptr, size: new_size, }) } else { realloc_fallback(self, ptr, layout, new_size) } } #[inline] pub unsafe fn dealloc(ptr: *mut u8, _layout: Layout) { libc::free(ptr as *mut libc::c_void) }
#![allow(non_snake_case, non_camel_case_types, non_upper_case_globals, clashing_extern_declarations, clippy::all)] #[link(name = "windows")] extern "system" { #[cfg(feature = "Win32_Foundation")] pub fn ApplyLocalManagementSyncML(syncmlrequest: super::super::Foundation::PWSTR, syncmlresult: *mut super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn DiscoverManagementService(pszupn: super::super::Foundation::PWSTR, ppmgmtinfo: *mut *mut MANAGEMENT_SERVICE_INFO) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn DiscoverManagementServiceEx(pszupn: super::super::Foundation::PWSTR, pszdiscoveryservicecandidate: super::super::Foundation::PWSTR, ppmgmtinfo: *mut *mut MANAGEMENT_SERVICE_INFO) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn GetDeviceManagementConfigInfo(providerid: super::super::Foundation::PWSTR, configstringbufferlength: *mut u32, configstring: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; pub fn GetDeviceRegistrationInfo(deviceinformationclass: REGISTRATION_INFORMATION_CLASS, ppdeviceregistrationinfo: *mut *mut ::core::ffi::c_void) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn GetManagementAppHyperlink(cchhyperlink: u32, pszhyperlink: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn IsDeviceRegisteredWithManagement(pfisdeviceregisteredwithmanagement: *mut super::super::Foundation::BOOL, cchupn: u32, pszupn: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn IsManagementRegistrationAllowed(pfismanagementregistrationallowed: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn IsMdmUxWithoutAadAllowed(isenrollmentallowed: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn RegisterDeviceWithLocalManagement(alreadyregistered: *mut super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn RegisterDeviceWithManagement(pszupn: super::super::Foundation::PWSTR, ppszmdmserviceuri: super::super::Foundation::PWSTR, ppzsaccesstoken: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn RegisterDeviceWithManagementUsingAADCredentials(usertoken: super::super::Foundation::HANDLE) -> ::windows_sys::core::HRESULT; pub fn RegisterDeviceWithManagementUsingAADDeviceCredentials() -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn RegisterDeviceWithManagementUsingAADDeviceCredentials2(mdmapplicationid: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn SetDeviceManagementConfigInfo(providerid: super::super::Foundation::PWSTR, configstring: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn SetManagedExternally(ismanagedexternally: super::super::Foundation::BOOL) -> ::windows_sys::core::HRESULT; pub fn UnregisterDeviceWithLocalManagement() -> ::windows_sys::core::HRESULT; #[cfg(feature = "Win32_Foundation")] pub fn UnregisterDeviceWithManagement(enrollmentid: super::super::Foundation::PWSTR) -> ::windows_sys::core::HRESULT; } pub const DEVICEREGISTRATIONTYPE_MAM: u32 = 5u32; pub const DEVICEREGISTRATIONTYPE_MDM_DEVICEWIDE_WITH_AAD: u32 = 6u32; pub const DEVICEREGISTRATIONTYPE_MDM_ONLY: u32 = 0u32; pub const DEVICEREGISTRATIONTYPE_MDM_USERSPECIFIC_WITH_AAD: u32 = 13u32; pub const DEVICE_ENROLLER_FACILITY_CODE: u32 = 24u32; #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MANAGEMENT_REGISTRATION_INFO { pub fDeviceRegisteredWithManagement: super::super::Foundation::BOOL, pub dwDeviceRegistionKind: u32, pub pszUPN: super::super::Foundation::PWSTR, pub pszMDMServiceUri: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for MANAGEMENT_REGISTRATION_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for MANAGEMENT_REGISTRATION_INFO { fn clone(&self) -> Self { *self } } #[repr(C)] #[cfg(feature = "Win32_Foundation")] pub struct MANAGEMENT_SERVICE_INFO { pub pszMDMServiceUri: super::super::Foundation::PWSTR, pub pszAuthenticationUri: super::super::Foundation::PWSTR, } #[cfg(feature = "Win32_Foundation")] impl ::core::marker::Copy for MANAGEMENT_SERVICE_INFO {} #[cfg(feature = "Win32_Foundation")] impl ::core::clone::Clone for MANAGEMENT_SERVICE_INFO { fn clone(&self) -> Self { *self } } pub const MDM_REGISTRATION_FACILITY_CODE: u32 = 25u32; pub const MENROLL_E_CERTAUTH_FAILED_TO_FIND_CERT: ::windows_sys::core::HRESULT = -2145910744i32; pub const MENROLL_E_CERTPOLICY_PRIVATEKEYCREATION_FAILED: ::windows_sys::core::HRESULT = -2145910745i32; pub const MENROLL_E_CONNECTIVITY: ::windows_sys::core::HRESULT = -2145910768i32; pub const MENROLL_E_DEVICEAPREACHED: ::windows_sys::core::HRESULT = -2145910765i32; pub const MENROLL_E_DEVICECAPREACHED: ::windows_sys::core::HRESULT = -2145910765i32; pub const MENROLL_E_DEVICENOTSUPPORTED: ::windows_sys::core::HRESULT = -2145910764i32; pub const MENROLL_E_DEVICE_ALREADY_ENROLLED: ::windows_sys::core::HRESULT = -2145910774i32; pub const MENROLL_E_DEVICE_AUTHENTICATION_ERROR: ::windows_sys::core::HRESULT = -2145910782i32; pub const MENROLL_E_DEVICE_AUTHORIZATION_ERROR: ::windows_sys::core::HRESULT = -2145910781i32; pub const MENROLL_E_DEVICE_CERTIFCATEREQUEST_ERROR: ::windows_sys::core::HRESULT = -2145910780i32; pub const MENROLL_E_DEVICE_CERTIFICATEREQUEST_ERROR: ::windows_sys::core::HRESULT = -2145910780i32; pub const MENROLL_E_DEVICE_CONFIGMGRSERVER_ERROR: ::windows_sys::core::HRESULT = -2145910779i32; pub const MENROLL_E_DEVICE_INTERNALSERVICE_ERROR: ::windows_sys::core::HRESULT = -2145910778i32; pub const MENROLL_E_DEVICE_INVALIDSECURITY_ERROR: ::windows_sys::core::HRESULT = -2145910777i32; pub const MENROLL_E_DEVICE_MANAGEMENT_BLOCKED: ::windows_sys::core::HRESULT = -2145910746i32; pub const MENROLL_E_DEVICE_MESSAGE_FORMAT_ERROR: ::windows_sys::core::HRESULT = -2145910783i32; pub const MENROLL_E_DEVICE_NOT_ENROLLED: ::windows_sys::core::HRESULT = -2145910773i32; pub const MENROLL_E_DEVICE_UNKNOWN_ERROR: ::windows_sys::core::HRESULT = -2145910776i32; pub const MENROLL_E_DISCOVERY_SEC_CERT_DATE_INVALID: ::windows_sys::core::HRESULT = -2145910771i32; pub const MENROLL_E_EMPTY_MESSAGE: ::windows_sys::core::HRESULT = -2145910743i32; pub const MENROLL_E_ENROLLMENTDATAINVALID: ::windows_sys::core::HRESULT = -2145910759i32; pub const MENROLL_E_ENROLLMENT_IN_PROGRESS: ::windows_sys::core::HRESULT = -2145910775i32; pub const MENROLL_E_INMAINTENANCE: ::windows_sys::core::HRESULT = -2145910761i32; pub const MENROLL_E_INSECUREREDIRECT: ::windows_sys::core::HRESULT = -2145910758i32; pub const MENROLL_E_INVALIDSSLCERT: ::windows_sys::core::HRESULT = -2145910766i32; pub const MENROLL_E_MDM_NOT_CONFIGURED: ::windows_sys::core::HRESULT = -2145910735i32; pub const MENROLL_E_NOTELIGIBLETORENEW: ::windows_sys::core::HRESULT = -2145910762i32; pub const MENROLL_E_NOTSUPPORTED: ::windows_sys::core::HRESULT = -2145910763i32; pub const MENROLL_E_NOT_SUPPORTED: ::windows_sys::core::HRESULT = -2145910763i32; pub const MENROLL_E_PASSWORD_NEEDED: ::windows_sys::core::HRESULT = -2145910770i32; pub const MENROLL_E_PLATFORM_LICENSE_ERROR: ::windows_sys::core::HRESULT = -2145910756i32; pub const MENROLL_E_PLATFORM_UNKNOWN_ERROR: ::windows_sys::core::HRESULT = -2145910755i32; pub const MENROLL_E_PLATFORM_WRONG_STATE: ::windows_sys::core::HRESULT = -2145910757i32; pub const MENROLL_E_PROV_CSP_APPMGMT: ::windows_sys::core::HRESULT = -2145910747i32; pub const MENROLL_E_PROV_CSP_CERTSTORE: ::windows_sys::core::HRESULT = -2145910754i32; pub const MENROLL_E_PROV_CSP_DMCLIENT: ::windows_sys::core::HRESULT = -2145910752i32; pub const MENROLL_E_PROV_CSP_MISC: ::windows_sys::core::HRESULT = -2145910750i32; pub const MENROLL_E_PROV_CSP_PFW: ::windows_sys::core::HRESULT = -2145910751i32; pub const MENROLL_E_PROV_CSP_W7: ::windows_sys::core::HRESULT = -2145910753i32; pub const MENROLL_E_PROV_SSLCERTNOTFOUND: ::windows_sys::core::HRESULT = -2145910748i32; pub const MENROLL_E_PROV_UNKNOWN: ::windows_sys::core::HRESULT = -2145910749i32; pub const MENROLL_E_USERLICENSE: ::windows_sys::core::HRESULT = -2145910760i32; pub const MENROLL_E_USER_CANCELED: ::windows_sys::core::HRESULT = -2145910742i32; pub const MENROLL_E_USER_CANCELLED: ::windows_sys::core::HRESULT = -2145910736i32; pub const MENROLL_E_USER_LICENSE: ::windows_sys::core::HRESULT = -2145910760i32; pub const MENROLL_E_WAB_ERROR: ::windows_sys::core::HRESULT = -2145910769i32; pub const MREGISTER_E_DEVICE_ALREADY_REGISTERED: ::windows_sys::core::HRESULT = -2145845238i32; pub const MREGISTER_E_DEVICE_AUTHENTICATION_ERROR: ::windows_sys::core::HRESULT = -2145845246i32; pub const MREGISTER_E_DEVICE_AUTHORIZATION_ERROR: ::windows_sys::core::HRESULT = -2145845245i32; pub const MREGISTER_E_DEVICE_CERTIFCATEREQUEST_ERROR: ::windows_sys::core::HRESULT = -2145845244i32; pub const MREGISTER_E_DEVICE_CONFIGMGRSERVER_ERROR: ::windows_sys::core::HRESULT = -2145845243i32; pub const MREGISTER_E_DEVICE_INTERNALSERVICE_ERROR: ::windows_sys::core::HRESULT = -2145845242i32; pub const MREGISTER_E_DEVICE_INVALIDSECURITY_ERROR: ::windows_sys::core::HRESULT = -2145845241i32; pub const MREGISTER_E_DEVICE_MESSAGE_FORMAT_ERROR: ::windows_sys::core::HRESULT = -2145845247i32; pub const MREGISTER_E_DEVICE_NOT_AD_REGISTERED_ERROR: ::windows_sys::core::HRESULT = -2145845235i32; pub const MREGISTER_E_DEVICE_NOT_REGISTERED: ::windows_sys::core::HRESULT = -2145845237i32; pub const MREGISTER_E_DEVICE_UNKNOWN_ERROR: ::windows_sys::core::HRESULT = -2145845240i32; pub const MREGISTER_E_DISCOVERY_FAILED: ::windows_sys::core::HRESULT = -2145845234i32; pub const MREGISTER_E_DISCOVERY_REDIRECTED: ::windows_sys::core::HRESULT = -2145845236i32; pub const MREGISTER_E_REGISTRATION_IN_PROGRESS: ::windows_sys::core::HRESULT = -2145845239i32; pub type REGISTRATION_INFORMATION_CLASS = i32; pub const DeviceRegistrationBasicInfo: REGISTRATION_INFORMATION_CLASS = 1i32; pub const MaxDeviceInfoClass: REGISTRATION_INFORMATION_CLASS = 2i32;
fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let n: usize = rd.get(); let m: usize = rd.get(); let ab: Vec<(usize, usize)> = (0..m) .map(|_| { let a: usize = rd.get(); let b: usize = rd.get(); (a - 1, b - 1) }) .collect(); let mut deg = vec![0; n]; let mut g = vec![vec![]; n]; for &(a, b) in &ab { deg[a] += 1; deg[b] += 1; g[a].push(b); g[b].push(a); } let sqrt_m = (m as f64).sqrt() as usize; let mut friends = vec![vec![]; n]; for i in 0..n { friends[i] = g[i].iter().filter(|&&j| deg[j] > sqrt_m).collect(); } let mut recv = vec![0; n]; let mut sent = vec![0; n]; let mut prev = vec![0; n]; let q: usize = rd.get(); for _ in 0..q { let t: usize = rd.get(); let x: usize = rd.get(); let x = x - 1; match t { 1 => { if deg[x] <= sqrt_m { for &y in &g[x] { recv[y] += 1; } } else { sent[x] += 1; } } 2 => { let tot = recv[x] + friends[x].iter().map(|&&y| sent[y]).sum::<u64>(); println!("{}", tot - prev[x]); prev[x] = tot; } _ => unreachable!(), } } } pub struct ProconReader<R> { r: R, line: String, i: usize, } impl<R: std::io::BufRead> ProconReader<R> { pub fn new(reader: R) -> Self { Self { r: reader, line: String::new(), i: 0, } } pub fn get<T>(&mut self) -> T where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { self.skip_blanks(); assert!(self.i < self.line.len()); assert_ne!(&self.line[self.i..=self.i], " "); let line = &self.line[self.i..]; let end = line.find(' ').unwrap_or_else(|| line.len()); let s = &line[..end]; self.i += end; s.parse() .unwrap_or_else(|_| panic!("parse error `{}`", self.line)) } fn skip_blanks(&mut self) { loop { let start = self.line[self.i..].find(|ch| ch != ' '); match start { Some(j) => { self.i += j; break; } None => { self.line.clear(); self.i = 0; let num_bytes = self.r.read_line(&mut self.line).unwrap(); assert!(num_bytes > 0, "reached EOF :("); self.line = self.line.trim_end_matches(&['\r', '\n'][..]).to_string(); } } } } pub fn get_vec<T>(&mut self, n: usize) -> Vec<T> where T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug, { (0..n).map(|_| self.get()).collect() } }
pub mod minimum_deviation; pub mod next_permutation; pub mod vertical_traversal;
use clippy_utils::diagnostics::span_lint_and_sugg; use clippy_utils::paths; use clippy_utils::source::snippet_with_macro_callsite; use clippy_utils::ty::{is_type_diagnostic_item, is_type_ref_to_diagnostic_item}; use if_chain::if_chain; use rustc_errors::Applicability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::{declare_lint_pass, declare_tool_lint}; use rustc_span::symbol::{sym, Symbol}; declare_clippy_lint! { /// ### What it does /// Checks for usage of `libc::strlen` on a `CString` or `CStr` value, /// and suggest calling `as_bytes().len()` or `to_bytes().len()` respectively instead. /// /// ### Why is this bad? /// This avoids calling an unsafe `libc` function. /// Currently, it also avoids calculating the length. /// /// ### Example /// ```rust, ignore /// use std::ffi::CString; /// let cstring = CString::new("foo").expect("CString::new failed"); /// let len = unsafe { libc::strlen(cstring.as_ptr()) }; /// ``` /// Use instead: /// ```rust, no_run /// use std::ffi::CString; /// let cstring = CString::new("foo").expect("CString::new failed"); /// let len = cstring.as_bytes().len(); /// ``` #[clippy::version = "1.55.0"] pub STRLEN_ON_C_STRINGS, complexity, "using `libc::strlen` on a `CString` or `CStr` value, while `as_bytes().len()` or `to_bytes().len()` respectively can be used instead" } declare_lint_pass!(StrlenOnCStrings => [STRLEN_ON_C_STRINGS]); impl LateLintPass<'tcx> for StrlenOnCStrings { fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'_>) { if expr.span.from_expansion() { return; } if_chain! { if let hir::ExprKind::Call(func, [recv]) = expr.kind; if let hir::ExprKind::Path(hir::QPath::Resolved(_, path)) = func.kind; if (&paths::LIBC_STRLEN).iter().map(|x| Symbol::intern(x)).eq( path.segments.iter().map(|seg| seg.ident.name)); if let hir::ExprKind::MethodCall(path, _, args, _) = recv.kind; if args.len() == 1; if !args.iter().any(|e| e.span.from_expansion()); if path.ident.name == sym::as_ptr; then { let cstring = &args[0]; let ty = cx.typeck_results().expr_ty(cstring); let val_name = snippet_with_macro_callsite(cx, cstring.span, ".."); let sugg = if is_type_diagnostic_item(cx, ty, sym::cstring_type){ format!("{}.as_bytes().len()", val_name) } else if is_type_ref_to_diagnostic_item(cx, ty, sym::CStr){ format!("{}.to_bytes().len()", val_name) } else { return; }; span_lint_and_sugg( cx, STRLEN_ON_C_STRINGS, expr.span, "using `libc::strlen` on a `CString` or `CStr` value", "try this (you might also need to get rid of `unsafe` block in some cases):", sugg, Applicability::Unspecified // Sometimes unnecessary `unsafe` block ); } } } }
use std::fmt::{self, Display, Formatter}; use crate::type_info::TypeInfo; #[cfg(feature = "postgres")] use crate::postgres::PgTypeInfo; #[cfg(feature = "mysql")] use crate::mysql::MySqlTypeInfo; #[cfg(feature = "sqlite")] use crate::sqlite::SqliteTypeInfo; #[cfg(feature = "mssql")] use crate::mssql::MssqlTypeInfo; #[derive(Debug, Clone, PartialEq)] pub struct AnyTypeInfo(pub(crate) AnyTypeInfoKind); #[derive(Debug, Clone, PartialEq)] pub(crate) enum AnyTypeInfoKind { #[cfg(feature = "postgres")] Postgres(PgTypeInfo), #[cfg(feature = "mysql")] MySql(MySqlTypeInfo), #[cfg(feature = "sqlite")] Sqlite(SqliteTypeInfo), #[cfg(feature = "mssql")] Mssql(MssqlTypeInfo), } impl TypeInfo for AnyTypeInfo { fn is_null(&self) -> bool { match &self.0 { #[cfg(feature = "postgres")] AnyTypeInfoKind::Postgres(ty) => ty.is_null(), #[cfg(feature = "mysql")] AnyTypeInfoKind::MySql(ty) => ty.is_null(), #[cfg(feature = "sqlite")] AnyTypeInfoKind::Sqlite(ty) => ty.is_null(), #[cfg(feature = "mssql")] AnyTypeInfoKind::Mssql(ty) => ty.is_null(), } } fn name(&self) -> &str { match &self.0 { #[cfg(feature = "postgres")] AnyTypeInfoKind::Postgres(ty) => ty.name(), #[cfg(feature = "mysql")] AnyTypeInfoKind::MySql(ty) => ty.name(), #[cfg(feature = "sqlite")] AnyTypeInfoKind::Sqlite(ty) => ty.name(), #[cfg(feature = "mssql")] AnyTypeInfoKind::Mssql(ty) => ty.name(), } } } impl Display for AnyTypeInfo { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { match &self.0 { #[cfg(feature = "postgres")] AnyTypeInfoKind::Postgres(ty) => ty.fmt(f), #[cfg(feature = "mysql")] AnyTypeInfoKind::MySql(ty) => ty.fmt(f), #[cfg(feature = "sqlite")] AnyTypeInfoKind::Sqlite(ty) => ty.fmt(f), #[cfg(feature = "mssql")] AnyTypeInfoKind::Mssql(ty) => ty.fmt(f), } } }
use std::collections::HashMap; use std::fs::read_dir; use std::fs::File; use std::io; use std::io::prelude::*; use std::path::Path; use fluent_bundle::{FluentBundle, FluentResource, FluentValue}; use fluent_locale::negotiate_languages; pub trait Loader { fn lookup( &self, lang: &str, text_id: &str, args: Option<&HashMap<&str, FluentValue>>, ) -> String; } #[macro_export] macro_rules! simple_loader { ($constructor:ident, $location:expr, $fallback:expr) => { use $crate::loader::{build_resources, build_bundles, build_fallbacks, SimpleLoader, load_core_resource}; use std::collections::HashMap; use $crate::fluent_bundle::{FluentBundle, FluentResource, FluentValue}; $crate::lazy_static::lazy_static! { static ref RESOURCES: HashMap<String, Vec<FluentResource>> = build_resources($location); static ref BUNDLES: HashMap<String, FluentBundle<'static>> = build_bundles(&&RESOURCES, None); static ref LOCALES: Vec<&'static str> = RESOURCES.iter().map(|(l, _)| &**l).collect(); static ref FALLBACKS: HashMap<String, Vec<String>> = build_fallbacks(&LOCALES); } pub fn $constructor() -> SimpleLoader { SimpleLoader::new(&*BUNDLES, &*FALLBACKS, $fallback.into()) } }; ($constructor:ident, $location:expr, $fallback:expr, core: $core:expr) => { use $crate::loader::{build_resources, build_bundles, build_fallbacks, SimpleLoader, load_core_resource}; use std::collections::HashMap; use $crate::fluent_bundle::{FluentBundle, FluentResource, FluentValue}; $crate::lazy_static::lazy_static! { static ref CORE_RESOURCE: FluentResource = load_core_resource($core); static ref RESOURCES: HashMap<String, Vec<FluentResource>> = build_resources($location); static ref BUNDLES: HashMap<String, FluentBundle<'static>> = build_bundles(&*RESOURCES, Some(&CORE_RESOURCE)); static ref LOCALES: Vec<&'static str> = RESOURCES.iter().map(|(l, _)| &**l).collect(); static ref FALLBACKS: HashMap<String, Vec<String>> = build_fallbacks(&LOCALES); } pub fn $constructor() -> SimpleLoader { SimpleLoader::new(&*BUNDLES, &*FALLBACKS, $fallback.into()) } }; } pub fn build_fallbacks(locales: &[&str]) -> HashMap<String, Vec<String>> { locales .iter() .map(|locale| { ( locale.to_string(), negotiate_languages( &[locale], &locales, None, &fluent_locale::NegotiationStrategy::Filtering, ) .into_iter() .map(|x| x.to_string()) .collect(), ) }) .collect() } pub struct SimpleLoader { bundles: &'static HashMap<String, FluentBundle<'static>>, fallbacks: &'static HashMap<String, Vec<String>>, fallback: String, } impl SimpleLoader { pub fn new( bundles: &'static HashMap<String, FluentBundle<'static>>, fallbacks: &'static HashMap<String, Vec<String>>, fallback: String, ) -> Self { Self { bundles, fallbacks, fallback, } } pub fn lookup_single_language( &self, lang: &str, text_id: &str, args: Option<&HashMap<&str, FluentValue>>, ) -> Option<String> { if let Some(bundle) = self.bundles.get(lang) { if bundle.has_message(text_id) { let (value, _errors) = bundle.format(text_id, args).unwrap_or_else(|| { panic!( "Failed to format a message for locale {} and id {}", lang, text_id ) }); Some(value) } else { None } } else { panic!("Unknown language {}", lang) } } // Don't fall back to English pub fn lookup_no_english( &self, lang: &str, text_id: &str, args: Option<&HashMap<&str, FluentValue>>, ) -> Option<String> { for l in self.fallbacks.get(lang).expect("language not found") { if let Some(val) = self.lookup_single_language(l, text_id, args) { return Some(val); } } None } } impl Loader for SimpleLoader { // Traverse the fallback chain, fn lookup( &self, lang: &str, text_id: &str, args: Option<&HashMap<&str, FluentValue>>, ) -> String { for l in self.fallbacks.get(lang).expect("language not found") { if let Some(val) = self.lookup_single_language(l, text_id, args) { return val; } } if lang != self.fallback { if let Some(val) = self.lookup_single_language(&self.fallback, text_id, args) { return val; } } format!("Unknown localization {}", text_id) } } fn read_from_file<P: AsRef<Path>>(filename: P) -> io::Result<FluentResource> { let mut file = File::open(filename)?; let mut string = String::new(); file.read_to_string(&mut string)?; Ok(FluentResource::try_new(string).expect("File did not parse!")) } fn read_from_dir<P: AsRef<Path>>(dirname: P) -> io::Result<Vec<FluentResource>> { let mut result = Vec::new(); for dir_entry in read_dir(dirname)? { let entry = dir_entry?; let resource = read_from_file(entry.path())?; result.push(resource); } Ok(result) } pub fn create_bundle( lang: &str, resources: &'static Vec<FluentResource>, core_resource: Option<&'static FluentResource>, ) -> FluentBundle<'static> { let mut bundle = FluentBundle::new(&[lang]); if let Some(core) = core_resource { bundle .add_resource(core) .expect("Failed to add core resource to bundle"); } for res in resources { bundle .add_resource(res) .expect("Failed to add FTL resources to the bundle."); } bundle .add_function("EMAIL", |values, _named| { let email = match *values.get(0)?.as_ref()? { FluentValue::String(ref s) => s, _ => return None, }; Some(FluentValue::String(format!( "<a href='mailto:{0}' lang='en-US'>{0}</a>", email ))) }) .expect("could not add function"); bundle .add_function("ENGLISH", |values, _named| { let text = match *values.get(0)?.as_ref()? { FluentValue::String(ref s) => s, _ => return None, }; Some(FluentValue::String(format!( "<span lang='en-US'>{0}</span>", text ))) }) .expect("could not add function"); bundle } pub fn build_resources(dir: &str) -> HashMap<String, Vec<FluentResource>> { let mut all_resources = HashMap::new(); let entries = read_dir(dir).unwrap(); for entry in entries { let entry = entry.unwrap(); if entry.file_type().unwrap().is_dir() { if let Ok(lang) = entry.file_name().into_string() { let resources = read_from_dir(entry.path()).unwrap(); all_resources.insert(lang, resources); } } } all_resources } pub fn build_bundles( resources: &'static HashMap<String, Vec<FluentResource>>, core_resource: Option<&'static FluentResource>, ) -> HashMap<String, FluentBundle<'static>> { let mut bundles = HashMap::new(); for (ref k, ref v) in &*resources { bundles.insert(k.to_string(), create_bundle(&k, &v, core_resource)); } bundles } pub fn load_core_resource(path: &str) -> FluentResource { read_from_file(path).expect("cannot find core resource") }
#[macro_use] extern crate quicli; use quicli::prelude::*; // Add cool slogan for your app here, e.g.: /// Get first n lines of a file #[derive(Debug, StructOpt)] struct Cli { // Add a CLI argument `--count`/-n` that defaults to 3, and has this help text: /// How many lines to get #[structopt(long = "git", short = "g")] git: String, // Add a positional argument that the user has to supply: /// Pass many times for more log output #[structopt(long = "verbose", short = "v", parse(from_occurrences))] verbosity: u8, } main!(|args: Cli, log_level: verbosity| { println!("{}", &args.git); });
extern crate communicator; use communicator::_trait::hello_trait; use communicator::advanced_features::advanced_features; use communicator::collection; use communicator::concurrency::hello_rust_thread; use communicator::functional::hello_closures; use communicator::functional::hello_iterator; use communicator::generics::hello_generics; use communicator::lifetime::hello_lifetime; use communicator::minigrep::Config; use communicator::oop::oop_demo; use communicator::panic::hello_panic; use communicator::patterns::pattern_syntax; use communicator::smart_pointer::hello_smart_pointer; use communicator::web_server::web_start; use std::env; use std::error::Error; use std::process; #[allow(unused_variables)] fn main() { // crate // hello_crate(); // collection // vector // collection::hello_vector(); // string // collection::hello_string(); // hash_map // collection::hello_hash_map(); // panic // hello_panic().expect("o_o"); // generics // hello_generics(); // trait // hello_trait(); // lifetime // hello_lifetime(); // mini_grep // mini_grep(); // functional // closure // hello_closures(); // iterator // hello_iterator(); // smart pointer // hello_smart_pointer(); // rust thread // hello_rust_thread(); // oop // oop_demo(); // patterns // pattern_syntax(); // advance features // advanced_features(); // web server web_start(); } #[allow(unused_variables)] pub fn hello_crate() { communicator::client::connect(); } #[allow(unused_variables)] pub fn mini_grep() { // let args: Vec<String> = env::args().collect(); // let config = communicator::minigrep::Config::new(&args).unwrap_or_else(|err| { // eprintln!("problem parsing arguments: {}", err); // process::exit(1); // }); let config = Config::new(env::args()).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {}", err); process::exit(1); }); if let Err(e) = communicator::minigrep::mini_grep_run(config) { eprintln!("app error: {}", e); process::exit(1); }; }
extern crate rand; use rand::Rng; use super::Point; use super::Direction; use super::MazeGenerator; use super::super::grid::Grid; pub struct RecursiveBacktracker; impl MazeGenerator for RecursiveBacktracker { fn generate<T: Grid>(grid: &mut T) { let (width, height) = grid.get_dimensions(); if width == 0 || height == 0 { return; } let x = rand::thread_rng().gen_range(0, width); let y = rand::thread_rng().gen_range(0, height); let mut stack = vec![(x, y)]; while !stack.is_empty() { let tile = stack[stack.len() - 1]; let dir = get_direction(grid, (tile.0, tile.1)); if let Direction::Stay = dir { stack.pop(); continue; } stack.push(grid.carve_path(tile, dir).expect("Failed to carve path")); } } } fn get_direction<T: Grid>(grid: &T, (x, y): Point) -> Direction { let mut available = [Direction::Stay; 4]; let mut count = 0; let (width, height) = grid.get_dimensions(); // Check up if (y < height - 1) && (grid.get_tile_data((x, y + 1)) .expect("Invalid tile") .is_available()) { available[count] = Direction::Up; count += 1; } // Check down if (y > 0) && (grid.get_tile_data((x, y - 1)) .expect("Invalid tile") .is_available()) { available[count] = Direction::Down; count += 1; } // Check left if (x > 0) && (grid.get_tile_data((x - 1, y)) .expect("Invalid tile") .is_available()) { available[count] = Direction::Left; count += 1; } // Check right if (x < width - 1) && (grid.get_tile_data((x + 1, y)) .expect("Invalid tile") .is_available()) { available[count] = Direction::Right; count += 1; } if count > 0 { // Generate a number between 0 and count let ind = rand::thread_rng().gen_range(0, count); available[ind] } else { Direction::Stay } }
use projecteuler::helper; fn main() { //dbg!(solve(17, 6).len()); helper::time_it( || { solve(8, 4); }, 10_000, ); } //returns the solutions for s-gonal and d digits fn solve(s: usize, d: usize) -> Vec<Vec<(u16, u16)>> { let numbers: Vec<_> = (3..s + 1) .rev() .map(|s| create_numbers(|n| psn(s, n), d)) .collect(); //dbg!(&numbers); //for i in 0..numbers.len() { // dbg!(numbers[i].len()); //} let mut solutions = vec![]; let mut current = vec![]; let mut used = vec![false; numbers.len()]; recursion(&mut current, &mut used, &numbers, &mut solutions); solutions } fn recursion( current: &mut Vec<(u16, u16)>, used: &mut Vec<bool>, numbers: &[Vec<(u16, u16)>], solutions: &mut Vec<Vec<(u16, u16)>>, ) { for i in 0..if current.len() == 0 { 1 } else { numbers.len() } { if used[i] { continue; } //make a binary search for the next possible starting number let start = { if current.len() == 0 { 0 } else { match numbers[i].binary_search_by_key(&current[current.len() - 1].1, |(a, _b)| *a) { Ok(mut some_start) => { while some_start > 0 && current[current.len() - 1].1 == numbers[i][some_start - 1].0 { some_start -= 1; } some_start } Err(_) => continue, } } }; used[i] = true; for j in start..numbers[i].len() { let new = numbers[i][j]; //from the binary search we know that once we encounter an invalid one, the rest will be invalid too. if current.len() > 0 && current[current.len() - 1].1 != new.0 { break; } if current.len() == 0 || current[current.len() - 1].1 == new.0 && (current.len() < numbers.len() - 1 || current[0].0 == new.1) { current.push(new); if current.len() == numbers.len() { solutions.push(current.clone()); } else { recursion(current, used, numbers, solutions); } current.pop(); } } used[i] = false; } } fn create_numbers<F: Fn(usize) -> usize>(f: F, d: usize) -> Vec<(u16, u16)> { let min = 10usize.pow(d as u32 - 1) - 1; let max = 10usize.pow(d as u32) - 1; let div = 10usize.pow(d as u32 / 2); let min_b = 10u16.pow(d as u32 / 2 - 1); //the second part cant start with a zero (1..) .map(|n| f(n)) .filter(|n| *n > min) .take_while(|n| *n <= max) .map(|n| ((n / div) as u16, (n % div) as u16)) .filter(|(_a, b)| *b >= min_b) .collect() } fn psn(s: usize, n: usize) -> usize { ((s - 2) * (n * n) + 4 * n - s * n) / 2 }
extern crate arrayvec; extern crate clap; extern crate hyper; extern crate screenprints; extern crate stopwatch; extern crate time; extern crate url; mod measured_response; mod summary; use measured_response::MeasuredResponse; use summary::Summary; use std::io::{stdout, Write}; use std::str::FromStr; use std::time::Duration; use clap::{App, Arg}; use screenprints::Printer; use url::Url; const DEFAULT_INTERVAL_IN_SECONDS: u64 = 10; const DEFAULT_TIMEOUT_IN_SECONDS: u64 = 10; const DEFAULT_REDIRECT_LIMIT_COUNT: u8 = 5; struct ApplicationConfiguration { url: String, interval: Duration, timeout: Duration, redirect_limit: u8, } impl ApplicationConfiguration { fn next_request_in(&self, time_spent: Duration) -> Duration { if self.interval >= time_spent { self.interval - time_spent } else { Duration::new(0, 0) } } } fn url_validator(arg: String) -> Result<(), String> { match Url::parse(&arg) { Ok(_) => Ok(()), Err(_) => { Err("The url argument must be complete, specifying the protocol as well. For example: \ http://example.com" .to_string()) } } } fn main() { let application_configuration = parse_arguments(); let mut summary = Summary::new(); let mut printer = Printer::new(stdout(), Duration::from_millis(10)); loop { let measured_response = MeasuredResponse::request(&application_configuration.url, application_configuration.timeout, application_configuration.redirect_limit); let next_tick = application_configuration.next_request_in(measured_response.std_time()); summary.push(measured_response); display(&summary, &mut printer); std::thread::sleep(next_tick); } } fn display(summary: &Summary, printer: &mut Write) { let requests = summary.last_requests() .iter() .map(|req| { format!("{} -> Status: {}, Response Time: {}", req.url(), req.status, req.time) }) .collect::<Vec<_>>(); let _ = write!(printer, "Total\r\nRequests: {} - Success: {}/{:.1}% - Failure: {}/{:.1}%\r\n\r\nLast \ requests\r\n{}", summary.total_requests, summary.total_success(), summary.total_percentual_success(), summary.total_failure(), summary.total_percentual_failure(), requests.join("\r\n")); } fn parse_arguments() -> ApplicationConfiguration { let interval_help_message = format!("The interval in seconds between requests, default to {} \ seconds", DEFAULT_INTERVAL_IN_SECONDS); let timeout_help_message = format!("The timeout in seconds to wait for a response, default \ to {} seconds", DEFAULT_TIMEOUT_IN_SECONDS); let redirect_limit_message = format!("The amount of redirects to follow, defaults to {} \ redirects", DEFAULT_REDIRECT_LIMIT_COUNT); let cli_arguments = App::new("heartbeat") .version("v0.1.1-beta") .arg(Arg::with_name("interval") .long("interval") .short("i") .takes_value(true) .value_name("INTERVAL") .help(&interval_help_message)) .arg(Arg::with_name("timeout") .long("timeout") .short("t") .takes_value(true) .value_name("TIMEOUT") .help(&timeout_help_message)) .arg(Arg::with_name("redirect_limit") .long("follow") .short("F") .takes_value(true) .value_name("FOLLOW COUNT") .help(&redirect_limit_message)) .arg(Arg::with_name("url") .long("url") .index(1) .takes_value(true) .value_name("URL") .help("The URL to monitor") .validator(url_validator) .required(true)) .get_matches(); let interval_argument = cli_arguments.value_of("interval") .map(|arg| u64::from_str(arg).expect("The interval argument requires a number")); let timeout_argument = cli_arguments.value_of("timeout") .map(|arg| u64::from_str(arg).expect("The timeout argument requires a number")); let redirect_limit_argument = cli_arguments.value_of("redirect_limit") .map(|arg| u8::from_str(arg).expect("The redirect limit requires a number")); ApplicationConfiguration { url: cli_arguments.value_of("url").expect("URL not present").to_string(), interval: Duration::from_secs(interval_argument.unwrap_or(DEFAULT_INTERVAL_IN_SECONDS)), timeout: Duration::from_secs(timeout_argument.unwrap_or(DEFAULT_TIMEOUT_IN_SECONDS)), redirect_limit: redirect_limit_argument.unwrap_or(DEFAULT_REDIRECT_LIMIT_COUNT), } } #[test] fn next_tick_should_remove_the_time_spent_on_the_request() { let configuration = ApplicationConfiguration { url: Default::default(), interval: Duration::from_secs(3), timeout: Duration::from_secs(0), redirect_limit: 1, }; let time_spent = Duration::from_secs(1); assert_eq!(configuration.next_request_in(time_spent), Duration::from_secs(2)); } #[test] fn next_tick_should_be_right_away_when_more_time_is_spent() { let configuration = ApplicationConfiguration { url: Default::default(), interval: Duration::from_secs(3), timeout: Duration::from_secs(0), redirect_limit: 1, }; let time_spent = Duration::from_secs(5); assert_eq!(configuration.next_request_in(time_spent), Duration::from_secs(0)); }
#[doc = "Reader of register ULPIVBUSCTL"] pub type R = crate::R<u8, super::ULPIVBUSCTL>; #[doc = "Writer for register ULPIVBUSCTL"] pub type W = crate::W<u8, super::ULPIVBUSCTL>; #[doc = "Register ULPIVBUSCTL `reset()`'s with value 0"] impl crate::ResetValue for super::ULPIVBUSCTL { type Type = u8; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `USEEXTVBUS`"] pub type USEEXTVBUS_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USEEXTVBUS`"] pub struct USEEXTVBUS_W<'a> { w: &'a mut W, } impl<'a> USEEXTVBUS_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 u8) & 0x01); self.w } } #[doc = "Reader of field `USEEXTVBUSIND`"] pub type USEEXTVBUSIND_R = crate::R<bool, bool>; #[doc = "Write proxy for field `USEEXTVBUSIND`"] pub struct USEEXTVBUSIND_W<'a> { w: &'a mut W, } impl<'a> USEEXTVBUSIND_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 u8) & 0x01) << 1); self.w } } impl R { #[doc = "Bit 0 - Use External VBUS"] #[inline(always)] pub fn useextvbus(&self) -> USEEXTVBUS_R { USEEXTVBUS_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 1 - Use External VBUS Indicator"] #[inline(always)] pub fn useextvbusind(&self) -> USEEXTVBUSIND_R { USEEXTVBUSIND_R::new(((self.bits >> 1) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Use External VBUS"] #[inline(always)] pub fn useextvbus(&mut self) -> USEEXTVBUS_W { USEEXTVBUS_W { w: self } } #[doc = "Bit 1 - Use External VBUS Indicator"] #[inline(always)] pub fn useextvbusind(&mut self) -> USEEXTVBUSIND_W { USEEXTVBUSIND_W { w: self } } }
pub fn parse_input(input: &str) -> Result<Vec<usize>, std::num::ParseIntError> { input .split(',') .map(|s| s.trim().parse::<usize>()) .collect::<Result<Vec<usize>, std::num::ParseIntError>>() } pub fn run_prog(input: &[usize]) -> Vec<usize> { let mut idx = 0; let mut output = Vec::with_capacity(input.len()); output.extend_from_slice(input); loop { match output[idx] { 1 => { let operand_1 = output[output[idx + 1]]; let operand_2 = output[output[idx + 2]]; let store_idx = output[idx + 3]; output[store_idx] = operand_1 + operand_2; idx += 4; } 2 => { let operand_1 = output[output[idx + 1]]; let operand_2 = output[output[idx + 2]]; let store_idx = output[idx + 3]; output[store_idx] = operand_1 * operand_2; idx += 4; } 99 => break, _ => panic!("Unexpected operation"), } } output } #[cfg(test)] mod tests { use super::*; #[test] fn ex1() { let input = vec![1, 9, 10, 3, 2, 3, 11, 0, 99, 30, 40, 50]; let output = run_prog(&input); assert_eq!(vec![3500, 9, 10, 70, 2, 3, 11, 0, 99, 30, 40, 50], output); } #[test] fn ex2() { let input = vec![1, 0, 0, 0, 99]; let output = run_prog(&input); assert_eq!(vec![2, 0, 0, 0, 99], output); } #[test] fn ex3() { let input = vec![2, 3, 0, 3, 99]; let output = run_prog(&input); assert_eq!(vec![2, 3, 0, 6, 99], output); } #[test] fn ex4() { let input = vec![2, 4, 4, 5, 99, 0]; let output = run_prog(&input); assert_eq!(vec![2, 4, 4, 5, 99, 9801], output); } #[test] fn ex5() { let input = vec![1, 1, 1, 4, 99, 5, 6, 0, 99]; let output = run_prog(&input); assert_eq!(vec![30, 1, 1, 4, 2, 5, 6, 0, 99], output); } }
use super::circular_unit::CircularUnit; use super::faction::Faction; use super::living_unit::LivingUnit; use super::message::Message; use super::skill_type::SkillType; use super::status::Status; use super::unit::Unit; #[derive(Clone, Debug, PartialEq)] pub struct Wizard { id: i64, x: f64, y: f64, speed_x: f64, speed_y: f64, angle: f64, faction: Faction, radius: f64, life: i32, max_life: i32, statuses: Vec<Status>, owner_player_id: i64, me: bool, mana: i32, max_mana: i32, vision_range: f64, cast_range: f64, xp: i32, level: i32, skills: Vec<SkillType>, remaining_action_cooldown_ticks: i32, remaining_cooldown_ticks_by_action: Vec<i32>, master: bool, messages: Vec<Message>, } impl Wizard { pub fn new() -> Self { Wizard { id: 0, x: 0.0, y: 0.0, speed_x: 0.0, speed_y: 0.0, angle: 0.0, faction: Faction::Unknown, radius: 0.0, life: 0, max_life: 0, statuses: vec![], owner_player_id: 0, me: false, mana: 0, max_mana: 0, vision_range: 0.0, cast_range: 0.0, xp: 0, level: 0, skills: vec![], remaining_action_cooldown_ticks: 0, remaining_cooldown_ticks_by_action: vec![], master: false, messages: vec![], } } pub fn id(&self) -> i64 { self.id } pub fn set_id(&mut self, value: i64) -> &mut Self { self.id = value; self } pub fn x(&self) -> f64 { self.x } pub fn set_x(&mut self, value: f64) -> &mut Self { self.x = value; self } pub fn y(&self) -> f64 { self.y } pub fn set_y(&mut self, value: f64) -> &mut Self { self.y = value; self } pub fn speed_x(&self) -> f64 { self.speed_x } pub fn set_speed_x(&mut self, value: f64) -> &mut Self { self.speed_x = value; self } pub fn speed_y(&self) -> f64 { self.speed_y } pub fn set_speed_y(&mut self, value: f64) -> &mut Self { self.speed_y = value; self } pub fn angle(&self) -> f64 { self.angle } pub fn set_angle(&mut self, value: f64) -> &mut Self { self.angle = value; self } pub fn faction(&self) -> Faction { self.faction } pub fn set_faction(&mut self, value: Faction) -> &mut Self { self.faction = value; self } pub fn radius(&self) -> f64 { self.radius } pub fn set_radius(&mut self, value: f64) -> &mut Self { self.radius = value; self } pub fn life(&self) -> i32 { self.life } pub fn set_life(&mut self, value: i32) -> &mut Self { self.life = value; self } pub fn max_life(&self) -> i32 { self.max_life } pub fn set_max_life(&mut self, value: i32) -> &mut Self { self.max_life = value; self } pub fn statuses(&self) -> &Vec<Status> { &self.statuses } pub fn set_statuses(&mut self, value: Vec<Status>) -> &mut Self { self.statuses = value; self } pub fn owner_player_id(&self) -> i64 { self.owner_player_id } pub fn set_owner_player_id(&mut self, value: i64) -> &mut Self { self.owner_player_id = value; self } pub fn me(&self) -> bool { self.me } pub fn set_me(&mut self, value: bool) -> &mut Self { self.me = value; self } pub fn mana(&self) -> i32 { self.mana } pub fn set_mana(&mut self, value: i32) -> &mut Self { self.mana = value; self } pub fn max_mana(&self) -> i32 { self.max_mana } pub fn set_max_mana(&mut self, value: i32) -> &mut Self { self.max_mana = value; self } pub fn vision_range(&self) -> f64 { self.vision_range } pub fn set_vision_range(&mut self, value: f64) -> &mut Self { self.vision_range = value; self } pub fn cast_range(&self) -> f64 { self.cast_range } pub fn set_cast_range(&mut self, value: f64) -> &mut Self { self.cast_range = value; self } pub fn xp(&self) -> i32 { self.xp } pub fn set_xp(&mut self, value: i32) -> &mut Self { self.xp = value; self } pub fn level(&self) -> i32 { self.level } pub fn set_level(&mut self, value: i32) -> &mut Self { self.level = value; self } pub fn skills(&self) -> &Vec<SkillType> { &self.skills } pub fn set_skills(&mut self, value: Vec<SkillType>) -> &mut Self { self.skills = value; self } pub fn remaining_action_cooldown_ticks(&self) -> i32 { self.remaining_action_cooldown_ticks } pub fn set_remaining_action_cooldown_ticks(&mut self, value: i32) -> &mut Self { self.remaining_action_cooldown_ticks = value; self } pub fn remaining_cooldown_ticks_by_action(&self) -> &Vec<i32> { &self.remaining_cooldown_ticks_by_action } pub fn set_remaining_cooldown_ticks_by_action(&mut self, value: Vec<i32>) -> &mut Self { self.remaining_cooldown_ticks_by_action = value; self } pub fn master(&self) -> bool { self.master } pub fn set_master(&mut self, value: bool) -> &mut Self { self.master = value; self } pub fn messages(&self) -> &Vec<Message> { &self.messages } pub fn set_messages(&mut self, value: Vec<Message>) -> &mut Self { self.messages = value; self } } unit_impl!(Wizard); circular_unit_impl!(Wizard); living_unit_impl!(Wizard);
pub mod p1; pub mod p215; pub mod p63;
use crate::autopilot_wrapper::*; use crate::res::*; use crate::TYPING_SPEED; use autopilot::geometry::{Point, Rect, Size}; use autopilot::key; use regex::Regex; use std::fs::{self, File}; use std::io::{BufRead, BufReader}; use std::path::Path; use std::thread::sleep; use std::time::Duration; fn find_interactive_app(iv_header: &Point, app_name: &str) { let app_name_field = shifted_point(iv_header, (540.0, 175.0)); let find_button = shifted_point(iv_header, (100.0, 100.0)); double_click(&app_name_field); sleep(Duration::from_millis(500)); key::type_string(app_name, &[], 150.0, 0.0); sleep(Duration::from_millis(500)); click(&find_button); } pub fn switch_next_tab(po_header: &Point) -> bool { let zone = Rect::new( shifted_point(po_header, (0.0, 30.0)), Size::new(620.0, 50.0), ); let next_tab = search_for(&PO_NEXT_TAB, Some(zone), 2); match next_tab { Some(tab) => click(&shifted_point(&tab, (5.0, 20.0))), None => println!("Tab not found"), }; next_tab.is_some() } fn is_end_of_tab(po_header: &Point) -> bool { let zone = Rect::new( shifted_point(po_header, (0.0, 580.0)), Size::new(200.0, 70.0), ); search_for(&OK_BTN_FOCUSED, Some(zone), 2).is_some() } fn fill_in_po_all_tabs(po_header: &Point, po_vec: &Vec<String>) { let mut po_peek = po_vec.iter().peekable(); let mut i = 1; // While PO has left in po_vec while po_peek.peek().is_some() { for _ in 0..3 { tap_with_mod(&key::Code(key::KeyCode::Tab), &[], 100); sleep(Duration::from_millis(200)); } sleep(Duration::from_millis(500)); while !is_end_of_tab(po_header) { println!( "Current PO: {}", po_peek .peek() .unwrap_or(&&"Not enough PO in Vec".to_owned()) ); key::type_string( po_peek.nth(0).unwrap_or(&"".to_owned()), &[], TYPING_SPEED, 0.0, ); sleep(Duration::from_millis(200)); tap_with_mod(&key::Code(key::KeyCode::Tab), &[], 100); sleep(Duration::from_millis(200)); } println!("Tab {} finished", i); i += 1; sleep(Duration::from_millis(1000)); let cancel_btn = shifted_point(po_header, (550.0, 600.0)); match switch_next_tab(po_header) { true => { println!("Tab switched"); if po_peek.peek().is_none() { println!("[!] But no PO left in po_vec"); click(&cancel_btn); return (); } } false => { println!("No more tabs"); match po_peek.peek() { Some(_) => { println!("[!] But there are still PO left"); click(&cancel_btn); return (); } None => { click(&cancel_btn); return (); } } } } } if po_peek.peek().is_none() { tap_with_mod(&key::Code(key::KeyCode::Return), &[], 100); // THEY'VE CALLED ENTER FUCKING "RETURN"!} } } fn create_iv(app_name: &str, version_name: &str, po_vec: &Vec<String>) { { let iv_header = search_for(&IV_HEADER, None, 1).expect("IV header not found"); find_interactive_app(&iv_header, app_name); sleep(Duration::from_millis(1000)); let zone = Rect::new( shifted_point(&iv_header, (1220.0, 630.0)), Size::new(150.0, 100.0), ); if (search_till_disappear(&PLEASE_WAIT, Some(zone), 300)).is_some() { panic!("IV App Find >300 secs") }; let add_button = shifted_point(&iv_header, (160.0, 100.0)); click(&add_button); sleep(Duration::from_millis(500)); } { let iv_add_header = search_for(&IV_ADD_HEADER, None, 300).expect("Waited for IV Add to open >300 secs"); key::type_string(&version_name, &[], TYPING_SPEED, 0.0); tap_with_mod(&key::Code(key::KeyCode::Tab), &[], 100); key::type_string(version_name, &[], TYPING_SPEED, 0.0); let add_button = shifted_point(&iv_add_header, (45.0, 100.0)); click(&add_button); } { let iv_design_header = search_for(&IV_DESIGN_HEADER, None, 300) .expect("Waited for IV Design to open >300 secs"); let po_button = shifted_point(&iv_design_header, (230.0, 350.0)); click(&po_button); } { let po_header = search_for(&PO_HEADER, None, 300).expect("Waited for PO window to open >300 secs"); fill_in_po_all_tabs(&po_header, po_vec); let iv_design_header = search_for(&IV_DESIGN_HEADER, None, 300) .expect("Version saved, but IV design header not found"); let ok_button = shifted_point(&iv_design_header, (50.0, 100.0)); click(&ok_button); } } fn parse_dir_name(dir_name: &str) -> (String, String) { lazy_static! { static ref APP_NAME: Regex = Regex::new("JDE_(.*?)_").unwrap(); static ref VERSION_NAME: Regex = Regex::new("[^J][^D][^E]_(.*?)_2019").unwrap(); } let app_name = APP_NAME.captures(&dir_name).unwrap()[1].to_owned(); let version_name = VERSION_NAME.captures(&dir_name).unwrap()[1].to_owned(); (app_name, version_name) } pub fn create_iv_for_path_and_file(path: &Path, po_file: &File) { let (app_name, version_name) = parse_dir_name(path.file_name().unwrap().to_str().unwrap()); println!("{}", app_name); println!("{}", version_name); let po_reader = BufReader::new(po_file); let po_vec: Vec<String> = po_reader .lines() .map(|line| line.expect("Failed to read line from BufReader")) .collect(); println!("[START] App: {}, version: {}", app_name, version_name); create_iv(&app_name, &version_name, &po_vec); println!("[FINISH] App: {}, version: {}", app_name, version_name); let dir_name = path.file_name().unwrap().to_str().unwrap(); let new_path = Path::new(path.parent().unwrap()).join(&format!("[FINISHED]_{}", dir_name)); fs::rename(&path, &new_path).unwrap(); } #[test] fn test_is_end_of_tab() { let po_header = search_for(&PO_HEADER, None, 1).expect("PO header not found"); assert!(is_end_of_tab(&po_header)); } #[test] fn test_switch_next_tab() { let po_header = search_for(&PO_HEADER, None, 1).expect("PO header not found"); assert!(switch_next_tab(&po_header)); }
use crate::{ library::{Chapter, Content}, source::Source, CACHE, }; use core::slice::SlicePattern; use futures::future::join_all; use reqwest::{ header::{HeaderMap, REFERER}, Client, Url, }; use serde::{Deserialize, Serialize}; use std::{ collections::BTreeMap, fs::File, io::BufReader, ops::Deref, path::PathBuf, }; impl Default for Retriever { fn default() -> Self { let mut h = BTreeMap::new(); let m = "readmanganato.com".to_string(); h.insert(m.clone(), Headers::default()); h.get_mut(&m) .unwrap() .headers .insert(REFERER, "https://readmanganato.com/".parse().unwrap()); Self { client: Client::new(), headers: h, location: CACHE.to_string() + "/retriever.json", } } } impl Default for Headers { fn default() -> Self { let mut hm = HeaderMap::new(); hm.insert(REFERER, "https://manganato.com/".parse().unwrap()); Self { headers: hm } } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Retriever { headers: BTreeMap<String, Headers>, #[serde(skip)] client: Client, #[serde(skip)] location: String, } #[derive(Clone, Debug, Serialize, Deserialize)] struct Headers { #[serde(with = "http_serde::header_map")] pub headers: HeaderMap, } impl Retriever { pub async fn fetch( &self, url: String, ) -> Source { Source::from(url).refresh().await } pub async fn chapter( &self, src: Source, visual: Option<bool>, ) -> Chapter { let mut ch = Chapter::default(); // TODO: to be investigated ch.pos = src.place.0; let vis = visual.unwrap_or(src.check_visual().unwrap()); let path = &PathBuf::from(CACHE).join(&src.title().deref()); match vis { true => { join_all( src.images_batch() .unwrap_or_default() .iter() .map(|s| self.content(s, true, path)), ) .await .iter() .cloned() .for_each(|mut content| { content.0 = src.place.1; ch.add_content(content); }); } false => { let cnt = self.content(&src.location, false, path).await; ch.add_content(cnt); } }; ch.page = src; ch } pub async fn content( &self, source: &String, visual: bool, path: &PathBuf, ) -> Content { let src: Source = self.fetch(source.to_string()).await; let mut cnt = Content::default(); cnt.0 = src.place.0; cnt.1 = cnt.1.join(path).join(&src.place.1.to_string()); match visual { true => { cnt.save( &self .client .get(source) .headers(self.get_headers(source)) .send() .await .ok() .unwrap() .bytes() .await .ok() .unwrap() .as_slice(), ); } false => { println!("{:?}", &src.text()); let text = src.text().unwrap_or_default().join("\n\n"); cnt.save(text.as_bytes()); } } cnt } pub async fn save(&self) { let file = File::with_options() .write(true) .create(true) .open(&self.location) .unwrap(); serde_json::to_writer(&file, &serde_json::to_string(&self).unwrap()) .unwrap(); } pub async fn load(&mut self) { let reader = BufReader::new(File::open(&self.location).unwrap()); let contents: String = serde_json::from_reader(reader) .expect("The json has most likely been corrupted."); let Self { headers: h, .. } = serde_json::from_str(&contents).unwrap(); self.headers = h; } fn get_headers( &self, src: &String, ) -> HeaderMap { self.headers .get(src.parse::<Url>().unwrap().domain().unwrap()) .cloned() .unwrap_or_default() .headers } }
use crate::window::{Window, Geometry}; use crate::stack::Stack; pub fn handle_layout<W>(view: &Geometry, windows: Stack<Window<W>>) -> Stack<Window<W>> { windows.into_iter() .map(|(is_current, window)| { (is_current, window.set_view(view.clone()).visible(is_current)) }) .collect() }
#![allow(unused_variables, non_upper_case_globals, non_snake_case, unused_unsafe, non_camel_case_types, dead_code, clippy::all)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AudioRoutingEndpoint(pub i32); impl AudioRoutingEndpoint { pub const Default: AudioRoutingEndpoint = AudioRoutingEndpoint(0i32); pub const Earpiece: AudioRoutingEndpoint = AudioRoutingEndpoint(1i32); pub const Speakerphone: AudioRoutingEndpoint = AudioRoutingEndpoint(2i32); pub const Bluetooth: AudioRoutingEndpoint = AudioRoutingEndpoint(3i32); pub const WiredHeadset: AudioRoutingEndpoint = AudioRoutingEndpoint(4i32); pub const WiredHeadsetSpeakerOnly: AudioRoutingEndpoint = AudioRoutingEndpoint(5i32); pub const BluetoothWithNoiseAndEchoCancellation: AudioRoutingEndpoint = AudioRoutingEndpoint(6i32); pub const BluetoothPreferred: AudioRoutingEndpoint = AudioRoutingEndpoint(7i32); } impl ::core::convert::From<i32> for AudioRoutingEndpoint { fn from(value: i32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AudioRoutingEndpoint { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AudioRoutingEndpoint { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Phone.Media.Devices.AudioRoutingEndpoint;i4)"); } impl ::windows::core::DefaultType for AudioRoutingEndpoint { type DefaultType = Self; } #[repr(transparent)] #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: clone :: Clone, :: core :: fmt :: Debug)] pub struct AudioRoutingManager(pub ::windows::core::IInspectable); impl AudioRoutingManager { pub fn GetAudioEndpoint(&self) -> ::windows::core::Result<AudioRoutingEndpoint> { let this = self; unsafe { let mut result__: AudioRoutingEndpoint = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AudioRoutingEndpoint>(result__) } } pub fn SetAudioEndpoint(&self, endpoint: AudioRoutingEndpoint) -> ::windows::core::Result<()> { let this = self; unsafe { (::windows::core::Interface::vtable(this).7)(::core::mem::transmute_copy(this), endpoint).ok() } } #[cfg(feature = "Foundation")] pub fn AudioEndpointChanged<'a, Param0: ::windows::core::IntoParam<'a, super::super::super::Foundation::TypedEventHandler<AudioRoutingManager, ::windows::core::IInspectable>>>(&self, endpointchangehandler: 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), endpointchangehandler.into_param().abi(), &mut result__).from_abi::<super::super::super::Foundation::EventRegistrationToken>(result__) } } #[cfg(feature = "Foundation")] pub fn RemoveAudioEndpointChanged<'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() } } pub fn AvailableAudioEndpoints(&self) -> ::windows::core::Result<AvailableAudioRoutingEndpoints> { let this = self; unsafe { let mut result__: AvailableAudioRoutingEndpoints = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).10)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AvailableAudioRoutingEndpoints>(result__) } } pub fn GetDefault() -> ::windows::core::Result<AudioRoutingManager> { Self::IAudioRoutingManagerStatics(|this| unsafe { let mut result__: ::windows::core::RawPtr = ::core::mem::zeroed(); (::windows::core::Interface::vtable(this).6)(::core::mem::transmute_copy(this), &mut result__).from_abi::<AudioRoutingManager>(result__) }) } pub fn IAudioRoutingManagerStatics<R, F: FnOnce(&IAudioRoutingManagerStatics) -> ::windows::core::Result<R>>(callback: F) -> ::windows::core::Result<R> { static mut SHARED: ::windows::core::FactoryCache<AudioRoutingManager, IAudioRoutingManagerStatics> = ::windows::core::FactoryCache::new(); unsafe { SHARED.call(callback) } } } unsafe impl ::windows::core::RuntimeType for AudioRoutingManager { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"rc(Windows.Phone.Media.Devices.AudioRoutingManager;{79340d20-71cc-4526-9f29-fc8d2486418b})"); } unsafe impl ::windows::core::Interface for AudioRoutingManager { type Vtable = IAudioRoutingManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79340d20_71cc_4526_9f29_fc8d2486418b); } impl ::windows::core::RuntimeName for AudioRoutingManager { const NAME: &'static str = "Windows.Phone.Media.Devices.AudioRoutingManager"; } impl ::core::convert::From<AudioRoutingManager> for ::windows::core::IUnknown { fn from(value: AudioRoutingManager) -> Self { value.0 .0 } } impl ::core::convert::From<&AudioRoutingManager> for ::windows::core::IUnknown { fn from(value: &AudioRoutingManager) -> Self { value.0 .0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IUnknown> for AudioRoutingManager { 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 AudioRoutingManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IUnknown> { ::windows::core::Param::Borrowed(&self.0 .0) } } impl ::core::convert::From<AudioRoutingManager> for ::windows::core::IInspectable { fn from(value: AudioRoutingManager) -> Self { value.0 } } impl ::core::convert::From<&AudioRoutingManager> for ::windows::core::IInspectable { fn from(value: &AudioRoutingManager) -> Self { value.0.clone() } } impl<'a> ::windows::core::IntoParam<'a, ::windows::core::IInspectable> for AudioRoutingManager { 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 AudioRoutingManager { fn into_param(self) -> ::windows::core::Param<'a, ::windows::core::IInspectable> { ::windows::core::Param::Borrowed(&self.0) } } unsafe impl ::core::marker::Send for AudioRoutingManager {} unsafe impl ::core::marker::Sync for AudioRoutingManager {} #[derive(:: core :: cmp :: PartialEq, :: core :: cmp :: Eq, :: core :: marker :: Copy, :: core :: clone :: Clone, :: core :: default :: Default, :: core :: fmt :: Debug)] #[repr(transparent)] pub struct AvailableAudioRoutingEndpoints(pub u32); impl AvailableAudioRoutingEndpoints { pub const None: AvailableAudioRoutingEndpoints = AvailableAudioRoutingEndpoints(0u32); pub const Earpiece: AvailableAudioRoutingEndpoints = AvailableAudioRoutingEndpoints(1u32); pub const Speakerphone: AvailableAudioRoutingEndpoints = AvailableAudioRoutingEndpoints(2u32); pub const Bluetooth: AvailableAudioRoutingEndpoints = AvailableAudioRoutingEndpoints(4u32); } impl ::core::convert::From<u32> for AvailableAudioRoutingEndpoints { fn from(value: u32) -> Self { Self(value) } } unsafe impl ::windows::core::Abi for AvailableAudioRoutingEndpoints { type Abi = Self; } unsafe impl ::windows::core::RuntimeType for AvailableAudioRoutingEndpoints { const SIGNATURE: ::windows::core::ConstBuffer = ::windows::core::ConstBuffer::from_slice(b"enum(Windows.Phone.Media.Devices.AvailableAudioRoutingEndpoints;u4)"); } impl ::windows::core::DefaultType for AvailableAudioRoutingEndpoints { type DefaultType = Self; } impl ::core::ops::BitOr for AvailableAudioRoutingEndpoints { type Output = Self; fn bitor(self, rhs: Self) -> Self { Self(self.0 | rhs.0) } } impl ::core::ops::BitAnd for AvailableAudioRoutingEndpoints { type Output = Self; fn bitand(self, rhs: Self) -> Self { Self(self.0 & rhs.0) } } impl ::core::ops::BitOrAssign for AvailableAudioRoutingEndpoints { fn bitor_assign(&mut self, rhs: Self) { self.0.bitor_assign(rhs.0) } } impl ::core::ops::BitAndAssign for AvailableAudioRoutingEndpoints { fn bitand_assign(&mut self, rhs: Self) { self.0.bitand_assign(rhs.0) } } impl ::core::ops::Not for AvailableAudioRoutingEndpoints { type Output = Self; fn not(self) -> Self { Self(self.0.not()) } } #[repr(transparent)] #[doc(hidden)] pub struct IAudioRoutingManager(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAudioRoutingManager { type Vtable = IAudioRoutingManager_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x79340d20_71cc_4526_9f29_fc8d2486418b); } #[repr(C)] #[doc(hidden)] pub struct IAudioRoutingManager_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 AudioRoutingEndpoint) -> ::windows::core::HRESULT, pub unsafe extern "system" fn(this: ::windows::core::RawPtr, endpoint: AudioRoutingEndpoint) -> ::windows::core::HRESULT, #[cfg(feature = "Foundation")] pub unsafe extern "system" fn(this: ::windows::core::RawPtr, endpointchangehandler: ::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, result__: *mut AvailableAudioRoutingEndpoints) -> ::windows::core::HRESULT, ); #[repr(transparent)] #[doc(hidden)] pub struct IAudioRoutingManagerStatics(pub ::windows::core::IInspectable); unsafe impl ::windows::core::Interface for IAudioRoutingManagerStatics { type Vtable = IAudioRoutingManagerStatics_abi; const IID: ::windows::core::GUID = ::windows::core::GUID::from_u128(0x977fb2a4_5590_4a6f_adde_6a3d0ad58250); } #[repr(C)] #[doc(hidden)] pub struct IAudioRoutingManagerStatics_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, );
use std::sync::Arc; use crate::{ protocol::parts::WriteLobReply, ExecutionResult, OutputParameters, ParameterDescriptors, }; #[derive(Debug)] pub enum InternalReturnValue { #[cfg(feature = "sync")] SyncResultSet(crate::sync::ResultSet), #[cfg(feature = "async")] AsyncResultSet(crate::a_sync::ResultSet), ExecutionResults(Vec<ExecutionResult>), OutputParameters(OutputParameters), ParameterMetadata(Arc<ParameterDescriptors>), WriteLobReply(WriteLobReply), }
use serde::{Deserialize, Serialize}; use serde_json::Result; use std::error::Error; use std::fmt; /* @4.10 获得账号关系 RequestAccountRelationsCommand 请求格式 id: u64, //(固定值): 1 command: String, //(固定值): account_lines relation_type: Option<String>, //None account: String, //需要用户传递的参数,钱包的地址 ledger_index: String //(固定值): 'validated' */ #[derive(Serialize, Deserialize, Debug)] pub struct RequestAccountRelationsCommand { #[serde(rename="id")] id: u64, #[serde(rename="command")] command: String, #[serde(rename="relation_type")] relation_type: Option<String>, #[serde(rename="account")] account: String, #[serde(rename="ledger_index")] ledger_index: String, } impl RequestAccountRelationsCommand { pub fn with_params(account: String, relation_type: Option<String>) -> Box<Self> { Box::new( RequestAccountRelationsCommand { id: 1, command: "account_lines".to_string(), relation_type: relation_type, account: account, ledger_index: "validated".to_string(), } ) } pub fn to_string(&self) -> Result<String> { let j = serde_json::to_string(&self)?; Ok(j) } } ///////////////////////// /* RequestAccountRelationsResponse 数据返回格式 */ #[derive(Serialize, Deserialize, Debug)] pub struct RequestAccountRelationsResponse { #[serde(rename="account")] pub account: String, // #[serde(rename="ledger_hash")] // pub ledger_hash: String, #[serde(rename="ledger_current_index")] pub ledger_index: u64, #[serde(rename="lines")] pub lines: Vec<Line>, #[serde(rename="validated")] pub validated: bool, } #[derive(Serialize, Deserialize, Debug)] pub struct Line { #[serde(rename="account")] pub account: String, #[serde(rename="balance")] pub balance: String, #[serde(rename="currency")] pub currency: String, #[serde(rename="limit")] pub limit: String, #[serde(rename="limit_peer")] pub limit_peer: String, #[serde(rename="no_skywell")] pub no_skywell: bool, #[serde(rename="quality_in")] pub quality_in: u64, #[serde(rename="quality_out")] pub quality_out: u64, } #[derive(Debug, Serialize, Deserialize)] pub struct RelationsSideKick { pub error : String, pub error_code : i32, pub error_message : String, pub id : u32, pub request : RequestAccountRelationsCommand, pub status : String, #[serde(rename="type")] pub rtype : String, } impl fmt::Display for RelationsSideKick { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "RelationsSideKick is here!") } } impl Error for RelationsSideKick { fn description(&self) -> &str { "I'm RelationsSideKick side kick" } }
use instruction; use std::io; error_chain! { errors { UnrecognizedInstruction(iw: instruction::InstructionWord) } foreign_links { Io(io::Error); } }