text
stringlengths
8
4.13M
use std::vec::Vec; use server::player::Player; pub enum ZirconError { FailedToBind } /// This is the base implementation of any server. /// ZirconServer may be overridden in custom environments where certain requirements /// are neededt that we don't provide. pub trait ZirconServer { fn start(&self, address: &str, port: u16) -> Result<(), ZirconError>; fn stop(&self) -> Result<(), ZirconError>; fn online_players(&self) -> Vec<&dyn Player>; } mod player; mod location;
use ::log::{LogRecord, LogMetadata}; ///The Logger used by Netherrack /// ///For now, it simply logs to standard output. In future versions, it will be extended pub struct NetherrackLogger; impl ::log::Log for NetherrackLogger { ///Checks to see if a LogRecord can be accepted based on LogMetadata #[allow(unused_variables)] fn enabled(&self, metadata: &LogMetadata) -> bool { true //Before 0.1, change dynamically based on if we're a prerelease version } ///Attempts to log a LogRecord fn log(&self, record: &LogRecord) { //First, check to see if logging is enabled for the metadata if self.enabled(record.metadata()) { println!("[{}] {}: {}", record.level(), record.target(), record.args()); } } }
#[derive(Eq, PartialEq, Debug)] pub struct Ident(pub String); #[derive(Debug)] pub struct Num(pub f64); #[derive(Debug)] pub struct FuncHead { pub name: Ident, pub params: ParamList, } pub type ParamList = Vec<RVal>; #[derive(Debug)] pub enum RVal { Num(Num), LVal(LVal), FuncCall(FuncCall), OpAdd(Box<RVal>, Box<RVal>), OpSub(Box<RVal>, Box<RVal>), OpMul(Box<RVal>, Box<RVal>), OpDiv(Box<RVal>, Box<RVal>), } #[derive(Eq, PartialEq, Debug)] pub enum LVal { Var(Ident), } #[derive(Debug)] pub struct FuncCall { pub name: Ident, pub args: ParamList, } pub type Block = Vec<Command>; #[derive(Debug)] pub enum Command { RVal(RVal), Assign(Assign), Block(Vec<Command>), If(If), } #[derive(Debug)] pub struct If { pub cond: BExp, pub then_case: Block, pub else_case: Block } impl If { pub fn new(cond: BExp, then: Block) -> Self { If { cond: cond, then_case: then, else_case: Vec::new() } } pub fn new_with_else(cond: BExp, then: Block, elsec: Block) -> Self { If { cond: cond, then_case: then, else_case: elsec, } } } #[derive(Debug)] pub struct Assign(pub LVal, pub RVal); #[derive(Debug)] pub enum BExp { Eq(RVal, RVal), Neq(RVal, RVal), Le(RVal, RVal), Leq(RVal, RVal), Ge(RVal, RVal), Geq(RVal, RVal), Not(Box<BExp>), And(Box<BExp>, Box<BExp>), Or(Box<BExp>, Box<BExp>), Val(BVal), } #[derive(Debug)] pub enum BVal { True, False, }
use hyper::client::request::Request; use hyper::net::Fresh; use hyper::client::response::Response; use hyper::status::StatusCode; use std::error::Error as StdErr; use err::Error; use error::ApiError; use std::fmt; use std::rc::Rc; use std::cell::RefCell; use hyper::header::Headers; use body_builder::{BodyBuilder, RequestBody}; pub use hyper::method::Method as HttpMethod; pub struct ApiRequest { pub base_url: String, pub method: HttpMethod, pub path: String, pub headers: Option<Headers>, pub queryParameters: Vec<(String, String)>, pub body: Option<RequestBody>, } pub trait ApiRequestBuilder<ResponseType> { // Define this function when you want to override base url fn base_url(&self) -> Option<String> { return None; } fn method(&self) -> HttpMethod; fn path(&self) -> String; fn queryParameters(&self) -> Vec<(String, String)> { let vc: Vec<(String, String)> = vec![]; return vc; } fn requestBody(&self) -> Option<RequestBody> { return None; } fn interceptRequest(&self, request: Request<Fresh>) -> Result<Request<Fresh>, ApiError> { return Ok(request); } fn interceptResponse(&self, response: Rc<RefCell<Response>>) -> Result<Rc<RefCell<Response>>, ApiError> { return Ok(response); } fn responseFromObject(&self, response: Rc<RefCell<Response>>) -> Result<ResponseType, ApiError>; }
pub struct View { value: u64, } impl View { pub fn new() -> Self { Self { value: 1 } } pub fn value(&self) -> u64 { self.value } }
use std::io::{ self, BufRead }; use clap::{ Arg, App, crate_name, crate_version, crate_authors, }; use chunks; fn main() -> Result<(), io::Error> { let matches = App::new(crate_name!()) .version(crate_version!()) .author(crate_authors!()) .about("Splits (large) input files up and execs child processes over these") .arg(Arg::with_name("type") .long("type") .multiple(false) .takes_value(true) .required(true) .help("Record format type. [embl|fasta]")) .arg(Arg::with_name("in") .short("i") .long("in") .multiple(false) .takes_value(true) .help("Input file. If not provided, defaults to STDIN.")) .arg(Arg::with_name("commands") .multiple(true)) .get_matches(); let ins: Vec<Box<dyn BufRead>> = chunks::read_from_files_or_stdin(matches.values_of("in"))?; let delim = match matches.value_of("type").unwrap() { "fasta" => chunks::Delim::new(b">", false), "embl" => chunks::Delim::new(b"\n//\n", true), unknown => { panic!("Unknown record type `{}'", unknown); } }; let commands = matches.values_of("commands"); let mut chunk_handler: Box<dyn FnMut(&[u8]) -> ()> = match commands { None => Box::new(print_chunk), Some(mut cs) => { use std::process::*; use std::io::Write; let mut cmd = Command::new(cs.next().unwrap()); cmd.args(cs) .stdin(Stdio::piped()); let handle = move |chunk: &[u8]| { let mut child = cmd.spawn().expect("Chunk command failed"); child.stdin.as_mut().unwrap().write_all(chunk).expect("Failed to write to child process stdin"); let ecode = child.wait().expect("Failed to wait on a child"); assert!(ecode.success()); }; Box::new(handle) } }; for in_reader in ins { for chunk in chunks::chunks(in_reader, &delim) { chunk_handler(&chunk.unwrap()); } } Ok(()) } fn print_chunk(chunk: &[u8]) { println!("<<<"); println!("{}", std::str::from_utf8(chunk).unwrap().trim()); println!(">>>") }
use std::convert::Infallible; use std::error::Error; use serde::Serialize; use slog::{info, Logger}; use warp::http::StatusCode; use warp::{reject, Rejection, Reply}; use crate::node_runner::{LightNodeRunnerError, LightNodeRunnerRef}; use crate::tezos_client_runner::{ BakeRequest, SandboxWallets, TezosClientRunnerError, TezosClientRunnerRef, TezosProtcolActivationParameters, reply_with_client_output, }; #[derive(Debug, Serialize)] pub struct ErrorMessage { code: u16, error_type: String, message: String, field_name: String, } impl ErrorMessage { pub fn generic(code: u16, message: String) -> Self { Self { code, error_type: "generic".to_string(), message, field_name: "".to_string(), } } pub fn validation(code: u16, message: String, field_name: String) -> Self { Self { code, error_type: "validation".to_string(), message, field_name, } } } /// Handler for start endpoint pub async fn start_node_with_config( cfg: serde_json::Value, log: Logger, runner: LightNodeRunnerRef, ) -> Result<impl warp::Reply, reject::Rejection> { info!( log, "Received request to start the light node with config: {:?}", cfg ); // aquire a write lock to the runner let mut runner = runner.write().unwrap(); info!(log, "Starting light-node..."); // spawn the node runner.spawn(cfg)?; Ok(StatusCode::OK) } pub async fn stop_node( log: Logger, runner: LightNodeRunnerRef, client_runner: TezosClientRunnerRef, ) -> Result<impl warp::Reply, reject::Rejection> { info!(log, "Received request to stop the light node"); // aquire a write lock to the runner let mut runner = runner.write().unwrap(); let mut client_runner = client_runner.write().unwrap(); // cleanup tezos client data let _ = client_runner.cleanup(); // shut down the node runner.shut_down()?; Ok(StatusCode::OK) } pub async fn init_client_data( wallets: SandboxWallets, log: Logger, client_runner: TezosClientRunnerRef, ) -> Result<impl warp::Reply, reject::Rejection> { info!(log, "Received request to init the tezos-client"); let mut client_runner = client_runner.write().unwrap(); let client_output = client_runner.init_client_data(wallets)?; reply_with_client_output(client_output, &log) } pub async fn get_wallets( log: Logger, client_runner: TezosClientRunnerRef, ) -> Result<impl warp::Reply, reject::Rejection> { info!(log, "Received request to list the activated wallets"); let client_runner = client_runner.read().unwrap(); // let client_output = client_runner.init_client_data(wallets)?; // let wallets = client_runner.wallets.clone(); let reply = warp::reply::json(&client_runner.wallets.values().cloned().collect::<SandboxWallets>()); Ok(warp::reply::with_status(reply, StatusCode::OK)) } pub async fn activate_protocol( activation_parameters: TezosProtcolActivationParameters, log: Logger, client_runner: TezosClientRunnerRef, ) -> Result<impl warp::Reply, reject::Rejection> { info!(log, "Received request to activate the protocol"); let client_runner = client_runner.read().unwrap(); let client_output = client_runner.activate_protocol(activation_parameters)?; reply_with_client_output(client_output, &log) } pub async fn bake_block_with_client( request: BakeRequest, log: Logger, client_runner: TezosClientRunnerRef, ) -> Result<impl warp::Reply, reject::Rejection> { info!(log, "Received request to bake a block"); let client_runner = client_runner.read().unwrap(); let client_output = client_runner.bake_block(Some(request))?; reply_with_client_output(client_output, &log) } pub async fn bake_block_with_client_arbitrary( log: Logger, client_runner: TezosClientRunnerRef, ) -> Result<impl warp::Reply, reject::Rejection> { info!(log, "Received request to bake a block"); let client_runner = client_runner.read().unwrap(); let client_output = client_runner.bake_block(None)?; reply_with_client_output(client_output, &log) } pub async fn handle_rejection(err: Rejection) -> Result<impl Reply, Infallible> { let code; let message; let mut field_name: Option<String> = None; if err.is_not_found() { code = StatusCode::NOT_FOUND; message = "NOT FOUND"; } else if let Some(TezosClientRunnerError::ProtocolParameterError) = err.find() { code = StatusCode::BAD_REQUEST; message = "Protocol parameter deserialization error"; } else if let Some(TezosClientRunnerError::NonexistantWallet) = err.find() { code = StatusCode::BAD_REQUEST; message = "The provided alias is not a known wallet"; } else if let Some(LightNodeRunnerError::NodeAlreadyRunning) = err.find() { code = StatusCode::BAD_REQUEST; message = "Node is allready running"; } else if let Some(LightNodeRunnerError::NodeNotRunnig) = err.find() { code = StatusCode::BAD_REQUEST; message = "Node not running"; } else if let Some(LightNodeRunnerError::NodeStartupError {reason}) = err.find() { code = StatusCode::INTERNAL_SERVER_ERROR; field_name = extract_field_name(&reason); message = reason; } else if let Some(e) = err.find::<warp::filters::body::BodyDeserializeError>() { // This error happens if the body could not be deserialized correctly match e.source() { Some(_) => { message = "Request deserialization errror"; } None => message = "Request deserialization errror", } code = StatusCode::BAD_REQUEST; } else if let Some(TezosClientRunnerError::CallError { message }) = err.find() { // the error message is constructed in error creation return Ok(warp::reply::with_status(warp::reply::json(message), StatusCode::INTERNAL_SERVER_ERROR)) } else { code = StatusCode::INTERNAL_SERVER_ERROR; message = "UNHANDLED_REJECTION"; } let json = if let Some(field_name) = field_name { warp::reply::json(&ErrorMessage::validation(code.as_u16(), message.to_string(), field_name)) } else { warp::reply::json(&ErrorMessage::generic(code.as_u16(), message.to_string())) }; Ok(warp::reply::with_status(json, code)) } fn extract_field_name(message: &str) -> Option<String> { let field_name = message.split_whitespace().filter(|s| s.starts_with("\'--")).map(|s| s.to_string()).collect::<Vec<String>>(); if field_name.len() < 1 { None } else { Some(field_name[0].replace("\'--", "")) } }
//! Service and ServiceFactory implementation. Specialized wrapper over substrate service. use runtime; use sc_service::{ error::{Error as ServiceError}, AbstractService, Configuration, }; use sp_inherents::InherentDataProviders; use sc_executor::native_executor_instance; pub use sc_executor::NativeExecutor; use sc_consensus_manual_seal::{rpc, self as manual_seal}; use futures::future::Either; // Our native executor instance. native_executor_instance!( pub Executor, runtime::api::dispatch, runtime::native_version, ); /// Starts a `ServiceBuilder` for a full service. /// /// Use this macro if you don't actually need the full service, but just the builder in order to /// be able to perform chain operations. macro_rules! new_full_start { ($config:expr) => {{ let builder = sc_service::ServiceBuilder::new_full::< runtime::opaque::Block, runtime::RuntimeApi, crate::service::Executor >($config)? .with_select_chain(|_config, backend| { Ok(sc_client::LongestChain::new(backend.clone())) })? .with_transaction_pool(|config, client, _fetcher| { let pool_api = sc_transaction_pool::FullChainApi::new(client.clone()); Ok(sc_transaction_pool::BasicPool::new(config, std::sync::Arc::new(pool_api))) })? .with_import_queue(|_config, client, _select_chain, _transaction_pool| { Ok(sc_consensus_manual_seal::import_queue::<_, sc_client_db::Backend<_>>(Box::new(client))) })?; builder }} } type RpcExtension = jsonrpc_core::IoHandler<sc_rpc::Metadata>; /// Builds a new service for a full client. pub fn new_full(config: Configuration, instant_seal: bool) -> Result<impl AbstractService, ServiceError> { let inherent_data_providers = InherentDataProviders::new(); inherent_data_providers .register_provider(sp_timestamp::InherentDataProvider) .map_err(Into::into) .map_err(sp_consensus::error::Error::InherentData)?; let builder = new_full_start!(config); // Channel for the rpc handler to communicate with the authorship task. let (command_sink, commands_stream) = futures::channel::mpsc::channel(1000); let service = if instant_seal { builder.build()? } else { builder // manual-seal relies on receiving sealing requests aka EngineCommands over rpc. .with_rpc_extensions(|_| -> Result<RpcExtension, _> { let mut io = jsonrpc_core::IoHandler::default(); io.extend_with( // We provide the rpc handler with the sending end of the channel to allow the rpc // send EngineCommands to the background block authorship task. rpc::ManualSealApi::to_delegate(rpc::ManualSeal::new(command_sink)), ); Ok(io) })? .build()? }; // Proposer object for block authorship. let proposer = sc_basic_authorship::ProposerFactory::new( service.client().clone(), service.transaction_pool(), ); // Background authorship future. let future = if instant_seal { log::info!("Running Instant Sealing Engine"); Either::Right(manual_seal::run_instant_seal( Box::new(service.client()), proposer, service.client().clone(), service.transaction_pool().pool().clone(), service.select_chain().unwrap(), inherent_data_providers )) } else { log::info!("Running Manual Sealing Engine"); Either::Left(manual_seal::run_manual_seal( Box::new(service.client()), proposer, service.client().clone(), service.transaction_pool().pool().clone(), commands_stream, service.select_chain().unwrap(), inherent_data_providers )) }; // we spawn the future on a background thread managed by service. service.spawn_essential_task( if instant_seal { "instant-seal" } else { "manual-seal" }, future ); Ok(service) } /// Builds a new service for a light client. pub fn new_light(_config: Configuration) -> Result<impl AbstractService, ServiceError> { unimplemented!("No light client for manual seal"); // This needs to be here or it won't compile. #[allow(unreachable_code)] new_full(_config, false) }
mod types; mod allocator; mod allocator_jni; mod transformer_jni;
use std::io; use IRustError::*; #[derive(Debug)] pub enum IRustError { IoError(io::Error), CrosstermError(crossterm::ErrorKind), Custom(String), RacerDisabled, ParsingError(String), } impl std::error::Error for IRustError {} impl From<io::Error> for IRustError { fn from(error: io::Error) -> Self { IRustError::IoError(error) } } impl From<&Self> for IRustError { fn from(error: &Self) -> Self { match error { RacerDisabled => RacerDisabled, _ => Custom(error.to_string()), } } } impl From<&mut Self> for IRustError { fn from(error: &mut Self) -> Self { match error { RacerDisabled => RacerDisabled, _ => Custom(error.to_string()), } } } impl From<&str> for IRustError { fn from(error: &str) -> Self { Custom(error.to_string()) } } impl From<crossterm::ErrorKind> for IRustError { fn from(error: crossterm::ErrorKind) -> Self { IRustError::CrosstermError(error) } } impl From<toml::de::Error> for IRustError { fn from(error: toml::de::Error) -> Self { IRustError::ParsingError(error.to_string()) } } impl From<toml::ser::Error> for IRustError { fn from(error: toml::ser::Error) -> Self { IRustError::ParsingError(error.to_string()) } } impl From<String> for IRustError { fn from(error: String) -> Self { IRustError::Custom(error) } } impl std::fmt::Display for IRustError { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> { match self { IoError(e) => write!(f, "{}", e), CrosstermError(e) => write!(f, "{}", e), Custom(e) => write!(f, "{}", e), RacerDisabled => write!(f, "Racer is disabled"), ParsingError(e) => write!(f, "{}", e), } } }
extern crate autograd as ag; use crate::abs_model::{MNISTModel, NdArray}; use crate::dataset::load; use ag::ndarray_ext as array; use ag::optimizers::adam; use ag::rand::seq::SliceRandom; use ag::tensor::Variable; use ag::Graph; use ndarray::s; use ndarray_npy::{ReadNpyExt, WriteNpyExt}; use std::fs::File; use std::sync::{Arc, RwLock}; type Tensor<'graph> = ag::Tensor<'graph, f32>; fn inputs(g: &Graph<f32>) -> (Tensor, Tensor) { let x = g.placeholder(&[-1, 28 * 28]); let y = g.placeholder(&[-1, 1]); (x, y) } fn get_permutation(size: usize) -> Vec<usize> { let mut perm: Vec<usize> = (0..size).collect(); perm.shuffle(&mut rand::thread_rng()); perm } pub struct MNISTMlp { x_train: NdArray, y_train: NdArray, x_test: NdArray, y_test: NdArray, hidden1: Arc<RwLock<NdArray>>, hidden2: Arc<RwLock<NdArray>>, biased: Arc<RwLock<NdArray>>, } impl MNISTModel for MNISTMlp { fn new() -> MNISTMlp { let ((x_train, y_train), (x_test, y_test)) = load(); let rng = ag::ndarray_ext::ArrayRng::<f32>::default(); let model = MNISTMlp { x_train: x_train, y_train: y_train, x_test: x_test, y_test: y_test, hidden1: array::into_shared(rng.glorot_uniform(&[28 * 28, 128])), hidden2: array::into_shared(rng.glorot_uniform(&[128, 10])), biased: array::into_shared(array::zeros(&[1, 10])), }; return model; } fn load_model(&mut self) -> Result<(), std::io::Error> { self.hidden1 = array::into_shared(NdArray::read_npy(File::open("./hidden1.npy")?).expect("err")); self.hidden2 = array::into_shared(NdArray::read_npy(File::open("./hidden2.npy")?).expect("err")); self.biased = array::into_shared(NdArray::read_npy(File::open("./biased.npy")?).expect("err")); Ok(()) } fn train(&self) { let adam_state = adam::AdamState::new(&[&self.hidden1, &self.hidden2, &self.biased]); let max_epoch = 3; let batch_size = 25isize; let num_samples = self.x_train.shape()[0]; let num_batches = num_samples / batch_size as usize; for epoch in 0..max_epoch { ag::with(|g| { let h1 = g.variable(self.hidden1.clone()); let h2 = g.variable(self.hidden2.clone()); let b = g.variable(self.biased.clone()); let (x, y) = inputs(g); let z = g.matmul(g.relu(g.matmul(x, h1)), h2) + b; let loss = g.sparse_softmax_cross_entropy(z, &y); let mean_loss = g .reduce_mean(loss, &[0], false) .raw_hook(|arr| println!("{:?}", arr[0])); let grads = &g.grad(&[&mean_loss], &[h1, h2, b]); let update_ops: &[Tensor] = &adam::Adam::default().compute_updates(&[h1, h2, b], grads, &adam_state, g); for i in get_permutation(num_batches) { let i = i as isize * batch_size; let x_batch = self.x_train.slice(s![i..i + batch_size, ..]).into_dyn(); let y_batch = self.y_train.slice(s![i..i + batch_size, ..]).into_dyn(); g.eval(update_ops, &[x.given(x_batch), y.given(y_batch)]); } println!("finish epoch {}", epoch); }); } match self.hidden1.try_read() { Ok(arr) => (*arr) .write_npy(File::create("hidden1.npy").expect("err")) .expect("err"), Err(_) => {} } match self.hidden2.try_read() { Ok(arr) => (*arr) .write_npy(File::create("hidden2.npy").expect("err")) .expect("err"), Err(_) => {} } match self.biased.try_read() { Ok(arr) => (*arr) .write_npy(File::create("biased.npy").expect("err")) .expect("err"), Err(_) => (), } } fn validate(&self) -> f64 { let mut res: f64 = 0.0; ag::with(|g| { let h1 = g.variable(self.hidden1.clone()); let h2 = g.variable(self.hidden2.clone()); let b = g.variable(self.biased.clone()); let (x, y) = inputs(g); let z = g.matmul(g.relu(g.matmul(x, h1)), h2) + b; let predictions = g.argmax(z, -1, true); let accuracy = g.reduce_mean(&g.equal(predictions, &y), &[0, 1], false); res = accuracy .eval(&[x.given(self.x_test.view()), y.given(self.y_test.view())]) .expect("e") .scalar_sum() as f64; }); return res; } }
//! Tokens use std::fmt; use parser::util::{rcstr, SharedString}; // --- Token -------------------------------------------------------------------- /// A token #[derive(Clone, PartialEq)] pub enum Token { LPAREN, RPAREN, LBRACE, RBRACE, STRING(SharedString), SYMBOL(SharedString), NUMBER(f64), EOF, PLACEHOLDER } impl fmt::Display for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { Token::LPAREN => write!(f, "("), Token::RPAREN => write!(f, ")"), Token::LBRACE => write!(f, "{{"), Token::RBRACE => write!(f, "}}"), Token::STRING(ref s) => write!(f, "\"{}\"", s.escape_default()), Token::SYMBOL(ref s) => write!(f, "{}", s), Token::NUMBER(n) => write!(f, "{}", n), Token::EOF => write!(f, "EOF"), Token::PLACEHOLDER => write!(f, "PLACEHOLDER") } } } impl fmt::Debug for Token { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", self) } } // --- Source location ---------------------------------------------------------- /// Represntation of a location in the input #[derive(PartialEq, Eq, Clone)] pub struct SourceLocation { pub filename: SharedString, pub lineno: usize } impl fmt::Display for SourceLocation { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}:{}", self.filename, self.lineno) } } /// A dummy source location pub fn dummy_source() -> SourceLocation { SourceLocation { filename: rcstr("<input>"), lineno: 0 } }
use skulpin::app::MouseButton; use skulpin::skia_safe::*; use crate::ui::*; use crate::util::quantize; pub enum SliderStep { Smooth, Discrete(f32), } pub struct Slider { value: f32, min: f32, max: f32, step: SliderStep, sliding: bool, } #[derive(Clone, Copy)] pub struct SliderArgs { pub width: f32, pub color: Color, } impl Slider { pub fn new(value: f32, min: f32, max: f32, step: SliderStep) -> Self { Self { value: (value - min) / (max - min), min, max, step, sliding: false, } } fn step_count(&self) -> u32 { if let SliderStep::Discrete(step) = self.step { ((self.max - self.min) / step) as u32 } else { panic!("attempt to use step_count on a non-discrete slider"); } } pub fn process(&mut self, ui: &mut Ui, canvas: &mut Canvas, input: &Input, SliderArgs { width, color }: SliderArgs) { ui.push_group((width, ui.height()), Layout::Freeform); if ui.has_mouse(input) && input.mouse_button_just_pressed(MouseButton::Left) { self.sliding = true; } if input.mouse_button_just_released(MouseButton::Left) { self.sliding = false; } if self.sliding { self.value = ui.mouse_position(input).x / ui.width(); self.value = self.value.clamp(0.0, 1.0); } ui.draw_on_canvas(canvas, |canvas| { let transparent = Color4f::from(color.with_a(96)); let mut paint = Paint::new(transparent, None); let mut x = self.value * ui.width(); let y = ui.height() / 2.0; paint.set_anti_alias(true); paint.set_style(paint::Style::Stroke); paint.set_stroke_width(2.0); canvas.draw_line((0.0, y), (ui.width(), y), &paint); paint.set_color(paint.color().with_a(255)); if let SliderStep::Discrete(_) = self.step { let step_count = self.step_count(); let norm_step = 1.0 / step_count as f32; let step_width = norm_step * ui.width(); if step_width > 4.0 { for i in 0..=step_count { let t = i as f32 * norm_step; let px = t * ui.width(); canvas.draw_point((px, y), &paint); } } x = quantize(x, step_width); } paint.set_style(paint::Style::Fill); canvas.draw_circle((x, y), 5.0, &paint); }); ui.pop_group(); } pub fn value(&self) -> f32 { let raw = (self.value * (self.max - self.min)) + self.min; match self.step { SliderStep::Smooth => raw, SliderStep::Discrete(step) => quantize(raw, step), } } }
#![cfg_attr( all(not(debug_assertions), target_os = "windows"), windows_subsystem = "windows" )] use r2d2_sqlite::SqliteConnectionManager; fn main() { let mut path = dirs::cache_dir().unwrap(); path.push("tauri-app.sql"); let manager = r2d2_sqlite::SqliteConnectionManager::file(path); let pool = r2d2::Pool::new(manager).unwrap(); let conn = pool.get().unwrap(); conn .execute( "CREATE TABLE IF NOT EXISTS kvs (k TEXT PRIMARY KEY, v TEXT NOT NULL)", [], ) .unwrap(); tauri::Builder::default() .manage(pool) .invoke_handler(tauri::generate_handler![persist_entry, fetch_entries]) .run(tauri::generate_context!()) .expect("error while running tauri application"); } #[tauri::command] fn fetch_entries(pool: tauri::State<r2d2::Pool<SqliteConnectionManager>>) -> Vec<(String, String)> { println!("fetching all entries"); let conn = pool.get().unwrap(); let mut stmt = conn.prepare("SELECT k, v FROM kvs ORDER BY k").unwrap(); stmt .query_map([], |row| Ok((row.get_unwrap("k"), row.get_unwrap("v")))) .unwrap() .collect::<Result<_, _>>() .unwrap() } #[tauri::command] fn persist_entry( pool: tauri::State<r2d2::Pool<SqliteConnectionManager>>, key: String, value: String, ) { println!("recording {} = {}", key, value); let conn = pool.get().unwrap(); conn .execute( "INSERT OR REPLACE INTO kvs (k, v) VALUES (?, ?)", [key, value], ) .unwrap(); }
pub fn implement(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let max_dimensions = 4; let vec_type = syn::parse_macro_input!(input as syn::Ident); let vec_type_name = vec_type.to_string(); let scalar_type_name = &vec_type_name[0..vec_type_name.len() - 1]; let scalar_fn_name = voca_rs::case::lower_first(scalar_type_name); let dimension = vec_type_name[vec_type_name.len() - 1..] .parse::<usize>() .unwrap(); let trait_name = quote::format_ident!("{}{}", "AccessFrom", dimension); let axes = "xyzw"; let trait_method_declarations: Vec<syn::TraitItem> = (dimension..=max_dimensions) .flat_map(|dim| { accessor_names(dim, &axes[0..dimension]) .into_iter() .map(move |name| { let ret_type = quote::format_ident!("{}{}", scalar_type_name, dim); let fn_name = quote::format_ident!("{}", name); syn::parse_quote!(fn #fn_name(self) -> #ret_type;) }) }) .collect(); let trait_method_definitions: Vec<syn::TraitItem> = (dimension..=max_dimensions) .flat_map(|dim| { accessor_names(dim, &axes[0..dimension]) .into_iter() .map(|name| { let ret_type = quote::format_ident!("{}{}", scalar_type_name, dim); let fn_name = quote::format_ident!("{}", name); let constuctor = quote::format_ident!("{}{}", scalar_fn_name, dim); let args: syn::punctuated::Punctuated<_, syn::Token![,]> = name .chars() .map(|ch| { let field = quote::format_ident!("{}", ch); let access: syn::Expr = syn::parse_quote!(self.#field); access }) .collect(); syn::parse_quote!(fn #fn_name(self) -> #ret_type {(#args).#constuctor()}) }) .collect::<Vec<_>>() }) .collect(); let result = quote::quote!( pub trait #trait_name { #(#trait_method_declarations)* } impl #trait_name for #vec_type { #(#trait_method_definitions)* } ); // eprintln!("{}", result); proc_macro::TokenStream::from(result) } fn accessor_names(dims: usize, axes: &str) -> Vec<String> { let mut result = vec!["".to_string()]; for _ in 0..dims { let mut next = vec![]; for ch in axes.chars() { for sofar in result.iter() { next.push(format!("{}{}", sofar, ch)); } } result = next; } result }
mod controls; #[macro_use] mod renderer; mod bounding_volume; mod camera; mod assets; mod particle; mod planet; mod star; use iced_wgpu::{wgpu, Backend, Renderer, Settings, Viewport}; use iced_winit::{ conversion, futures, futures::task::SpawnExt, program, Debug, Size, winit, winit::event::{Event, WindowEvent}, }; /*pub unsafe fn transmute_vec<S, T>(mut vec: Vec<S>) -> Vec<T> { let ptr = vec.as_mut_ptr() as *mut T; let len = vec.len()*std::mem::size_of::<S>()/std::mem::size_of::<T>(); let capacity = vec.capacity()*std::mem::size_of::<S>()/std::mem::size_of::<T>(); std::mem::forget(vec); Vec::from_raw_parts(ptr, len, capacity) }*/ pub unsafe fn transmute_slice<S, T>(slice: &[S]) -> &[T] { let ptr = slice.as_ptr() as *const T; let len = slice.len()*std::mem::size_of::<S>()/std::mem::size_of::<T>(); std::slice::from_raw_parts(ptr, len) } pub unsafe fn transmute_slice_mut<S, T>(slice: &mut [S]) -> &mut [T] { let ptr = slice.as_mut_ptr() as *mut T; let len = slice.len()*std::mem::size_of::<S>()/std::mem::size_of::<T>(); std::slice::from_raw_parts_mut(ptr, len) } fn generate_swap_chain_descriptor(window: &winit::window::Window, scale_factor: f32) -> wgpu::SwapChainDescriptor { let size = window.inner_size(); wgpu::SwapChainDescriptor { usage: wgpu::TextureUsage::OUTPUT_ATTACHMENT, format: wgpu::TextureFormat::Bgra8UnormSrgb, width: (size.width as f32*scale_factor) as u32, height: (size.height as f32*scale_factor) as u32, present_mode: wgpu::PresentMode::Mailbox, } } pub fn main() { // env_logger::init(); let event_loop = winit::event_loop::EventLoop::new(); let window = winit::window::Window::new(&event_loop).unwrap(); let physical_size = window.inner_size(); let mut viewport = Viewport::with_physical_size( Size::new(physical_size.width, physical_size.height), window.scale_factor(), ); let instance = wgpu::Instance::new(wgpu::BackendBit::PRIMARY); let surface = unsafe { instance.create_surface(&window) }; let (mut device, queue) = futures::executor::block_on(async { let adapter = instance .request_adapter(&wgpu::RequestAdapterOptions { power_preference: wgpu::PowerPreference::Default, compatible_surface: Some(&surface), }) .await .unwrap(); adapter .request_device( &wgpu::DeviceDescriptor { features: wgpu::Features::PUSH_CONSTANTS|wgpu::Features::SAMPLED_TEXTURE_ARRAY_NON_UNIFORM_INDEXING, limits: wgpu::Limits { max_push_constant_size: 128, ..Default::default() }, shader_validation: false, }, None, ) .await .unwrap() }); let mut resized = false; let mut staging_belt = wgpu::util::StagingBelt::new(5 * 1024); let mut local_pool = futures::executor::LocalPool::new(); let mut controls = controls::Controls::new(&device); let (mut swap_chain, mut renderer, asset_pack, particle_renderer, particle_system, planet_renderer, star_renderer) = { let mut encoder = device.create_command_encoder( &wgpu::CommandEncoderDescriptor { label: None }, ); let swap_chain_descriptor = generate_swap_chain_descriptor(&window, controls.render_options.scale_factor); let swap_chain = device.create_swap_chain(&surface, &swap_chain_descriptor); let mut path_pool = assets::AssetPack::create_path_pool(); assets::AssetPack::collect_paths(&mut path_pool, &std::path::PathBuf::from("assets/shader_modules/")); let mut asset_pack = assets::AssetPack::default(); asset_pack.load(&device, &queue, &mut encoder, None, None, None, &path_pool).unwrap(); let mipmap_generator = assets::MipmapGenerator::new(&device, &asset_pack); let renderer = renderer::Renderer::new(&mut device, &swap_chain_descriptor, &controls.render_options, &asset_pack); let mut path_pool = assets::AssetPack::create_path_pool(); assets::AssetPack::collect_paths(&mut path_pool, &std::path::PathBuf::from("assets/example/meshes/hex/")); assets::AssetPack::collect_paths(&mut path_pool, &std::path::PathBuf::from("assets/textures/")); asset_pack.load(&device, &queue, &mut encoder, Some(&renderer.bind_group_layouts.surface_pass_bind_group_layout), Some(&renderer.sampler), Some(&mipmap_generator), &path_pool).unwrap(); let particle_renderer = particle::ParticleRenderer::new(&device, &renderer, &asset_pack); let particle_system = crate::particle::ParticleSystem::new(&device, &particle_renderer, 512); { let matrices = [ controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 0, 0)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 0, 1)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 0, 2)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 0, 3)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 1, 0)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 1, 1)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 1, 2)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 1, 3)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 2, 0)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 2, 1)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 2, 2)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 2, 3)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 3, 0)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 3, 1)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 3, 2)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 3, 3)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 4, 0)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 4, 1)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 4, 2)), controls.planet.surface_matrix(&crate::planet::TriangleCoordinate::new(controls.planet.gp_index, [5, 5, 5], 4, 3)), ]; particle_system.generate_clouds(&queue, &matrices); } let mut planet_renderer = planet::PlanetRenderer::new(&device, &renderer, &asset_pack); controls.planet.generate_terrain_and_selection_texture(&queue); controls.planet.generate_atmosphere(&device, &mut encoder, &planet_renderer); planet_renderer.generate_bind_group(&device, &renderer, &asset_pack, &controls.planet); let star_renderer = star::StarRenderer::new(&device, &renderer, &asset_pack); staging_belt.finish(); queue.submit(Some(encoder.finish())); (swap_chain, renderer, asset_pack, particle_renderer, particle_system, planet_renderer, star_renderer) }; let cursor_position = conversion::cursor_position(controls.pointer_position, viewport.scale_factor()); let mut gui_debug = Debug::new(); let mut gui_renderer = Renderer::new(Backend::new(&mut device, Settings::default())); let mut gui_state = program::State::new( controls, viewport.logical_size(), cursor_position, &mut gui_renderer, &mut gui_debug, ); gui_state.queue_message(controls::Message::Resized(physical_size)); event_loop.run(move |event, _, control_flow| { *control_flow = winit::event_loop::ControlFlow::Wait; match event { Event::WindowEvent { event, .. } => { match event { WindowEvent::KeyboardInput { input, .. } => { gui_state.queue_message(controls::Message::KeyboardInput(input)); }, WindowEvent::CursorEntered { .. } => { gui_state.queue_message(controls::Message::CursorEntered); }, WindowEvent::CursorLeft { .. } => { gui_state.queue_message(controls::Message::CursorLeft); }, WindowEvent::MouseWheel { delta, phase, .. } => { gui_state.queue_message(controls::Message::MouseWheel(delta, phase)); }, WindowEvent::ModifiersChanged(new_modifiers) => { gui_state.queue_message(controls::Message::ModifiersChanged(new_modifiers)); }, WindowEvent::CursorMoved { position, .. } => { gui_state.queue_message(controls::Message::CursorMoved(position)); }, WindowEvent::MouseInput { state, button, .. } => { gui_state.queue_message(controls::Message::MouseInput(button, state)); }, WindowEvent::Resized(new_size) => { gui_state.queue_message(controls::Message::Resized(new_size)); viewport = Viewport::with_physical_size( Size::new(new_size.width, new_size.height), window.scale_factor(), ); resized = true; }, WindowEvent::CloseRequested => { *control_flow = winit::event_loop::ControlFlow::Exit; }, _ => {} } let program = gui_state.program(); if let Some(event) = iced_winit::conversion::window_event( &event, window.scale_factor(), program.modifiers, ) { gui_state.queue_event(event); } } Event::MainEventsCleared => { if !gui_state.is_queue_empty() { let program = gui_state.program(); let cursor_position = conversion::cursor_position(program.pointer_position, viewport.scale_factor()); let _ = gui_state.update( viewport.logical_size(), cursor_position, None, &mut gui_renderer, &mut gui_debug, ); window.request_redraw(); } } Event::RedrawRequested(_) => { let controls = gui_state.program(); if resized { let swap_chain_descriptor = generate_swap_chain_descriptor(&window, controls.render_options.scale_factor); swap_chain = device.create_swap_chain(&surface, &swap_chain_descriptor); renderer.resize(&mut device, &swap_chain_descriptor); resized = false; } let mut encoder = device.create_command_encoder( &wgpu::CommandEncoderDescriptor { label: None }, ); renderer.update_instances( &mut encoder, &queue, &[ glam::Mat4::from_scale_rotation_translation(glam::Vec3::splat(2.0), glam::Quat::from_rotation_x(-0.1*std::f32::consts::PI), glam::Vec3::new(0.0, 14.5, 0.0)), glam::Mat4::from_scale_rotation_translation(glam::Vec3::splat(2.0), glam::Quat::identity(), glam::Vec3::new(14.5, 0.0, 0.0)), glam::Mat4::from_scale_rotation_translation(glam::Vec3::new(20.0, 20.0, 40.0), glam::Quat::identity(), glam::Vec3::new(0.0, 0.0, 20.0)), controls.selection_matrix, glam::Mat4::from_scale(glam::Vec3::splat(controls.planet.surface_radius())), glam::Mat4::from_scale(glam::Vec3::splat(controls.planet.atmosphere_radius())), glam::Mat4::from_scale_rotation_translation(glam::Vec3::splat(500.0), glam::Quat::identity(), glam::Vec3::new(0.0, 0.0, 5000.0)), glam::Mat4::from_scale_rotation_translation(glam::Vec3::splat(500.0*1.75), glam::Quat::identity(), glam::Vec3::new(0.0, 0.0, 5000.0)), glam::Mat4::identity(), ] ); renderer.update_camera(&mut encoder, &queue, 8, &controls.camera); { let mut surface_pass = renderer.render_surface_pass(&mut encoder); surface_pass.set_pipeline(&renderer.render_pipelines.surface_pass_pipeline); asset_pack.meshes[&std::path::PathBuf::from("assets/example/meshes/hex/hex/Circle")].render(&mut surface_pass, 3..4); star_renderer.render_surface(&mut surface_pass, 6..7); planet_renderer.render_surface(&mut surface_pass, 4..5); particle_renderer.render_surface(&mut surface_pass, &particle_system, 8..9); } { let mut volumetric_pass = renderer.render_volumetric_pass(&mut encoder); planet_renderer.render_atmosphere(&mut volumetric_pass, 5..6); star_renderer.render_atmosphere(&mut volumetric_pass, 7..8); } let frame = swap_chain.get_current_frame().unwrap(); renderer.render_frame(&mut encoder, &frame.output.view); let mouse_interaction = gui_renderer.backend_mut().draw( &mut device, &mut staging_belt, &mut encoder, &frame.output.view, &viewport, gui_state.primitive(), &gui_debug.overlay(), ); window.set_cursor_icon( iced_winit::conversion::mouse_interaction(mouse_interaction) ); staging_belt.finish(); queue.submit(Some(encoder.finish())); local_pool.spawner().spawn(staging_belt.recall()).unwrap(); local_pool.run_until_stalled(); } _ => {} } }) }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Device address and endpoint control"] pub addr_endp: ADDR_ENDP, #[doc = "0x04 - Interrupt endpoint 1. Only valid for HOST mode."] pub addr_endp1: ADDR_ENDP1, #[doc = "0x08 - Interrupt endpoint 2. Only valid for HOST mode."] pub addr_endp2: ADDR_ENDP2, #[doc = "0x0c - Interrupt endpoint 3. Only valid for HOST mode."] pub addr_endp3: ADDR_ENDP3, #[doc = "0x10 - Interrupt endpoint 4. Only valid for HOST mode."] pub addr_endp4: ADDR_ENDP4, #[doc = "0x14 - Interrupt endpoint 5. Only valid for HOST mode."] pub addr_endp5: ADDR_ENDP5, #[doc = "0x18 - Interrupt endpoint 6. Only valid for HOST mode."] pub addr_endp6: ADDR_ENDP6, #[doc = "0x1c - Interrupt endpoint 7. Only valid for HOST mode."] pub addr_endp7: ADDR_ENDP7, #[doc = "0x20 - Interrupt endpoint 8. Only valid for HOST mode."] pub addr_endp8: ADDR_ENDP8, #[doc = "0x24 - Interrupt endpoint 9. Only valid for HOST mode."] pub addr_endp9: ADDR_ENDP9, #[doc = "0x28 - Interrupt endpoint 10. Only valid for HOST mode."] pub addr_endp10: ADDR_ENDP10, #[doc = "0x2c - Interrupt endpoint 11. Only valid for HOST mode."] pub addr_endp11: ADDR_ENDP11, #[doc = "0x30 - Interrupt endpoint 12. Only valid for HOST mode."] pub addr_endp12: ADDR_ENDP12, #[doc = "0x34 - Interrupt endpoint 13. Only valid for HOST mode."] pub addr_endp13: ADDR_ENDP13, #[doc = "0x38 - Interrupt endpoint 14. Only valid for HOST mode."] pub addr_endp14: ADDR_ENDP14, #[doc = "0x3c - Interrupt endpoint 15. Only valid for HOST mode."] pub addr_endp15: ADDR_ENDP15, #[doc = "0x40 - Main control register"] pub main_ctrl: MAIN_CTRL, #[doc = "0x44 - Set the SOF (Start of Frame) frame number in the host controller. The SOF packet is sent every 1ms and the host will increment the frame number by 1 each time."] pub sof_wr: SOF_WR, #[doc = "0x48 - Read the last SOF (Start of Frame) frame number seen. In device mode the last SOF received from the host. In host mode the last SOF sent by the host."] pub sof_rd: SOF_RD, #[doc = "0x4c - SIE control register"] pub sie_ctrl: SIE_CTRL, #[doc = "0x50 - SIE status register"] pub sie_status: SIE_STATUS, #[doc = "0x54 - interrupt endpoint control register"] pub int_ep_ctrl: INT_EP_CTRL, #[doc = "0x58 - Buffer status register. A bit set here indicates that a buffer has completed on the endpoint (if the buffer interrupt is enabled). It is possible for 2 buffers to be completed, so clearing the buffer status bit may instantly re set it on the next clock cycle."] pub buff_status: BUFF_STATUS, #[doc = "0x5c - Which of the double buffers should be handled. Only valid if using an interrupt per buffer (i.e. not per 2 buffers). Not valid for host interrupt endpoint polling because they are only single buffered."] pub buff_cpu_should_handle: BUFF_CPU_SHOULD_HANDLE, #[doc = "0x60 - Device only: Can be set to ignore the buffer control register for this endpoint in case you would like to revoke a buffer. A NAK will be sent for every access to the endpoint until this bit is cleared. A corresponding bit in `EP_ABORT_DONE` is set when it is safe to modify the buffer control register."] pub ep_abort: EP_ABORT, #[doc = "0x64 - Device only: Used in conjunction with `EP_ABORT`. Set once an endpoint is idle so the programmer knows it is safe to modify the buffer control register."] pub ep_abort_done: EP_ABORT_DONE, #[doc = "0x68 - Device: this bit must be set in conjunction with the `STALL` bit in the buffer control register to send a STALL on EP0. The device controller clears these bits when a SETUP packet is received because the USB spec requires that a STALL condition is cleared when a SETUP packet is received."] pub ep_stall_arm: EP_STALL_ARM, #[doc = "0x6c - Used by the host controller. Sets the wait time in microseconds before trying again if the device replies with a NAK."] pub nak_poll: NAK_POLL, #[doc = "0x70 - Device: bits are set when the `IRQ_ON_NAK` or `IRQ_ON_STALL` bits are set. For EP0 this comes from `SIE_CTRL`. For all other endpoints it comes from the endpoint control register."] pub ep_status_stall_nak: EP_STATUS_STALL_NAK, #[doc = "0x74 - Where to connect the USB controller. Should be to_phy by default."] pub usb_muxing: USB_MUXING, #[doc = "0x78 - Overrides for the power signals in the event that the VBUS signals are not hooked up to GPIO. Set the value of the override and then the override enable to switch over to the override value."] pub usb_pwr: USB_PWR, #[doc = "0x7c - This register allows for direct control of the USB phy. Use in conjunction with usbphy_direct_override register to enable each override bit."] pub usbphy_direct: USBPHY_DIRECT, #[doc = "0x80 - Override enable for each control in usbphy_direct"] pub usbphy_direct_override: USBPHY_DIRECT_OVERRIDE, #[doc = "0x84 - Used to adjust trim values of USB phy pull down resistors."] pub usbphy_trim: USBPHY_TRIM, _reserved34: [u8; 4usize], #[doc = "0x8c - Raw Interrupts"] pub intr: INTR, #[doc = "0x90 - Interrupt Enable"] pub inte: INTE, #[doc = "0x94 - Interrupt Force"] pub intf: INTF, #[doc = "0x98 - Interrupt status after masking & forcing"] pub ints: INTS, } #[doc = "Device address and endpoint control\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp](addr_endp) module"] pub type ADDR_ENDP = crate::Reg<u32, _ADDR_ENDP>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP; #[doc = "`read()` method returns [addr_endp::R](addr_endp::R) reader structure"] impl crate::Readable for ADDR_ENDP {} #[doc = "`write(|w| ..)` method takes [addr_endp::W](addr_endp::W) writer structure"] impl crate::Writable for ADDR_ENDP {} #[doc = "Device address and endpoint control"] pub mod addr_endp; #[doc = "Interrupt endpoint 1. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp1](addr_endp1) module"] pub type ADDR_ENDP1 = crate::Reg<u32, _ADDR_ENDP1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP1; #[doc = "`read()` method returns [addr_endp1::R](addr_endp1::R) reader structure"] impl crate::Readable for ADDR_ENDP1 {} #[doc = "`write(|w| ..)` method takes [addr_endp1::W](addr_endp1::W) writer structure"] impl crate::Writable for ADDR_ENDP1 {} #[doc = "Interrupt endpoint 1. Only valid for HOST mode."] pub mod addr_endp1; #[doc = "Interrupt endpoint 2. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp2](addr_endp2) module"] pub type ADDR_ENDP2 = crate::Reg<u32, _ADDR_ENDP2>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP2; #[doc = "`read()` method returns [addr_endp2::R](addr_endp2::R) reader structure"] impl crate::Readable for ADDR_ENDP2 {} #[doc = "`write(|w| ..)` method takes [addr_endp2::W](addr_endp2::W) writer structure"] impl crate::Writable for ADDR_ENDP2 {} #[doc = "Interrupt endpoint 2. Only valid for HOST mode."] pub mod addr_endp2; #[doc = "Interrupt endpoint 3. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp3](addr_endp3) module"] pub type ADDR_ENDP3 = crate::Reg<u32, _ADDR_ENDP3>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP3; #[doc = "`read()` method returns [addr_endp3::R](addr_endp3::R) reader structure"] impl crate::Readable for ADDR_ENDP3 {} #[doc = "`write(|w| ..)` method takes [addr_endp3::W](addr_endp3::W) writer structure"] impl crate::Writable for ADDR_ENDP3 {} #[doc = "Interrupt endpoint 3. Only valid for HOST mode."] pub mod addr_endp3; #[doc = "Interrupt endpoint 4. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp4](addr_endp4) module"] pub type ADDR_ENDP4 = crate::Reg<u32, _ADDR_ENDP4>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP4; #[doc = "`read()` method returns [addr_endp4::R](addr_endp4::R) reader structure"] impl crate::Readable for ADDR_ENDP4 {} #[doc = "`write(|w| ..)` method takes [addr_endp4::W](addr_endp4::W) writer structure"] impl crate::Writable for ADDR_ENDP4 {} #[doc = "Interrupt endpoint 4. Only valid for HOST mode."] pub mod addr_endp4; #[doc = "Interrupt endpoint 5. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp5](addr_endp5) module"] pub type ADDR_ENDP5 = crate::Reg<u32, _ADDR_ENDP5>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP5; #[doc = "`read()` method returns [addr_endp5::R](addr_endp5::R) reader structure"] impl crate::Readable for ADDR_ENDP5 {} #[doc = "`write(|w| ..)` method takes [addr_endp5::W](addr_endp5::W) writer structure"] impl crate::Writable for ADDR_ENDP5 {} #[doc = "Interrupt endpoint 5. Only valid for HOST mode."] pub mod addr_endp5; #[doc = "Interrupt endpoint 6. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp6](addr_endp6) module"] pub type ADDR_ENDP6 = crate::Reg<u32, _ADDR_ENDP6>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP6; #[doc = "`read()` method returns [addr_endp6::R](addr_endp6::R) reader structure"] impl crate::Readable for ADDR_ENDP6 {} #[doc = "`write(|w| ..)` method takes [addr_endp6::W](addr_endp6::W) writer structure"] impl crate::Writable for ADDR_ENDP6 {} #[doc = "Interrupt endpoint 6. Only valid for HOST mode."] pub mod addr_endp6; #[doc = "Interrupt endpoint 7. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp7](addr_endp7) module"] pub type ADDR_ENDP7 = crate::Reg<u32, _ADDR_ENDP7>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP7; #[doc = "`read()` method returns [addr_endp7::R](addr_endp7::R) reader structure"] impl crate::Readable for ADDR_ENDP7 {} #[doc = "`write(|w| ..)` method takes [addr_endp7::W](addr_endp7::W) writer structure"] impl crate::Writable for ADDR_ENDP7 {} #[doc = "Interrupt endpoint 7. Only valid for HOST mode."] pub mod addr_endp7; #[doc = "Interrupt endpoint 8. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp8](addr_endp8) module"] pub type ADDR_ENDP8 = crate::Reg<u32, _ADDR_ENDP8>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP8; #[doc = "`read()` method returns [addr_endp8::R](addr_endp8::R) reader structure"] impl crate::Readable for ADDR_ENDP8 {} #[doc = "`write(|w| ..)` method takes [addr_endp8::W](addr_endp8::W) writer structure"] impl crate::Writable for ADDR_ENDP8 {} #[doc = "Interrupt endpoint 8. Only valid for HOST mode."] pub mod addr_endp8; #[doc = "Interrupt endpoint 9. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp9](addr_endp9) module"] pub type ADDR_ENDP9 = crate::Reg<u32, _ADDR_ENDP9>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP9; #[doc = "`read()` method returns [addr_endp9::R](addr_endp9::R) reader structure"] impl crate::Readable for ADDR_ENDP9 {} #[doc = "`write(|w| ..)` method takes [addr_endp9::W](addr_endp9::W) writer structure"] impl crate::Writable for ADDR_ENDP9 {} #[doc = "Interrupt endpoint 9. Only valid for HOST mode."] pub mod addr_endp9; #[doc = "Interrupt endpoint 10. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp10](addr_endp10) module"] pub type ADDR_ENDP10 = crate::Reg<u32, _ADDR_ENDP10>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP10; #[doc = "`read()` method returns [addr_endp10::R](addr_endp10::R) reader structure"] impl crate::Readable for ADDR_ENDP10 {} #[doc = "`write(|w| ..)` method takes [addr_endp10::W](addr_endp10::W) writer structure"] impl crate::Writable for ADDR_ENDP10 {} #[doc = "Interrupt endpoint 10. Only valid for HOST mode."] pub mod addr_endp10; #[doc = "Interrupt endpoint 11. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp11](addr_endp11) module"] pub type ADDR_ENDP11 = crate::Reg<u32, _ADDR_ENDP11>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP11; #[doc = "`read()` method returns [addr_endp11::R](addr_endp11::R) reader structure"] impl crate::Readable for ADDR_ENDP11 {} #[doc = "`write(|w| ..)` method takes [addr_endp11::W](addr_endp11::W) writer structure"] impl crate::Writable for ADDR_ENDP11 {} #[doc = "Interrupt endpoint 11. Only valid for HOST mode."] pub mod addr_endp11; #[doc = "Interrupt endpoint 12. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp12](addr_endp12) module"] pub type ADDR_ENDP12 = crate::Reg<u32, _ADDR_ENDP12>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP12; #[doc = "`read()` method returns [addr_endp12::R](addr_endp12::R) reader structure"] impl crate::Readable for ADDR_ENDP12 {} #[doc = "`write(|w| ..)` method takes [addr_endp12::W](addr_endp12::W) writer structure"] impl crate::Writable for ADDR_ENDP12 {} #[doc = "Interrupt endpoint 12. Only valid for HOST mode."] pub mod addr_endp12; #[doc = "Interrupt endpoint 13. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp13](addr_endp13) module"] pub type ADDR_ENDP13 = crate::Reg<u32, _ADDR_ENDP13>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP13; #[doc = "`read()` method returns [addr_endp13::R](addr_endp13::R) reader structure"] impl crate::Readable for ADDR_ENDP13 {} #[doc = "`write(|w| ..)` method takes [addr_endp13::W](addr_endp13::W) writer structure"] impl crate::Writable for ADDR_ENDP13 {} #[doc = "Interrupt endpoint 13. Only valid for HOST mode."] pub mod addr_endp13; #[doc = "Interrupt endpoint 14. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp14](addr_endp14) module"] pub type ADDR_ENDP14 = crate::Reg<u32, _ADDR_ENDP14>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP14; #[doc = "`read()` method returns [addr_endp14::R](addr_endp14::R) reader structure"] impl crate::Readable for ADDR_ENDP14 {} #[doc = "`write(|w| ..)` method takes [addr_endp14::W](addr_endp14::W) writer structure"] impl crate::Writable for ADDR_ENDP14 {} #[doc = "Interrupt endpoint 14. Only valid for HOST mode."] pub mod addr_endp14; #[doc = "Interrupt endpoint 15. Only valid for HOST mode.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [addr_endp15](addr_endp15) module"] pub type ADDR_ENDP15 = crate::Reg<u32, _ADDR_ENDP15>; #[allow(missing_docs)] #[doc(hidden)] pub struct _ADDR_ENDP15; #[doc = "`read()` method returns [addr_endp15::R](addr_endp15::R) reader structure"] impl crate::Readable for ADDR_ENDP15 {} #[doc = "`write(|w| ..)` method takes [addr_endp15::W](addr_endp15::W) writer structure"] impl crate::Writable for ADDR_ENDP15 {} #[doc = "Interrupt endpoint 15. Only valid for HOST mode."] pub mod addr_endp15; #[doc = "Main control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [main_ctrl](main_ctrl) module"] pub type MAIN_CTRL = crate::Reg<u32, _MAIN_CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MAIN_CTRL; #[doc = "`read()` method returns [main_ctrl::R](main_ctrl::R) reader structure"] impl crate::Readable for MAIN_CTRL {} #[doc = "`write(|w| ..)` method takes [main_ctrl::W](main_ctrl::W) writer structure"] impl crate::Writable for MAIN_CTRL {} #[doc = "Main control register"] pub mod main_ctrl; #[doc = "Set the SOF (Start of Frame) frame number in the host controller. The SOF packet is sent every 1ms and the host will increment the frame number by 1 each time.\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sof_wr](sof_wr) module"] pub type SOF_WR = crate::Reg<u32, _SOF_WR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SOF_WR; #[doc = "`write(|w| ..)` method takes [sof_wr::W](sof_wr::W) writer structure"] impl crate::Writable for SOF_WR {} #[doc = "Set the SOF (Start of Frame) frame number in the host controller. The SOF packet is sent every 1ms and the host will increment the frame number by 1 each time."] pub mod sof_wr; #[doc = "Read the last SOF (Start of Frame) frame number seen. In device mode the last SOF received from the host. In host mode the last SOF sent by the host.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sof_rd](sof_rd) module"] pub type SOF_RD = crate::Reg<u32, _SOF_RD>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SOF_RD; #[doc = "`read()` method returns [sof_rd::R](sof_rd::R) reader structure"] impl crate::Readable for SOF_RD {} #[doc = "Read the last SOF (Start of Frame) frame number seen. In device mode the last SOF received from the host. In host mode the last SOF sent by the host."] pub mod sof_rd; #[doc = "SIE control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sie_ctrl](sie_ctrl) module"] pub type SIE_CTRL = crate::Reg<u32, _SIE_CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SIE_CTRL; #[doc = "`read()` method returns [sie_ctrl::R](sie_ctrl::R) reader structure"] impl crate::Readable for SIE_CTRL {} #[doc = "`write(|w| ..)` method takes [sie_ctrl::W](sie_ctrl::W) writer structure"] impl crate::Writable for SIE_CTRL {} #[doc = "SIE control register"] pub mod sie_ctrl; #[doc = "SIE status register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sie_status](sie_status) module"] pub type SIE_STATUS = crate::Reg<u32, _SIE_STATUS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SIE_STATUS; #[doc = "`read()` method returns [sie_status::R](sie_status::R) reader structure"] impl crate::Readable for SIE_STATUS {} #[doc = "`write(|w| ..)` method takes [sie_status::W](sie_status::W) writer structure"] impl crate::Writable for SIE_STATUS {} #[doc = "SIE status register"] pub mod sie_status; #[doc = "interrupt endpoint control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [int_ep_ctrl](int_ep_ctrl) module"] pub type INT_EP_CTRL = crate::Reg<u32, _INT_EP_CTRL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INT_EP_CTRL; #[doc = "`read()` method returns [int_ep_ctrl::R](int_ep_ctrl::R) reader structure"] impl crate::Readable for INT_EP_CTRL {} #[doc = "`write(|w| ..)` method takes [int_ep_ctrl::W](int_ep_ctrl::W) writer structure"] impl crate::Writable for INT_EP_CTRL {} #[doc = "interrupt endpoint control register"] pub mod int_ep_ctrl; #[doc = "Buffer status register. A bit set here indicates that a buffer has completed on the endpoint (if the buffer interrupt is enabled). It is possible for 2 buffers to be completed, so clearing the buffer status bit may instantly re set it on the next clock cycle.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [buff_status](buff_status) module"] pub type BUFF_STATUS = crate::Reg<u32, _BUFF_STATUS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _BUFF_STATUS; #[doc = "`read()` method returns [buff_status::R](buff_status::R) reader structure"] impl crate::Readable for BUFF_STATUS {} #[doc = "`write(|w| ..)` method takes [buff_status::W](buff_status::W) writer structure"] impl crate::Writable for BUFF_STATUS {} #[doc = "Buffer status register. A bit set here indicates that a buffer has completed on the endpoint (if the buffer interrupt is enabled). It is possible for 2 buffers to be completed, so clearing the buffer status bit may instantly re set it on the next clock cycle."] pub mod buff_status; #[doc = "Which of the double buffers should be handled. Only valid if using an interrupt per buffer (i.e. not per 2 buffers). Not valid for host interrupt endpoint polling because they are only single buffered.\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [buff_cpu_should_handle](buff_cpu_should_handle) module"] pub type BUFF_CPU_SHOULD_HANDLE = crate::Reg<u32, _BUFF_CPU_SHOULD_HANDLE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _BUFF_CPU_SHOULD_HANDLE; #[doc = "`read()` method returns [buff_cpu_should_handle::R](buff_cpu_should_handle::R) reader structure"] impl crate::Readable for BUFF_CPU_SHOULD_HANDLE {} #[doc = "Which of the double buffers should be handled. Only valid if using an interrupt per buffer (i.e. not per 2 buffers). Not valid for host interrupt endpoint polling because they are only single buffered."] pub mod buff_cpu_should_handle; #[doc = "Device only: Can be set to ignore the buffer control register for this endpoint in case you would like to revoke a buffer. A NAK will be sent for every access to the endpoint until this bit is cleared. A corresponding bit in `EP_ABORT_DONE` is set when it is safe to modify the buffer control register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep_abort](ep_abort) module"] pub type EP_ABORT = crate::Reg<u32, _EP_ABORT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EP_ABORT; #[doc = "`read()` method returns [ep_abort::R](ep_abort::R) reader structure"] impl crate::Readable for EP_ABORT {} #[doc = "`write(|w| ..)` method takes [ep_abort::W](ep_abort::W) writer structure"] impl crate::Writable for EP_ABORT {} #[doc = "Device only: Can be set to ignore the buffer control register for this endpoint in case you would like to revoke a buffer. A NAK will be sent for every access to the endpoint until this bit is cleared. A corresponding bit in `EP_ABORT_DONE` is set when it is safe to modify the buffer control register."] pub mod ep_abort; #[doc = "Device only: Used in conjunction with `EP_ABORT`. Set once an endpoint is idle so the programmer knows it is safe to modify the buffer control register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep_abort_done](ep_abort_done) module"] pub type EP_ABORT_DONE = crate::Reg<u32, _EP_ABORT_DONE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EP_ABORT_DONE; #[doc = "`read()` method returns [ep_abort_done::R](ep_abort_done::R) reader structure"] impl crate::Readable for EP_ABORT_DONE {} #[doc = "`write(|w| ..)` method takes [ep_abort_done::W](ep_abort_done::W) writer structure"] impl crate::Writable for EP_ABORT_DONE {} #[doc = "Device only: Used in conjunction with `EP_ABORT`. Set once an endpoint is idle so the programmer knows it is safe to modify the buffer control register."] pub mod ep_abort_done; #[doc = "Device: this bit must be set in conjunction with the `STALL` bit in the buffer control register to send a STALL on EP0. The device controller clears these bits when a SETUP packet is received because the USB spec requires that a STALL condition is cleared when a SETUP packet is received.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep_stall_arm](ep_stall_arm) module"] pub type EP_STALL_ARM = crate::Reg<u32, _EP_STALL_ARM>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EP_STALL_ARM; #[doc = "`read()` method returns [ep_stall_arm::R](ep_stall_arm::R) reader structure"] impl crate::Readable for EP_STALL_ARM {} #[doc = "`write(|w| ..)` method takes [ep_stall_arm::W](ep_stall_arm::W) writer structure"] impl crate::Writable for EP_STALL_ARM {} #[doc = "Device: this bit must be set in conjunction with the `STALL` bit in the buffer control register to send a STALL on EP0. The device controller clears these bits when a SETUP packet is received because the USB spec requires that a STALL condition is cleared when a SETUP packet is received."] pub mod ep_stall_arm; #[doc = "Used by the host controller. Sets the wait time in microseconds before trying again if the device replies with a NAK.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [nak_poll](nak_poll) module"] pub type NAK_POLL = crate::Reg<u32, _NAK_POLL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _NAK_POLL; #[doc = "`read()` method returns [nak_poll::R](nak_poll::R) reader structure"] impl crate::Readable for NAK_POLL {} #[doc = "`write(|w| ..)` method takes [nak_poll::W](nak_poll::W) writer structure"] impl crate::Writable for NAK_POLL {} #[doc = "Used by the host controller. Sets the wait time in microseconds before trying again if the device replies with a NAK."] pub mod nak_poll; #[doc = "Device: bits are set when the `IRQ_ON_NAK` or `IRQ_ON_STALL` bits are set. For EP0 this comes from `SIE_CTRL`. For all other endpoints it comes from the endpoint control register.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ep_status_stall_nak](ep_status_stall_nak) module"] pub type EP_STATUS_STALL_NAK = crate::Reg<u32, _EP_STATUS_STALL_NAK>; #[allow(missing_docs)] #[doc(hidden)] pub struct _EP_STATUS_STALL_NAK; #[doc = "`read()` method returns [ep_status_stall_nak::R](ep_status_stall_nak::R) reader structure"] impl crate::Readable for EP_STATUS_STALL_NAK {} #[doc = "`write(|w| ..)` method takes [ep_status_stall_nak::W](ep_status_stall_nak::W) writer structure"] impl crate::Writable for EP_STATUS_STALL_NAK {} #[doc = "Device: bits are set when the `IRQ_ON_NAK` or `IRQ_ON_STALL` bits are set. For EP0 this comes from `SIE_CTRL`. For all other endpoints it comes from the endpoint control register."] pub mod ep_status_stall_nak; #[doc = "Where to connect the USB controller. Should be to_phy by default.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [usb_muxing](usb_muxing) module"] pub type USB_MUXING = crate::Reg<u32, _USB_MUXING>; #[allow(missing_docs)] #[doc(hidden)] pub struct _USB_MUXING; #[doc = "`read()` method returns [usb_muxing::R](usb_muxing::R) reader structure"] impl crate::Readable for USB_MUXING {} #[doc = "`write(|w| ..)` method takes [usb_muxing::W](usb_muxing::W) writer structure"] impl crate::Writable for USB_MUXING {} #[doc = "Where to connect the USB controller. Should be to_phy by default."] pub mod usb_muxing; #[doc = "Overrides for the power signals in the event that the VBUS signals are not hooked up to GPIO. Set the value of the override and then the override enable to switch over to the override value.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [usb_pwr](usb_pwr) module"] pub type USB_PWR = crate::Reg<u32, _USB_PWR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _USB_PWR; #[doc = "`read()` method returns [usb_pwr::R](usb_pwr::R) reader structure"] impl crate::Readable for USB_PWR {} #[doc = "`write(|w| ..)` method takes [usb_pwr::W](usb_pwr::W) writer structure"] impl crate::Writable for USB_PWR {} #[doc = "Overrides for the power signals in the event that the VBUS signals are not hooked up to GPIO. Set the value of the override and then the override enable to switch over to the override value."] pub mod usb_pwr; #[doc = "This register allows for direct control of the USB phy. Use in conjunction with usbphy_direct_override register to enable each override bit.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [usbphy_direct](usbphy_direct) module"] pub type USBPHY_DIRECT = crate::Reg<u32, _USBPHY_DIRECT>; #[allow(missing_docs)] #[doc(hidden)] pub struct _USBPHY_DIRECT; #[doc = "`read()` method returns [usbphy_direct::R](usbphy_direct::R) reader structure"] impl crate::Readable for USBPHY_DIRECT {} #[doc = "`write(|w| ..)` method takes [usbphy_direct::W](usbphy_direct::W) writer structure"] impl crate::Writable for USBPHY_DIRECT {} #[doc = "This register allows for direct control of the USB phy. Use in conjunction with usbphy_direct_override register to enable each override bit."] pub mod usbphy_direct; #[doc = "Override enable for each control in usbphy_direct\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [usbphy_direct_override](usbphy_direct_override) module"] pub type USBPHY_DIRECT_OVERRIDE = crate::Reg<u32, _USBPHY_DIRECT_OVERRIDE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _USBPHY_DIRECT_OVERRIDE; #[doc = "`read()` method returns [usbphy_direct_override::R](usbphy_direct_override::R) reader structure"] impl crate::Readable for USBPHY_DIRECT_OVERRIDE {} #[doc = "`write(|w| ..)` method takes [usbphy_direct_override::W](usbphy_direct_override::W) writer structure"] impl crate::Writable for USBPHY_DIRECT_OVERRIDE {} #[doc = "Override enable for each control in usbphy_direct"] pub mod usbphy_direct_override; #[doc = "Used to adjust trim values of USB phy pull down resistors.\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [usbphy_trim](usbphy_trim) module"] pub type USBPHY_TRIM = crate::Reg<u32, _USBPHY_TRIM>; #[allow(missing_docs)] #[doc(hidden)] pub struct _USBPHY_TRIM; #[doc = "`read()` method returns [usbphy_trim::R](usbphy_trim::R) reader structure"] impl crate::Readable for USBPHY_TRIM {} #[doc = "`write(|w| ..)` method takes [usbphy_trim::W](usbphy_trim::W) writer structure"] impl crate::Writable for USBPHY_TRIM {} #[doc = "Used to adjust trim values of USB phy pull down resistors."] pub mod usbphy_trim; #[doc = "Raw Interrupts\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [intr](intr) module"] pub type INTR = crate::Reg<u32, _INTR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTR; #[doc = "`read()` method returns [intr::R](intr::R) reader structure"] impl crate::Readable for INTR {} #[doc = "Raw Interrupts"] pub mod intr; #[doc = "Interrupt Enable\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [inte](inte) module"] pub type INTE = crate::Reg<u32, _INTE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTE; #[doc = "`read()` method returns [inte::R](inte::R) reader structure"] impl crate::Readable for INTE {} #[doc = "`write(|w| ..)` method takes [inte::W](inte::W) writer structure"] impl crate::Writable for INTE {} #[doc = "Interrupt Enable"] pub mod inte; #[doc = "Interrupt Force\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [intf](intf) module"] pub type INTF = crate::Reg<u32, _INTF>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTF; #[doc = "`read()` method returns [intf::R](intf::R) reader structure"] impl crate::Readable for INTF {} #[doc = "`write(|w| ..)` method takes [intf::W](intf::W) writer structure"] impl crate::Writable for INTF {} #[doc = "Interrupt Force"] pub mod intf; #[doc = "Interrupt status after masking & forcing\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ints](ints) module"] pub type INTS = crate::Reg<u32, _INTS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _INTS; #[doc = "`read()` method returns [ints::R](ints::R) reader structure"] impl crate::Readable for INTS {} #[doc = "Interrupt status after masking & forcing"] pub mod ints;
use std::process::{Command, Stdio}; fn exo4_pipes(){ let ls = Command::new("ls") .stdout(Stdio::piped()) .spawn() .expect(" ls? What is it?"); let ls_stdout = Stdio::from(ls.stdout.expect("Failed")); let process = Command::new("grep") .arg("Hello") .stdin(ls_stdout) .spawn() .expect("Not hello? something wrong with grep"); } fn main() -> std::io::Result<()> { use std::collections::VecDeque; let mut stock_prgm = VecDeque::new(); loop{ let stdin = io::stdin(); use std::io::{self, Write}; let stdout = io::stdout(); let mut out = stdout; out.write(b"-->")?; // `?` sert à « propager l'erreur » dans la fonction appellante // c'est mieux que de crash avec un unwrap ou expect ;) out.flush()?; // On récupère la commande de l'utilisateur let mut user_input = String::with_capacity(256); stdin.read_line(&mut user_input)?; if user_input.trim() == "" { continue } else if user_input.trim() == "exit" { break } let mut user_input_split = user_input.trim().split(" "); let commande = user_input_split.next().unwrap(); let arg = user_input_split; println!("{}",commande); let mut prg=Command::new(commande) .args(arg) .spawn() .unwrap(); //prg.wait().expect("failed to wait on child"); // Partie 5 match prg.try_wait() { Ok(Some(status)) => println!("exited with: {}", status), Ok(None) => { let res = prg.wait(); println!("Etat: {:?}", res); stock_prgm.push_back(prg); // On vérifie les processus en cours println!("Stockage: {:?}", stock_prgm); } Err(e) => println!("Erreur lors de l'attente du wait: {}", e), } } exo4_pipes(); Ok(()) }
use regex::Regex; use serenity::client::Context; use serenity::futures::StreamExt; use serenity::http::CacheHttp; use serenity::model::guild::Member; use serenity::model::id::{GuildId, UserId}; use serenity::model::user::User; use std::ops::Add; #[derive(Debug, Copy, Clone)] pub enum ParameterType { Word, Number, Remainder, User, Timespan, } pub struct RequestParameter { pub(crate) _kind: ParameterType, pub(crate) value: String, } impl RequestParameter { pub fn as_string(&self) -> String { self.value.clone() } pub fn as_int(&self) -> Option<i32> { match self.value.parse() { Ok(v) => Some(v), _ => None, } } pub fn as_u64(&self) -> Option<u64> { match self.value.parse() { Ok(v) => Some(v), _ => None, } } pub async fn as_discord_guild_user(&self, ctx: &Context, guild: &GuildId) -> Option<Member> { let mut cached_guild = guild.to_guild_cached(ctx).await; if let Some(v) = self.as_u64() { let t1 = chrono::Utc::now(); if let Some(guild) = &mut cached_guild { if let Some(user) = guild.members.get(&UserId(v)) { trace!( "Time fetching member from cache: {}", ((chrono::Utc::now() - t1).num_milliseconds()) ); return Some(user.clone()); } } if let Ok(user) = ctx.http().get_member(guild.0, v).await { trace!( "Time fetching member over http: {}", ((chrono::Utc::now() - t1).num_milliseconds()) ); if cached_guild.is_some() { cached_guild .unwrap() .members .insert(UserId(v), user.clone()); } return Some(user); } }; if let Some(guild) = cached_guild { match guild.member_named(self.value.as_str()) { None => {} Some(m) => { return Some(m.clone()); } } } let mut members = guild.members_iter(ctx.http()).boxed(); while let Some(member_result) = members.next().await { if let Ok(member) = member_result { if member.user.name.eq_ignore_ascii_case(self.value.as_str()) { return Some(member); } } } None } pub async fn as_discord_user(&self, ctx: &Context) -> Option<User> { match self.as_u64() { Some(v) => match UserId(v).to_user(ctx).await { Ok(u) => Some(u), _ => None, }, None => None, } } } fn get_parameter_regex(t: &ParameterType) -> &str { match t { ParameterType::Word => (" *(\\w+)"), ParameterType::Number => (" *(\\d+)(?:$| |\n)"), ParameterType::Remainder => (" *(.*)"), ParameterType::User => (" *(?:<@!*(\\d+)>|(\\d+)|(\\w+)(?:$| |\n))"), ParameterType::Timespan => (" *(?\\d+\\.*\\d*[smhd])"), } } pub fn generate_parameter_regex(pars: &[Vec<ParameterType>]) -> Vec<Regex> { let mut a = Vec::new(); for par_types in pars { let mut s = String::new(); for t in par_types { s = s.add(get_parameter_regex(t)); } a.push(Regex::new(s.as_str()).unwrap()); } a }
#![allow(dead_code)] // If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. // The sum of these multiples is 23. // // Find the sum of all the multiples of 3 or 5 below 1000. pub fn problem() -> usize { (1..1000).fold(0, |acc, x| { if x % 3 == 0 || x % 5 == 0 { acc + x } else { acc } }) } #[cfg(test)] mod tests { use super::*; #[test] fn correct_result() { assert_eq!(problem(), 233168); } }
struct Point<T, U> { x: T, y: U, } impl<T, U> Point<T, U> { fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> { Point { x: self.x, y: other.y, } } fn x(&self) -> &T { &self.x } } pub fn generic_struct() { println!("{}", "------------generic string start-------------------"); let string_and_string = Point { x: String::from("generic"), y: String::from("demo"), }; println!("{}", string_and_string.x); println!("{}", string_and_string.y); let mut x = String::from("demo"); let mut y = String::from("generic"); let xpointer = &mut x; let ypointer = &mut y; let string_string = Point { x: xpointer, y: ypointer, }; println!("{}", string_string.x); string_string.x.push_str("_generic"); //cannot borrow `x` as immutable because it is also borrowed as mutable //println!("x value is :{}",x); } pub fn generic_method() { println!("{}", "------------generic method start-------------------"); let p1 = Point { x: 5, y: 10.4 }; let p2 = Point { x: "Hello", y: 'c' }; let p3 = p1.mixup(p2); println!("p3.x = {}, p3.y = {}", p3.x, p3.y); println!("p3.x= {}", p3.x()); }
use criterion::{black_box, criterion_group, criterion_main, BatchSize, BenchmarkId, Criterion}; macro_rules! bench_lib { ($name:ident, $data_fn:expr, $({ $lib_name:expr, $lib_table:expr }),* $(,)?) => { pub fn $name(c: &mut Criterion) { let mut group = c.benchmark_group(stringify!($name)); for size in [1, 8, 32, 128, 512] { let (columns, data) = $data_fn(size); $({ group.bench_with_input(BenchmarkId::new($lib_name, size), &size, |b, _size| { b.iter_batched( || (columns.clone(), data.clone()), |(columns, data)| { let _ = black_box($lib_table(columns, data)); }, BatchSize::SmallInput ); }); })* } group.finish(); } }; } macro_rules! create_bench { ($name:ident, $table:expr) => { bench_lib!( $name, $table, { "tabled", lib_comp::tabled_current::build }, { "tabled_color", lib_comp::tabled_color_current::build }, { "tabled_iter", lib_comp::tabled_current_iter::build }, { "tabled_compact", lib_comp::tabled_current_compact::build }, { "cli_table", lib_comp::cli_table::build }, { "comfy_table", lib_comp::comfy_table::build }, { "term_table", lib_comp::term_table::build }, { "prettytable_rs", lib_comp::prettytable_rs::build }, ); }; } create_bench!(test_empty_table, |size| build_cost_table(size, "", "")); create_bench!(test_const_table, |size| build_cost_table( size, "Hello World", "Hi!" )); create_bench!(test_dynamic_table, build_dynamic_table); create_bench!(test_multiline_table, |size| build_cost_table( size, "H\ne\nl\nlo\nWo\nr\nld", "Hello\n111\n111\ni\n!" )); criterion_group!( benches, test_empty_table, test_const_table, test_dynamic_table, test_multiline_table, ); criterion_main!(benches); fn build_cost_table<H, R>(size: usize, header: H, record: R) -> (Vec<String>, Vec<Vec<String>>) where H: Into<String>, R: Into<String>, { ( vec![header.into(); size], vec![vec![record.into(); size]; size], ) } fn build_dynamic_table(size: usize) -> (Vec<String>, Vec<Vec<String>>) { let mut data = Vec::with_capacity(size); for i in 0..size { let mut row = build_row(size, |i| format!("{i}")); // just make things more complex if i % 2 == 0 { row.sort_by(|a, b| b.cmp(a)); } data.push(row); } let columns = build_row(size, |i| format!("{i}")); (columns, data) } fn build_row(size: usize, f: impl Fn(usize) -> String) -> Vec<String> { let mut row = Vec::with_capacity(size); for i in 0..size { let s = f(i); row.push(s); } row }
/**********************************************************\ | | | hprose | | | | Official WebSite: http://www.hprose.com/ | | http://www.hprose.org/ | | | \**********************************************************/ /**********************************************************\ * * * io/decoders/u64_decoder.rs * * * * hprose u64 decoder for Rust. * * * * LastModified: Sep 26, 2016 * * Author: Chen Fei <cf@hprose.com> * * * \**********************************************************/ use io::{Reader, Decoder, DecoderError, ParserError}; use io::tags::*; use io::reader::cast_error; use io::util::utf8_slice_to_str; use std::result; type Result = result::Result<u64, DecoderError>; pub fn u64_decode(r: &mut Reader, tag: u8) -> Result { match tag { b'0' | TAG_NULL | TAG_EMPTY | TAG_FALSE => Ok(0), b'1' | TAG_TRUE => Ok(1), b'2' => Ok(2), b'3' => Ok(3), b'4' => Ok(4), b'5' => Ok(5), b'6' => Ok(6), b'7' => Ok(7), b'8' => Ok(8), b'9' => Ok(9), TAG_INTEGER | TAG_LONG => read_u64(r), TAG_DOUBLE => read_f64_as_u64(r), TAG_UTF8_CHAR => read_utf8_char_as_u64(r), TAG_STRING => read_string_as_u64(r), TAG_DATE => read_datetime_as_u64(r), TAG_TIME => read_time_as_u64(r), TAG_REF => r.read_ref(), _ => Err(cast_error(tag, "u64")) } } fn read_u64(r: &mut Reader) -> Result { r.byte_reader.read_u64_with_tag(TAG_SEMICOLON).map_err(|e| DecoderError::ParserError(e)) } fn read_f64_as_u64(r: &mut Reader) -> Result { r.byte_reader.read_f64().map(|f| f as u64).map_err(|e| DecoderError::ParserError(e)) } fn read_utf8_char_as_u64(r: &mut Reader) -> Result { r.byte_reader .read_utf8_slice(1) .and_then(|s| utf8_slice_to_str(s).parse::<u64>().map_err(|e| ParserError::ParseIntError(e))) .map_err(|e| DecoderError::ParserError(e)) } fn read_string_as_u64(r: &mut Reader) -> Result { r .read_string_without_tag() .and_then(|s| s.parse::<u64>().map_err(|e| ParserError::ParseIntError(e)).map_err(|e| DecoderError::ParserError(e))) } fn read_datetime_as_u64(r: &mut Reader) -> Result { r.read_datetime_without_tag() .map(|ref tm| { let ts = tm.to_timespec(); ts.sec as u64 * 1_000_000_000 + (ts.nsec as u64) }) } fn read_time_as_u64(r: &mut Reader) -> Result { r.read_time_without_tag() .map(|ref tm| { let ts = tm.to_timespec(); ts.sec as u64 * 1_000_000_000 + (ts.nsec as u64) }) }
#![no_std] pub mod slice;
mod r#impl; mod noop; pub use self::{ noop::NoopRepository, r#impl::{Repository, SingleEntityRepository}, }; use futures_util::stream::Stream; use std::{future::Future, pin::Pin}; pub type GetEntityFuture<'a, T, E> = Pin<Box<dyn Future<Output = Result<Option<T>, E>> + Send + 'a>>; pub type ListEntitiesFuture<'a, T, E> = Pin<Box<dyn Future<Output = Result<ListEntitiesStream<'a, T, E>, E>> + Send + 'a>>; pub type ListEntitiesStream<'a, T, E> = Pin<Box<dyn Stream<Item = Result<T, E>> + Send + 'a>>; pub type ListEntityIdsFuture<'a, T, E> = Pin<Box<dyn Future<Output = Result<ListEntityIdsStream<'a, T, E>, E>> + Send + 'a>>; pub type ListEntityIdsStream<'a, T, E> = Pin<Box<dyn Stream<Item = Result<T, E>> + Send + 'a>>; pub type RemoveEntityFuture<'a, E> = Pin<Box<dyn Future<Output = Result<(), E>> + Send + 'a>>; pub type RemoveEntitiesFuture<'a, E> = Pin<Box<dyn Future<Output = Result<(), E>> + Send + 'a>>; pub type UpsertEntityFuture<'a, E> = Pin<Box<dyn Future<Output = Result<(), E>> + Send + 'a>>; pub type UpsertEntitiesFuture<'a, E> = Pin<Box<dyn Future<Output = Result<(), E>> + Send + 'a>>;
extern crate community; mod requirements; mod checklists; mod db;
/* env.rs: This module contains the definition of an environment in RLisp. An environment is a map, that contains mappings from symbols to expressions. An environment is used by the Evaluator tho evaluate expressions. See eval.rs. */ // load functionality from sibling modules use crate::stdlib::core; use crate::types::{error, RlErr, RlReturn, RlType}; // load needed Rust modules use std::collections::HashMap; use std::cell::RefCell; use std::rc::Rc; /// Define RlEnv Type for convenience: the Env is wrapped in a Rc object(Smart Pointer), /// which allows easy referencing pub type RlEnv = Rc<Env>; /// This structure represents an environment/closure, it holds a Hashmap with the mapping of symbols to /// expressions as well as a pointer to an outer environment #[derive(Clone, Debug)] pub struct Env { env: RefCell<HashMap<String, RlType>>, outer: Option<RlEnv>, } /** Creates a new environment and loads all the functions defined in the stdlib into this environment. Then returns this environment which will be used as the initial global environment. Returns: The new environment (Type RlEnv) */ pub(crate) fn init_global() -> RlEnv { // create new RlEnv Instance using new_env() let defenv = new_env(None); // load definitions/mappings from stdlib module and set them in the environment for (key, func) in core() { set(&defenv, key.to_string(), func); } return defenv.clone(); } /** Creates a new RlEnv Instance with an optional pointer to an outer environment. Arguments: outer - is an option for a pointer to an outer environment (None if not given) Returns: new RlEnv instance */ pub fn new_env(outer: Option<RlEnv>) -> RlEnv { return Rc::new(Env { env: RefCell::new(HashMap::new()), outer, }); } /** creates a new environment and directly set given key value pairs in the environment. Then returns the environment or an RlError if anything fails. Arguments: outer - optional pointer to outer environment of new environment names - a list of symbol-names that will be mapped to expressions in new environment targets - the list of expressions matching the symbol-names in names Returns: The new environment with the bindings or an Error */ pub fn new_env_bound( outer: Option<RlEnv>, names: Vec<RlType>, targets: Vec<RlType>, ) -> Result<RlEnv, RlErr> { // create new environment using new_env() let env = new_env(outer); // check if lengths of lists are matching return if names.len() != targets.len() { Err(error("Error: Number of arguments are not matching!")) } else { // iterate through names for (i, name) in names.iter().enumerate() { match name { // if name is a valid Symbol, set the symbol-name to matching expression in targets RlType::Symbol(s) => set(&env, s.to_string(), targets[i].clone()), _ => { return Err(error( "Error: In self defined functions, Parameter names must be Symbols", )) } } } // Return new environment Ok(env.clone()) }; } /** Takes an environment, a symbol-name and an expression. Associate the symbol-name with the given expression in the given environment. Arguments: environment - the environment to set the given key-value pair symbol - the symbolname to set expr - the expression to map the associate the symbol with */ pub(crate) fn set(environment: &RlEnv, symbol: String, expr: RlType) { environment.env.borrow_mut().insert(symbol.clone(), expr.clone()); } /** Takes an environment and a symbol-name. Searches the environment for the symbol name. Start with the most inner environment and proceed with outer environments until symbol-name mapping is found. (leads to shadowing of variables) Returns the found mapping(value to symbol) or an Error if symbol not found. Arguments: environment - the environment to search in key - the symbol to look for */ pub fn search(environment: &RlEnv, key: String) -> RlReturn { // look for symbol in current environment match environment.env.borrow().get(&key) { // if symbol not found check if there is an outer environment None => match &environment.outer { // if there is an outer environment search in outer environment Some(x) => search(x, key), // if not we are certain that symbol is not defined None => Err(error(&format!("Symbol {} not found", key))), }, // if symbol was found, return it's value Some(value) => Ok(value.clone()), } }
mod off_icon; mod on_icon; pub use off_icon::*; pub use on_icon::*; use crate::bool_to_option; use gloo::events::EventListener; use std::borrow::Cow; use wasm_bindgen::prelude::*; use web_sys::Node; use yew::prelude::*; #[wasm_bindgen(module = "/build/mwc-icon-button-toggle.js")] extern "C" { #[derive(Debug)] #[wasm_bindgen(extends = Node)] type IconButtonToggle; #[wasm_bindgen(getter, static_method_of = IconButtonToggle)] fn _dummy_loader() -> JsValue; #[wasm_bindgen(method, getter)] fn on(this: &IconButtonToggle) -> bool; } loader_hack!(IconButtonToggle); /// The `mwc-icon-button-toggle` component /// /// [MWC Documentation](https://github.com/material-components/material-components-web-components/tree/master/packages/icon-button-toggle) pub struct MatIconButtonToggle { props: IconButtonToggleProps, node_ref: NodeRef, change_listener: Option<EventListener>, } /// Props for [`MatIconButtonToggle`] /// /// MWC Documentation: /// /// - [Properties](https://github.com/material-components/material-components-web-components/tree/master/packages/icon-button-toggle#propertiesattributes) /// - [Events](https://github.com/material-components/material-components-web-components/tree/master/packages/icon-button-toggle#events) #[derive(Debug, Properties, Clone)] pub struct IconButtonToggleProps { #[prop_or_default] pub on: bool, #[prop_or_default] pub on_icon: Cow<'static, str>, #[prop_or_default] pub off_icon: Cow<'static, str>, #[prop_or_default] pub label: Cow<'static, str>, #[prop_or_default] pub disabled: bool, /// Binds to `MDCIconButtonToggle:change`. /// /// Callback's parameter is the `isOn` value passed /// /// See events docs to learn more. #[prop_or_default] pub onchange: Callback<bool>, #[prop_or_default] pub children: Children, } impl Component for MatIconButtonToggle { type Message = (); type Properties = IconButtonToggleProps; fn create(props: Self::Properties, _: ComponentLink<Self>) -> Self { IconButtonToggle::ensure_loaded(); Self { props, node_ref: NodeRef::default(), change_listener: None, } } fn update(&mut self, _msg: Self::Message) -> ShouldRender { false } fn change(&mut self, props: Self::Properties) -> bool { self.props = props; true } fn view(&self) -> Html { html! { <mwc-icon-button-toggle on=bool_to_option(self.props.on) onIcon=self.props.on_icon.clone() offIcon=self.props.off_icon.clone() label=self.props.label.clone() disabled=self.props.disabled ref=self.node_ref.clone() > { self.props.children.clone() }</mwc-icon-button-toggle> } } fn rendered(&mut self, _first_render: bool) { if self.change_listener.is_none() { let element = self.node_ref.cast::<IconButtonToggle>().unwrap(); let callback = self.props.onchange.clone(); self.change_listener = Some(EventListener::new( &element.clone(), "MDCIconButtonToggle:change", move |_| callback.emit(element.on()), )); } } }
//! Data structure for mapping string keys to numeric identifiers. #[cfg(test)] use arrow2::io::parquet::read::read_metadata; use hashbrown::hash_map::{HashMap, Keys}; use std::borrow::Borrow; use std::fs::File; use std::hash::Hash; use std::path::Path; use anyhow::Result; use log::*; use polars::prelude::*; use serde::de::DeserializeOwned; use thiserror::Error; #[cfg(test)] use quickcheck::{Arbitrary, Gen}; #[cfg(test)] use tempfile::tempdir; /// The type of index identifiers. pub type Id = i32; #[derive(Error, Debug)] pub enum IndexError { #[error("key not present in frozen index")] KeyNotPresent, } /// Index identifiers from a data type pub struct IdIndex<K> { map: HashMap<K, Id>, frozen: bool, } impl<K> IdIndex<K> where K: Eq + Hash, { /// Create a new index. pub fn new() -> IdIndex<K> { IdIndex { map: HashMap::new(), frozen: false, } } /// Freeze the index so no new items can be added. #[allow(dead_code)] pub fn freeze(self) -> IdIndex<K> { IdIndex { map: self.map, frozen: true, } } /// Get the index length pub fn len(&self) -> usize { self.map.len() } /// Get the ID for a key, adding it to the index if needed. pub fn intern<Q>(&mut self, key: &Q) -> Result<Id, IndexError> where K: Borrow<Q>, Q: Hash + Eq + ToOwned<Owned = K> + ?Sized, { let n = self.map.len() as Id; if self.frozen { self.lookup(key).ok_or(IndexError::KeyNotPresent) } else { // use Hashbrown's raw-entry API to minimize cloning let eb = self.map.raw_entry_mut(); let e = eb.from_key(key); let (_, v) = e.or_insert_with(|| (key.to_owned(), n + 1)); Ok(*v) } } /// Get the ID for a key, adding it to the index if needed and transferring ownership. pub fn intern_owned(&mut self, key: K) -> Result<Id, IndexError> { let n = self.map.len() as Id; if self.frozen { self.lookup(&key).ok_or(IndexError::KeyNotPresent) } else { Ok(*self.map.entry(key).or_insert(n + 1)) } } /// Look up the ID for a key if it is present. #[allow(dead_code)] pub fn lookup<Q>(&self, key: &Q) -> Option<Id> where K: Borrow<Q>, Q: Hash + Eq + ?Sized, { self.map.get(key).map(|i| *i) } /// Iterate over keys (see [std::collections::HashMap::keys]). #[allow(dead_code)] pub fn keys(&self) -> Keys<'_, K, Id> { self.map.keys() } } impl IdIndex<String> { /// Get the keys in order. pub fn key_vec(&self) -> Vec<&str> { let mut vec = Vec::with_capacity(self.len()); vec.resize(self.len(), None); for (k, n) in self.map.iter() { let i = (n - 1) as usize; assert!(vec[i].is_none()); vec[i] = Some(k); } let vec = vec.iter().map(|ro| ro.unwrap().as_str()).collect(); vec } /// Conver this ID index into a [DataFrame], with columns for ID and key. pub fn data_frame(&self, id_col: &str, key_col: &str) -> Result<DataFrame, PolarsError> { debug!("preparing data frame for index"); let n = self.map.len() as i32; let keys = self.key_vec(); let ids = Int32Chunked::new(id_col, 1..(n + 1)); let keys = Utf8Chunked::new(key_col, keys); DataFrame::new(vec![ids.into_series(), keys.into_series()]) } /// Load from a Parquet file, with a standard configuration. /// /// This assumes the Parquet file has the following columns: /// /// - `key`, of type `String`, storing the keys /// - `id`, of type `u32`, storing the IDs pub fn load_standard<P: AsRef<Path>>(path: P) -> Result<IdIndex<String>> { IdIndex::load(path, "id", "key") } /// Load from a Parquet file. /// /// This loads two columns from a Parquet file. The ID column is expected to /// have type `UInt32` (or a type projectable to it), and the key column should /// be `Utf8`. pub fn load<P: AsRef<Path>>(path: P, id_col: &str, key_col: &str) -> Result<IdIndex<String>> { let path_str = path.as_ref().to_string_lossy(); info!("reading index from file {}", path_str); let file = File::open(path.as_ref())?; let frame = ParquetReader::new(file).finish()?; debug!("file schema: {:?}", frame.schema()); let ic = frame.column(id_col)?.i32()?; let kc = frame.column(key_col)?.utf8()?; let mut map = HashMap::new(); debug!("reading file contents"); let iter = ic.into_iter().zip(kc.into_iter()); for pair in iter { if let (Some(id), Some(key)) = pair { map.insert(key.to_string(), id); } } info!("read {} keys from {}", map.len(), path_str); Ok(IdIndex { map, frozen: false }) } /// Load an index from a CSV file. /// /// This loads an index from a CSV file. It assumes the first column is the ID, and the /// second column is the key. #[allow(dead_code)] pub fn load_csv<P: AsRef<Path>, K: Eq + Hash + DeserializeOwned>( path: P, ) -> Result<IdIndex<K>> { info!("reading ID index from from {:?}", path.as_ref()); let input = csv::Reader::from_path(path)?; let recs = input.into_deserialize(); let mut map = HashMap::new(); for row in recs { let rec: (i32, K) = row?; let (id, key) = rec; map.insert(key, id); } Ok(IdIndex { map, frozen: false }) } /// Save to a Parquet file with the standard configuration. pub fn save_standard<P: AsRef<Path>>(&self, path: P) -> Result<()> { self.save(path, "id", "key") } /// Save to a Parquet file with the standard configuration. pub fn save<P: AsRef<Path>>(&self, path: P, id_col: &str, key_col: &str) -> Result<()> { let mut frame = self.data_frame(id_col, key_col)?; let path = path.as_ref(); info!("saving index to {:?}", path); let file = File::create(path)?; let writer = ParquetWriter::new(file).with_compression(ParquetCompression::Zstd(None)); writer.finish(&mut frame)?; Ok(()) } } #[test] fn test_index_empty() { let index: IdIndex<String> = IdIndex::new(); assert_eq!(index.len(), 0); assert!(index.lookup("bob").is_none()); } #[test] fn test_index_intern_one() { let mut index: IdIndex<String> = IdIndex::new(); assert!(index.lookup("hackem muche").is_none()); let id = index.intern("hackem muche").expect("intern failure"); assert_eq!(id, 1); assert_eq!(index.lookup("hackem muche").unwrap(), 1); } #[test] fn test_index_intern_two() { let mut index: IdIndex<String> = IdIndex::new(); assert!(index.lookup("hackem muche").is_none()); let id = index.intern("hackem muche"); assert_eq!(id.expect("intern failure"), 1); let id2 = index.intern("readme"); assert_eq!(id2.expect("intern failure"), 2); assert_eq!(index.lookup("hackem muche").unwrap(), 1); } #[test] fn test_index_intern_twice() { let mut index: IdIndex<String> = IdIndex::new(); assert!(index.lookup("hackem muche").is_none()); let id = index.intern("hackem muche"); assert_eq!(id.expect("intern failure"), 1); let id2 = index.intern("hackem muche"); assert_eq!(id2.expect("intern failure"), 1); assert_eq!(index.len(), 1); } #[test] fn test_index_intern_twice_owned() { let mut index: IdIndex<String> = IdIndex::new(); assert!(index.lookup("hackem muche").is_none()); let id = index.intern_owned("hackem muche".to_owned()); assert!(id.is_ok()); assert_eq!(id.expect("intern failure"), 1); let id2 = index.intern_owned("hackem muche".to_owned()); assert!(id2.is_ok()); assert_eq!(id2.expect("intern failure"), 1); assert_eq!(index.len(), 1); } #[cfg(test)] #[test_log::test] fn test_index_save() -> Result<()> { let mut index: IdIndex<String> = IdIndex::new(); let mut gen = Gen::new(100); for _i in 0..10000 { let key = String::arbitrary(&mut gen); let prev = index.lookup(&key); let id = index.intern(&key).expect("intern failure"); match prev { Some(i) => assert_eq!(id, i), None => assert_eq!(id as usize, index.len()), }; } let dir = tempdir()?; let pq = dir.path().join("index.parquet"); index.save_standard(&pq).expect("save error"); let mut pqf = File::open(&pq).expect("open error"); let meta = read_metadata(&mut pqf).expect("meta error"); println!("file metadata: {:?}", meta); std::mem::drop(pqf); let i2 = IdIndex::load_standard(&pq).expect("load error"); assert_eq!(i2.len(), index.len()); for (k, v) in &index.map { let v2 = i2.lookup(k); assert!(v2.is_some()); assert_eq!(v2.unwrap(), *v); } Ok(()) } #[test] fn test_index_freeze() { let mut index: IdIndex<String> = IdIndex::new(); assert!(index.lookup("hackem muche").is_none()); let id = index.intern("hackem muche"); assert!(id.is_ok()); assert_eq!(id.expect("intern failure"), 1); let mut index = index.freeze(); let id = index.intern("hackem muche"); assert!(id.is_ok()); assert_eq!(id.expect("intern failure"), 1); let id2 = index.intern("foobie bletch"); assert!(id2.is_err()); }
use crate::domain::{repository::IRepository, service::search}; use crate::interface::presenter::suggest; use crate::{command::CommandError, domain::model::Favorite}; use anyhow::Error; use skim::prelude::*; use std::io::Cursor; use std::process::Command; pub enum JumpTo { Key(String), ProjectRoot, FuzzyFinder, } pub fn jump_to<T: IRepository>(repo: &T, to: JumpTo) -> anyhow::Result<String> { match to { JumpTo::FuzzyFinder => jump_with_skim(repo).map(|fav| fav.path()), JumpTo::Key(key) => jump_to_key(repo, &key).map(|fav| fav.path()), JumpTo::ProjectRoot => jump_to_project_root(), } } fn jump_with_skim<T: IRepository>(repo: &T) -> anyhow::Result<Favorite> { let skim_option: SkimOptions = SkimOptionsBuilder::default() .height(Some("30%")) .multi(true) .build() .map_err::<anyhow::Error, _>(|_| CommandError::SkimErrorOccured.into())?; let item_reader = SkimItemReader::default(); let favorites = repo .get_all()? .iter() .map(|favorite| format!("{} -> {}", favorite.name(), favorite.path())) .collect::<Vec<String>>(); let items = item_reader.of_bufread(Cursor::new(favorites.join("\n"))); let selected_items = Skim::run_with(&skim_option, Some(items)).map(|out| out.selected_items); let skim_error = Err(CommandError::SkimErrorOccured.into()); match selected_items { Some(item) if !item.is_empty() => { let mut favorite = item .get(0) .ok_or_else(|| -> Error { CommandError::SkimErrorOccured.into() })? .output() .into_owned() .split(" -> ") .map(|s| s.to_string()) .collect::<Vec<String>>(); match (favorite.pop(), favorite.pop()) { (Some(path), Some(key)) => Ok(Favorite::new(key, path)), _ => skim_error, } } _ => Err(CommandError::SkimErrorOccured.into()), } } fn jump_to_key<T: IRepository>(repo: &T, key: &str) -> anyhow::Result<Favorite> { let maybe_path_matched = repo.get(key); match maybe_path_matched { Ok(Some(favorite)) => Ok(favorite), _ => { let favorites = repo.get_all()?; suggest(key, search(key, favorites)); Err(CommandError::GivenKeyNotFound.into()) } } } fn get_project_root_path() -> anyhow::Result<String> { let output = Command::new("sh") .arg("-c") .arg("git rev-parse --show-toplevel") .output(); match output { Ok(output) => { if output.status.success() { Ok(String::from_utf8(output.stdout)?.trim_end().to_string()) } else { Err(CommandError::DotGitNotFound.into()) } } Err(_) => Err(CommandError::GitCommandNotFound.into()), } } fn jump_to_project_root() -> anyhow::Result<String> { match get_project_root_path() { Ok(path) => Ok(path), Err(e) => Err(e), } }
#[doc = "Reader of register INTR_SET"] pub type R = crate::R<u32, super::INTR_SET>; #[doc = "Writer for register INTR_SET"] pub type W = crate::W<u32, super::INTR_SET>; #[doc = "Register INTR_SET `reset()`'s with value 0x0600"] impl crate::ResetValue for super::INTR_SET { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x0600 } } #[doc = "Reader of field `RCB_DONE`"] pub type RCB_DONE_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RCB_DONE`"] pub struct RCB_DONE_W<'a> { w: &'a mut W, } impl<'a> RCB_DONE_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 `TX_FIFO_TRIGGER`"] pub type TX_FIFO_TRIGGER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TX_FIFO_TRIGGER`"] pub struct TX_FIFO_TRIGGER_W<'a> { w: &'a mut W, } impl<'a> TX_FIFO_TRIGGER_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 `TX_FIFO_NOT_FULL`"] pub type TX_FIFO_NOT_FULL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TX_FIFO_NOT_FULL`"] pub struct TX_FIFO_NOT_FULL_W<'a> { w: &'a mut W, } impl<'a> TX_FIFO_NOT_FULL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 9)) | (((value as u32) & 0x01) << 9); self.w } } #[doc = "Reader of field `TX_FIFO_EMPTY`"] pub type TX_FIFO_EMPTY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TX_FIFO_EMPTY`"] pub struct TX_FIFO_EMPTY_W<'a> { w: &'a mut W, } impl<'a> TX_FIFO_EMPTY_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 `TX_FIFO_OVERFLOW`"] pub type TX_FIFO_OVERFLOW_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TX_FIFO_OVERFLOW`"] pub struct TX_FIFO_OVERFLOW_W<'a> { w: &'a mut W, } impl<'a> TX_FIFO_OVERFLOW_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 11)) | (((value as u32) & 0x01) << 11); self.w } } #[doc = "Reader of field `TX_FIFO_UNDERFLOW`"] pub type TX_FIFO_UNDERFLOW_R = crate::R<bool, bool>; #[doc = "Write proxy for field `TX_FIFO_UNDERFLOW`"] pub struct TX_FIFO_UNDERFLOW_W<'a> { w: &'a mut W, } impl<'a> TX_FIFO_UNDERFLOW_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 12)) | (((value as u32) & 0x01) << 12); self.w } } #[doc = "Reader of field `RX_FIFO_TRIGGER`"] pub type RX_FIFO_TRIGGER_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RX_FIFO_TRIGGER`"] pub struct RX_FIFO_TRIGGER_W<'a> { w: &'a mut W, } impl<'a> RX_FIFO_TRIGGER_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 16)) | (((value as u32) & 0x01) << 16); self.w } } #[doc = "Reader of field `RX_FIFO_NOT_EMPTY`"] pub type RX_FIFO_NOT_EMPTY_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RX_FIFO_NOT_EMPTY`"] pub struct RX_FIFO_NOT_EMPTY_W<'a> { w: &'a mut W, } impl<'a> RX_FIFO_NOT_EMPTY_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 17)) | (((value as u32) & 0x01) << 17); self.w } } #[doc = "Reader of field `RX_FIFO_FULL`"] pub type RX_FIFO_FULL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RX_FIFO_FULL`"] pub struct RX_FIFO_FULL_W<'a> { w: &'a mut W, } impl<'a> RX_FIFO_FULL_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 18)) | (((value as u32) & 0x01) << 18); self.w } } #[doc = "Reader of field `RX_FIFO_OVERFLOW`"] pub type RX_FIFO_OVERFLOW_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RX_FIFO_OVERFLOW`"] pub struct RX_FIFO_OVERFLOW_W<'a> { w: &'a mut W, } impl<'a> RX_FIFO_OVERFLOW_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 19)) | (((value as u32) & 0x01) << 19); self.w } } #[doc = "Reader of field `RX_FIFO_UNDERFLOW`"] pub type RX_FIFO_UNDERFLOW_R = crate::R<bool, bool>; #[doc = "Write proxy for field `RX_FIFO_UNDERFLOW`"] pub struct RX_FIFO_UNDERFLOW_W<'a> { w: &'a mut W, } impl<'a> RX_FIFO_UNDERFLOW_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 20)) | (((value as u32) & 0x01) << 20); self.w } } impl R { #[doc = "Bit 0 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rcb_done(&self) -> RCB_DONE_R { RCB_DONE_R::new((self.bits & 0x01) != 0) } #[doc = "Bit 8 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_trigger(&self) -> TX_FIFO_TRIGGER_R { TX_FIFO_TRIGGER_R::new(((self.bits >> 8) & 0x01) != 0) } #[doc = "Bit 9 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_not_full(&self) -> TX_FIFO_NOT_FULL_R { TX_FIFO_NOT_FULL_R::new(((self.bits >> 9) & 0x01) != 0) } #[doc = "Bit 10 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_empty(&self) -> TX_FIFO_EMPTY_R { TX_FIFO_EMPTY_R::new(((self.bits >> 10) & 0x01) != 0) } #[doc = "Bit 11 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_overflow(&self) -> TX_FIFO_OVERFLOW_R { TX_FIFO_OVERFLOW_R::new(((self.bits >> 11) & 0x01) != 0) } #[doc = "Bit 12 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_underflow(&self) -> TX_FIFO_UNDERFLOW_R { TX_FIFO_UNDERFLOW_R::new(((self.bits >> 12) & 0x01) != 0) } #[doc = "Bit 16 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_trigger(&self) -> RX_FIFO_TRIGGER_R { RX_FIFO_TRIGGER_R::new(((self.bits >> 16) & 0x01) != 0) } #[doc = "Bit 17 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_not_empty(&self) -> RX_FIFO_NOT_EMPTY_R { RX_FIFO_NOT_EMPTY_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 18 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_full(&self) -> RX_FIFO_FULL_R { RX_FIFO_FULL_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 19 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_overflow(&self) -> RX_FIFO_OVERFLOW_R { RX_FIFO_OVERFLOW_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 20 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_underflow(&self) -> RX_FIFO_UNDERFLOW_R { RX_FIFO_UNDERFLOW_R::new(((self.bits >> 20) & 0x01) != 0) } } impl W { #[doc = "Bit 0 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rcb_done(&mut self) -> RCB_DONE_W { RCB_DONE_W { w: self } } #[doc = "Bit 8 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_trigger(&mut self) -> TX_FIFO_TRIGGER_W { TX_FIFO_TRIGGER_W { w: self } } #[doc = "Bit 9 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_not_full(&mut self) -> TX_FIFO_NOT_FULL_W { TX_FIFO_NOT_FULL_W { w: self } } #[doc = "Bit 10 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_empty(&mut self) -> TX_FIFO_EMPTY_W { TX_FIFO_EMPTY_W { w: self } } #[doc = "Bit 11 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_overflow(&mut self) -> TX_FIFO_OVERFLOW_W { TX_FIFO_OVERFLOW_W { w: self } } #[doc = "Bit 12 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn tx_fifo_underflow(&mut self) -> TX_FIFO_UNDERFLOW_W { TX_FIFO_UNDERFLOW_W { w: self } } #[doc = "Bit 16 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_trigger(&mut self) -> RX_FIFO_TRIGGER_W { RX_FIFO_TRIGGER_W { w: self } } #[doc = "Bit 17 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_not_empty(&mut self) -> RX_FIFO_NOT_EMPTY_W { RX_FIFO_NOT_EMPTY_W { w: self } } #[doc = "Bit 18 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_full(&mut self) -> RX_FIFO_FULL_W { RX_FIFO_FULL_W { w: self } } #[doc = "Bit 19 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_overflow(&mut self) -> RX_FIFO_OVERFLOW_W { RX_FIFO_OVERFLOW_W { w: self } } #[doc = "Bit 20 - Write with '1' to set corresponding bit in interrupt request register."] #[inline(always)] pub fn rx_fifo_underflow(&mut self) -> RX_FIFO_UNDERFLOW_W { RX_FIFO_UNDERFLOW_W { w: self } } }
use super::*; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[repr(transparent)] pub struct BlendControl(u16); impl BlendControl { const_new!(); bitfield_bool!(u16; 0, bg0_1st_target, with_bg0_1st_target, set_bg0_1st_target); bitfield_bool!(u16; 1, bg1_1st_target, with_bg1_1st_target, set_bg1_1st_target); bitfield_bool!(u16; 2, bg2_1st_target, with_bg2_1st_target, set_bg2_1st_target); bitfield_bool!(u16; 3, bg3_1st_target, with_bg3_1st_target, set_bg3_1st_target); bitfield_bool!(u16; 4, obj_1st_target, with_obj_1st_target, set_obj_1st_target); bitfield_bool!(u16; 5, backdrop_1st_target, with_backdrop_1st_target, set_backdrop_1st_target); bitfield_enum!(u16; 6..=7: ColorSpecialEffect, effect, with_effect, set_effect); bitfield_bool!(u16; 8, bg0_2nd_target, with_bg0_2nd_target, set_bg0_2nd_target); bitfield_bool!(u16; 9, bg1_2nd_target, with_bg1_2nd_target, set_bg1_2nd_target); bitfield_bool!(u16; 10, bg2_2nd_target, with_bg2_2nd_target, set_bg2_2nd_target); bitfield_bool!(u16; 11, bg3_2nd_target, with_bg3_2nd_target, set_bg3_2nd_target); bitfield_bool!(u16; 12, obj_2nd_target, with_obj_2nd_target, set_obj_2nd_target); bitfield_bool!(u16; 13, backdrop_2nd_target, with_backdrop_2nd_target, set_backdrop_2nd_target); } #[derive(Debug, Clone, Copy, PartialEq, Eq)] #[repr(u16)] pub enum ColorSpecialEffect { NoEffect = 0 << 6, AlphaBlend = 1 << 6, BrightnessIncrease = 2 << 6, BrightnessDecrease = 3 << 6, }
#![no_std] #![no_main] #![feature(asm)] #![feature(min_type_alias_impl_trait)] #![feature(impl_trait_in_bindings)] #![feature(type_alias_impl_trait)] #![allow(incomplete_features)] #[path = "../example_common.rs"] mod example_common; use embassy::executor::Spawner; use embassy_rp::gpio::{Input, Level, Output, Pull}; use embassy_rp::Peripherals; use embedded_hal::digital::v2::{InputPin, OutputPin}; #[embassy::main] async fn main(_spawner: Spawner, p: Peripherals) { let button = Input::new(p.PIN_28, Pull::Up); let mut led = Output::new(p.PIN_25, Level::Low); loop { if button.is_high() { led.set_high(); } else { led.set_low(); } } }
use core::{Point, SourceByteRange}; #[derive(Clone,Copy)] enum State { Code, Comment, CommentBlock, String, Char, Finished } #[derive(Clone,Copy)] pub struct CodeIndicesIter<'a> { src: &'a str, pos: Point, state: State } impl<'a> Iterator for CodeIndicesIter<'a> { type Item = SourceByteRange; #[inline] fn next(&mut self) -> Option<SourceByteRange> { match self.state { State::Code => Some(self.code()), State::Comment => Some(self.comment()), State::CommentBlock => Some(self.comment_block()), State::String => Some(self.string()), State::Char => Some(self.char()), State::Finished => None } } } impl<'a> CodeIndicesIter<'a> { fn code(&mut self) -> SourceByteRange { let mut pos = self.pos; let start = match self.state { State::String | State::Char => { pos-1 }, // include quote _ => { pos } }; let src_bytes = self.src.as_bytes(); for &b in &src_bytes[pos..] { pos += 1; match b { b'/' if src_bytes.len() > pos => match src_bytes[pos] { b'/' => { self.state = State::Comment; self.pos = pos + 1; return (start, pos-1); }, b'*' => { self.state = State::CommentBlock; self.pos = pos + 1; return (start, pos-1); }, _ => {} }, b'"' => { // " self.state = State::String; self.pos = pos; return (start, pos); // include dblquotes }, b'\'' => { // single quotes are also used for lifetimes, so we need to // be confident that this is not a lifetime. // Look for backslash starting the escape, or a closing quote: if src_bytes.len() > pos + 1 && (src_bytes[pos] == b'\\' || src_bytes[pos+1] == b'\'') { self.state = State::Char; self.pos = pos; return (start, pos); // include single quote } }, _ => {} } } self.state = State::Finished; (start, self.src.len()) } fn comment(&mut self) -> SourceByteRange { let mut pos = self.pos; let src_bytes = self.src.as_bytes(); for &b in &src_bytes[pos..] { pos += 1; if b == b'\n' { if pos + 2 <= src_bytes.len() && &src_bytes[pos..pos+2] == &[b'/', b'/'] { continue; } break; } } self.pos = pos; self.code() } fn comment_block(&mut self) -> SourceByteRange { let mut nesting_level = 0usize; let mut prev = b' '; let mut pos = self.pos; for &b in &self.src.as_bytes()[pos..] { pos += 1; match b { b'/' if prev == b'*' => { if nesting_level == 0 { break; } else { nesting_level -= 1; } }, b'*' if prev == b'/' => { nesting_level += 1; }, _ => { prev = b; } } } self.pos = pos; self.code() } fn string(&mut self) -> SourceByteRange { let src_bytes = self.src.as_bytes(); let mut pos = self.pos; if pos > 1 && src_bytes[pos-2] == b'r' { // raw string (eg br"\"): no escape match src_bytes[pos..].iter().position(|&b| b == b'"') { Some(p) => pos += p+1, None => pos = src_bytes.len() } } else { let mut is_not_escaped = true; for &b in &src_bytes[pos..] { pos += 1; match b { b'"' if is_not_escaped => { break; }, // " b'\\' => { is_not_escaped = !is_not_escaped; }, _ => { is_not_escaped = true; } } } } self.pos = pos; self.code() } fn char(&mut self) -> SourceByteRange { let mut is_not_escaped = true; let mut pos = self.pos; for &b in &self.src.as_bytes()[pos..] { pos += 1; match b { b'\'' if is_not_escaped => { break; }, b'\\' => { is_not_escaped = !is_not_escaped; }, _ => { is_not_escaped = true; } } } self.pos = pos; self.code() } } /// Returns indices of chunks of code (minus comments and string contents) pub fn code_chunks(src: &str) -> CodeIndicesIter { CodeIndicesIter { src: src, state: State::Code, pos: 0 } } /// Reverse Iterator for reading the source bytes skipping comments. /// This is written for get_start_of_pattern and maybe not so robust. pub struct CommentSkipIterRev<'a> { src: &'a str, pos: Point, } /// This produce CommentSkipIterRev for range [0, start) pub fn comment_skip_iter_rev(s: &str, start: Point) -> CommentSkipIterRev { let start = if start > s.len() { 0 } else { start }; CommentSkipIterRev { src: s, pos: start } } impl<'a> Iterator for CommentSkipIterRev<'a> { type Item = (char, Point); fn next(&mut self) -> Option<(char, Point)> { let cur_byte = self.cur_byte()?; match cur_byte { b'\n' => { let pos = self.pos; self.pos = self.skip_line_comment(); Some((cur_byte as char, pos - 1)) } b'/' => { if let Some(next_byte) = self.get_byte(self.pos - 1) { if next_byte == b'*' { self.pos = self.skip_block_comment(); Some((self.cur_byte()? as char, self.pos - 1)) } else { self.code() } } else { self.code() } } _ => self.code(), } } } impl<'a> CommentSkipIterRev<'a> { fn cur_byte(&self) -> Option<u8> { self.get_byte(self.pos) } fn code(&mut self) -> Option<(char, Point)> { let cur_byte = self.cur_byte()?; self.pos -= 1; Some((cur_byte as char, self.pos)) } fn get_byte(&self, p: Point) -> Option<u8> { if p == 0 { None } else { let b = self.src.as_bytes()[p - 1]; Some(b) } } // return where 'pos' shuld be after skipping block comments fn skip_block_comment(&self) -> Point { let mut nest_level = 0; let mut prev = b' '; for i in (0..self.pos - 2).rev() { let b = self.src.as_bytes()[i]; match b { b'/' if prev == b'*' => { if nest_level == 0 { return i; } else { nest_level -= 1; } } b'*' if prev == b'/' => { nest_level += 1; } _ => { prev = b; } } } 0 } // return where 'pos' shuld be after skipping line comments fn skip_line_comment(&self) -> Point { let skip_cr = |p: Point| -> Point { if let Some(b) = self.get_byte(p) { if b == b'\r' { return p - 1; } } p }; let mut pos = self.pos; let mut skipped_whole_line = true; while skipped_whole_line && pos > 0 { // now pos >= 1 && self.src.as_bytes()[pos - 1] == '\n' skipped_whole_line = false; let comment_start = if let Some(next_newline) = self.src[..pos - 1].rfind('\n') { if let Some(start) = self.src[next_newline + 1..pos - 1].find("//") { skipped_whole_line = start == 0; start + next_newline + 1 } else { return skip_cr(pos - 1); } } else { if let Some(start) = self.src[..pos - 1].find("//") { start } else { return skip_cr(pos - 1); } }; pos = comment_start; } pos } } #[cfg(test)] mod code_indices_iter_test { use super::*; use ::testutils::{rejustify, slice}; #[test] fn removes_a_comment() { let src = &rejustify(" this is some code // this is a comment some more code "); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!("some more code", slice(src, it.next().unwrap())); } #[test] fn removes_consecutive_comments() { let src = &rejustify(" this is some code // this is a comment // this is more comment // another comment some more code "); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!("some more code", slice(src, it.next().unwrap())); } #[test] fn removes_string_contents() { let src = &rejustify(" this is some code \"this is a string\" more code "); let mut it = code_chunks(src); assert_eq!("this is some code \"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn removes_char_contents() { let src = &rejustify(" this is some code \'\"\' more code \'\\x00\' and \'\\\'\' that\'s it "); let mut it = code_chunks(src); assert_eq!("this is some code \'", slice(src, it.next().unwrap())); assert_eq!("\' more code \'", slice(src, it.next().unwrap())); assert_eq!("\' and \'", slice(src, it.next().unwrap())); assert_eq!("\' that\'s it", slice(src, it.next().unwrap())); } #[test] fn removes_string_contents_with_a_comment_in_it() { let src = &rejustify(" this is some code \"string with a // fake comment \" more code "); let mut it = code_chunks(src); assert_eq!("this is some code \"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn removes_a_comment_with_a_dbl_quote_in_it() { let src = &rejustify(" this is some code // comment with \" double quote some more code "); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!("some more code", slice(src, it.next().unwrap())); } #[test] fn removes_multiline_comment() { let src = &rejustify(" this is some code /* this is a \"multiline\" comment */some more code "); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!("some more code", slice(src, it.next().unwrap())); } #[test] fn handles_nesting_of_block_comments() { let src = &rejustify(" this is some code /* nested /* block */ comment */ some more code "); let mut it = code_chunks(src); assert_eq!("this is some code ", slice(src, it.next().unwrap())); assert_eq!(" some more code", slice(src, it.next().unwrap())); } #[test] fn removes_string_with_escaped_dblquote_in_it() { let src = &rejustify(" this is some code \"string with a \\\" escaped dblquote fake comment \" more code "); let mut it = code_chunks(src); assert_eq!("this is some code \"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn removes_raw_string_with_dangling_escape_in_it() { let src = &rejustify(" this is some code br\" escaped dblquote raw string \\\" more code "); let mut it = code_chunks(src); assert_eq!("this is some code br\"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn removes_string_with_escaped_slash_before_dblquote_in_it() { let src = &rejustify(" this is some code \"string with an escaped slash, so dbl quote does end the string after all \\\\\" more code "); let mut it = code_chunks(src); assert_eq!("this is some code \"", slice(src, it.next().unwrap())); assert_eq!("\" more code", slice(src, it.next().unwrap())); } #[test] fn handles_tricky_bit_from_str_rs() { let src = &rejustify(" before(\"\\\\\'\\\\\\\"\\\\\\\\\"); more_code(\" skip me \") "); for (start, end) in code_chunks(src) { println!("BLOB |{}|", &src[start..end]); if src[start..end].contains("skip me") { panic!("{}", &src[start..end]); } } } } #[cfg(test)] mod comment_skip_iter_rev_test { use super::*; use ::testutils::rejustify; #[test] fn removes_consecutive_comments_with_comment_skip_iter_rev() { let src = &rejustify(" this is some code // this is a comment // this is more comment // another comment some more code "); let result: String = comment_skip_iter_rev(&src, src.len()).map(|c| c.0).collect(); assert_eq!(&result, "edoc erom emos\n edoc emos si siht"); } #[test] fn removes_nested_block_comments_with_comment_skip_iter_rev() { let src = &rejustify(" this is some code // this is a comment /* /* nested comment */ */ some more code "); let result: String = comment_skip_iter_rev(&src, src.len()).map(|c| c.0).collect(); assert_eq!(&result, "edoc erom emos\n\n\n edoc emos si siht"); } #[test] fn removes_multiline_comment_with_comment_skip_iter_rev() { let src = &rejustify(" this is some code /* this is a \"multiline\" comment */some more code "); let result: String = comment_skip_iter_rev(&src, src.len()).map(|c| c.0).collect(); assert_eq!(&result, "edoc erom emos edoc emos si siht"); } }
use std::env; fn main() { println!("rerun-if-changed=\"Cargo.toml\""); println!("rerun-if-env-changed=\"OPT_LEVEL\""); let opt_level = env::var("OPT_LEVEL").unwrap(); match opt_level.parse::<u32>() { Ok(opt_level) => { if opt_level > 0 { println!("cargo:rustc-cfg=opt_level_gt_0"); } } _ => {} } }
/* * Datadog API V1 Collection * * Collection of all Datadog Public endpoints. * * The version of the OpenAPI document: 1.0 * Contact: support@datadoghq.com * Generated by: https://openapi-generator.tech */ /// PagerDutyService : The PagerDuty service that is available for integration with Datadog. #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PagerDutyService { /// Your service key in PagerDuty. #[serde(rename = "service_key")] pub service_key: String, /// Your service name associated with a service key in PagerDuty. #[serde(rename = "service_name")] pub service_name: String, } impl PagerDutyService { /// The PagerDuty service that is available for integration with Datadog. pub fn new(service_key: String, service_name: String) -> PagerDutyService { PagerDutyService { service_key, service_name, } } }
use crate::geometry::rect::Rect; use cgmath::{ElementWise, EuclideanSpace, Point2, Vector2}; use ggez::graphics::{Color, DrawMode, MeshBuilder, Vertex, WHITE}; pub struct ShapeRenderer { pub color: Color, pub mode: DrawMode, pub meshbuilder: MeshBuilder, pub screen_box: Rect, pub empty: bool, pub zoom: f32, } const DEFAULT_THICKNESS: f32 = 0.2; impl ShapeRenderer { pub fn new(screen_box: &Rect, zoom: f32) -> Self { ShapeRenderer { color: WHITE, mode: DrawMode::fill(), meshbuilder: MeshBuilder::new(), screen_box: screen_box.clone(), empty: true, zoom, } } } fn from_srgb(component: f32) -> f32 { let a = 0.055; if component <= 0.04045 { component / 12.92 } else { ((component + a) / (1.0 + a)).powf(2.4) } } #[allow(dead_code)] impl ShapeRenderer { pub fn set_filled(&mut self, filled: bool) { if filled { self.mode = DrawMode::fill() } else { self.mode = DrawMode::stroke(DEFAULT_THICKNESS); } } pub fn draw_circle(&mut self, p: Vector2<f32>, r: f32) { let pp = Point2::from_vec(p); if r > 0.0 && self.screen_box.contains_within(p, r) { self.meshbuilder .circle(self.mode, pp, r, 0.3 / self.zoom, self.color); self.empty = false; } } pub fn reset(&mut self) { self.meshbuilder = MeshBuilder::new(); self.empty = true; self.color = WHITE; self.mode = DrawMode::fill(); } pub fn draw_rect_centered(&mut self, p: Vector2<f32>, width: f32, height: f32) { if !self.screen_box.contains_within(p, width.max(height)) { return; } self.meshbuilder.rectangle( self.mode, ggez::graphics::Rect::new(p.x - width / 2.0, p.y - height / 2.0, width, height), self.color, ); self.empty = false; } pub fn draw_rect_cos_sin( &mut self, p: Vector2<f32>, width: f32, height: f32, cos: f32, sin: f32, ) { if !self.screen_box.contains_within(p, width.max(height)) { return; } let a = Point2::new(width / 2.0 * cos, width / 2.0 * sin); let b = Vector2::new(height / 2.0 * -sin, height / 2.0 * cos); let points: [Point2<f32>; 4] = [ a + b + p, a - b + p, a.mul_element_wise(-1.0) - b + p, a.mul_element_wise(-1.0) + b + p, ]; let col = Color::new( from_srgb(self.color.r), from_srgb(self.color.g), from_srgb(self.color.b), 1.0, ); match self.mode { DrawMode::Fill(_) => { let verts: [Vertex; 4] = [ Vertex { pos: [points[0].x, points[0].y], uv: [0.0, 0.0], color: [col.r, col.g, col.b, col.a], }, Vertex { pos: [points[1].x, points[1].y], uv: [1.0, 0.0], color: [col.r, col.g, col.b, col.a], }, Vertex { pos: [points[2].x, points[2].y], uv: [1.0, 1.0], color: [col.r, col.g, col.b, col.a], }, Vertex { pos: [points[3].x, points[3].y], uv: [0.0, 1.0], color: [col.r, col.g, col.b, col.a], }, ]; self.meshbuilder.raw(&verts, &[0, 1, 2, 0, 2, 3], None); self.empty = false; } DrawMode::Stroke(_) => { self.meshbuilder .polygon(self.mode, &points, self.color) .expect("Error building rect"); self.empty = false; } } } pub fn draw_stroke(&mut self, p1: Vector2<f32>, p2: Vector2<f32>, thickness: f32) { if !self .screen_box .intersects_line_within(p1, p2, thickness / 2.0) { return; } if p1 == p2 { return; } self.meshbuilder .line( &[Point2::from_vec(p1), Point2::from_vec(p2)], thickness, Color { a: (self.zoom * self.zoom * 50.0).min(self.color.a).max(0.0), ..self.color }, ) .expect("Line error"); self.empty = false; } pub fn draw_polyline(&mut self, points: &[Vector2<f32>], thickness: f32) { if !self .screen_box .intersects_line_within(points[0], points[1], thickness) { return; } self.meshbuilder .polyline( DrawMode::stroke(thickness), &points .iter() .map(|x| Point2::new(x.x, x.y)) .collect::<Vec<Point2<f32>>>(), Color { a: (self.zoom * self.zoom * 50.0).min(self.color.a).max(0.0), ..self.color }, ) .expect("Line error"); self.empty = false; } pub fn draw_line(&mut self, p1: Vector2<f32>, p2: Vector2<f32>) { self.draw_stroke(p1, p2, 0.5 / self.zoom); } }
/// MigrateRepoOptions options for migrating repository's /// this is used to interact with api v1 #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct MigrateRepoOptions { pub auth_password: Option<String>, pub auth_token: Option<String>, pub auth_username: Option<String>, pub clone_addr: String, pub description: Option<String>, pub issues: Option<bool>, pub labels: Option<bool>, pub milestones: Option<bool>, pub mirror: Option<bool>, pub private: Option<bool>, pub pull_requests: Option<bool>, pub releases: Option<bool>, pub repo_name: String, /// Name of User or Organisation who will own Repo after migration pub repo_owner: Option<String>, pub service: Option<crate::migrate_repo_options::MigrateRepoOptionsService>, /// deprecated (only for backwards compatibility) pub uid: Option<i64>, pub wiki: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize)] #[allow(non_camel_case_types)] pub enum MigrateRepoOptionsService { #[serde(rename = "git")] Git, #[serde(rename = "github")] Github, #[serde(rename = "gitea")] Gitea, #[serde(rename = "gitlab")] Gitlab, } impl Default for MigrateRepoOptionsService { fn default() -> Self { MigrateRepoOptionsService::Git } } impl MigrateRepoOptions { /// Create a builder for this object. #[inline] pub fn builder() -> MigrateRepoOptionsBuilder<crate::generics::MissingCloneAddr, crate::generics::MissingRepoName> { MigrateRepoOptionsBuilder { body: Default::default(), _clone_addr: core::marker::PhantomData, _repo_name: core::marker::PhantomData, } } #[inline] pub fn repo_migrate() -> MigrateRepoOptionsPostBuilder<crate::generics::MissingCloneAddr, crate::generics::MissingRepoName> { MigrateRepoOptionsPostBuilder { body: Default::default(), _clone_addr: core::marker::PhantomData, _repo_name: core::marker::PhantomData, } } } impl Into<MigrateRepoOptions> for MigrateRepoOptionsBuilder<crate::generics::CloneAddrExists, crate::generics::RepoNameExists> { fn into(self) -> MigrateRepoOptions { self.body } } impl Into<MigrateRepoOptions> for MigrateRepoOptionsPostBuilder<crate::generics::CloneAddrExists, crate::generics::RepoNameExists> { fn into(self) -> MigrateRepoOptions { self.body } } /// Builder for [`MigrateRepoOptions`](./struct.MigrateRepoOptions.html) object. #[derive(Debug, Clone)] pub struct MigrateRepoOptionsBuilder<CloneAddr, RepoName> { body: self::MigrateRepoOptions, _clone_addr: core::marker::PhantomData<CloneAddr>, _repo_name: core::marker::PhantomData<RepoName>, } impl<CloneAddr, RepoName> MigrateRepoOptionsBuilder<CloneAddr, RepoName> { #[inline] pub fn auth_password(mut self, value: impl Into<String>) -> Self { self.body.auth_password = Some(value.into()); self } #[inline] pub fn auth_token(mut self, value: impl Into<String>) -> Self { self.body.auth_token = Some(value.into()); self } #[inline] pub fn auth_username(mut self, value: impl Into<String>) -> Self { self.body.auth_username = Some(value.into()); self } #[inline] pub fn clone_addr(mut self, value: impl Into<String>) -> MigrateRepoOptionsBuilder<crate::generics::CloneAddrExists, RepoName> { self.body.clone_addr = value.into(); unsafe { std::mem::transmute(self) } } #[inline] pub fn description(mut self, value: impl Into<String>) -> Self { self.body.description = Some(value.into()); self } #[inline] pub fn issues(mut self, value: impl Into<bool>) -> Self { self.body.issues = Some(value.into()); self } #[inline] pub fn labels(mut self, value: impl Into<bool>) -> Self { self.body.labels = Some(value.into()); self } #[inline] pub fn milestones(mut self, value: impl Into<bool>) -> Self { self.body.milestones = Some(value.into()); self } #[inline] pub fn mirror(mut self, value: impl Into<bool>) -> Self { self.body.mirror = Some(value.into()); self } #[inline] pub fn private(mut self, value: impl Into<bool>) -> Self { self.body.private = Some(value.into()); self } #[inline] pub fn pull_requests(mut self, value: impl Into<bool>) -> Self { self.body.pull_requests = Some(value.into()); self } #[inline] pub fn releases(mut self, value: impl Into<bool>) -> Self { self.body.releases = Some(value.into()); self } #[inline] pub fn repo_name(mut self, value: impl Into<String>) -> MigrateRepoOptionsBuilder<CloneAddr, crate::generics::RepoNameExists> { self.body.repo_name = value.into(); unsafe { std::mem::transmute(self) } } /// Name of User or Organisation who will own Repo after migration #[inline] pub fn repo_owner(mut self, value: impl Into<String>) -> Self { self.body.repo_owner = Some(value.into()); self } #[inline] pub fn service(mut self, value: crate::migrate_repo_options::MigrateRepoOptionsService) -> Self { self.body.service = Some(value.into()); self } /// deprecated (only for backwards compatibility) #[inline] pub fn uid(mut self, value: impl Into<i64>) -> Self { self.body.uid = Some(value.into()); self } #[inline] pub fn wiki(mut self, value: impl Into<bool>) -> Self { self.body.wiki = Some(value.into()); self } } /// Builder created by [`MigrateRepoOptions::repo_migrate`](./struct.MigrateRepoOptions.html#method.repo_migrate) method for a `POST` operation associated with `MigrateRepoOptions`. #[derive(Debug, Clone)] pub struct MigrateRepoOptionsPostBuilder<CloneAddr, RepoName> { body: self::MigrateRepoOptions, _clone_addr: core::marker::PhantomData<CloneAddr>, _repo_name: core::marker::PhantomData<RepoName>, } impl<CloneAddr, RepoName> MigrateRepoOptionsPostBuilder<CloneAddr, RepoName> { #[inline] pub fn auth_password(mut self, value: impl Into<String>) -> Self { self.body.auth_password = Some(value.into()); self } #[inline] pub fn auth_token(mut self, value: impl Into<String>) -> Self { self.body.auth_token = Some(value.into()); self } #[inline] pub fn auth_username(mut self, value: impl Into<String>) -> Self { self.body.auth_username = Some(value.into()); self } #[inline] pub fn clone_addr(mut self, value: impl Into<String>) -> MigrateRepoOptionsPostBuilder<crate::generics::CloneAddrExists, RepoName> { self.body.clone_addr = value.into(); unsafe { std::mem::transmute(self) } } #[inline] pub fn description(mut self, value: impl Into<String>) -> Self { self.body.description = Some(value.into()); self } #[inline] pub fn issues(mut self, value: impl Into<bool>) -> Self { self.body.issues = Some(value.into()); self } #[inline] pub fn labels(mut self, value: impl Into<bool>) -> Self { self.body.labels = Some(value.into()); self } #[inline] pub fn milestones(mut self, value: impl Into<bool>) -> Self { self.body.milestones = Some(value.into()); self } #[inline] pub fn mirror(mut self, value: impl Into<bool>) -> Self { self.body.mirror = Some(value.into()); self } #[inline] pub fn private(mut self, value: impl Into<bool>) -> Self { self.body.private = Some(value.into()); self } #[inline] pub fn pull_requests(mut self, value: impl Into<bool>) -> Self { self.body.pull_requests = Some(value.into()); self } #[inline] pub fn releases(mut self, value: impl Into<bool>) -> Self { self.body.releases = Some(value.into()); self } #[inline] pub fn repo_name(mut self, value: impl Into<String>) -> MigrateRepoOptionsPostBuilder<CloneAddr, crate::generics::RepoNameExists> { self.body.repo_name = value.into(); unsafe { std::mem::transmute(self) } } /// Name of User or Organisation who will own Repo after migration #[inline] pub fn repo_owner(mut self, value: impl Into<String>) -> Self { self.body.repo_owner = Some(value.into()); self } #[inline] pub fn service(mut self, value: crate::migrate_repo_options::MigrateRepoOptionsService) -> Self { self.body.service = Some(value.into()); self } /// deprecated (only for backwards compatibility) #[inline] pub fn uid(mut self, value: impl Into<i64>) -> Self { self.body.uid = Some(value.into()); self } #[inline] pub fn wiki(mut self, value: impl Into<bool>) -> Self { self.body.wiki = Some(value.into()); self } } impl<Client: crate::client::ApiClient + Sync + 'static> crate::client::Sendable<Client> for MigrateRepoOptionsPostBuilder<crate::generics::CloneAddrExists, crate::generics::RepoNameExists> { type Output = crate::repository::Repository; const METHOD: http::Method = http::Method::POST; fn rel_path(&self) -> std::borrow::Cow<'static, str> { "/repos/migrate".into() } fn modify(&self, req: Client::Request) -> Result<Client::Request, crate::client::ApiError<Client::Response>> { use crate::client::Request; Ok(req .json(&self.body)) } } impl crate::client::ResponseWrapper<crate::repository::Repository, MigrateRepoOptionsPostBuilder<crate::generics::CloneAddrExists, crate::generics::RepoNameExists>> { #[inline] pub fn message(&self) -> Option<String> { self.headers.get("message").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } #[inline] pub fn url(&self) -> Option<String> { self.headers.get("url").and_then(|v| String::from_utf8_lossy(v.as_ref()).parse().ok()) } }
// FIXED fn main() { let n = [0]; let [x] = n; }
use std::ops::Range; use std::marker::PhantomData; use num_traits::AsPrimitive; use renderer::Drawable; use point::Point2; #[derive(Clone, Copy, Debug)] pub struct Rectangle<T> { x0: T, x1: T, y0: T, y1: T, } impl<T> Rectangle<T> { #[inline(always)] pub fn new(x0: T, x1: T, y0: T, y1: T) -> Self { Rectangle { x0, x1, y0, y1 } } } impl<T: Copy + AsPrimitive<i64> + 'static> Drawable<T, Point2<T>> for Rectangle<T> where i64: AsPrimitive<T>, { #[inline(always)] fn vertices(&self) -> usize { 4 } } impl<T: Copy + AsPrimitive<i64> + 'static> IntoIterator for Rectangle<T> where i64: AsPrimitive<T>, { type Item = Point2<T>; type IntoIter = IntoIter<T>; #[inline] fn into_iter(self) -> Self::IntoIter { let x0 = self.x0.as_(); let x1 = self.x1.as_(); let y0 = self.y0.as_(); let y1 = self.y1.as_(); let width = x0..x1; let mut height = y0..y1; let x = width.clone(); let y = height.next(); let _phantom = PhantomData; IntoIter { width, height, x, y, _phantom, } } } #[derive(Debug)] pub struct IntoIter<T> { x: Range<i64>, y: Option<i64>, width: Range<i64>, height: Range<i64>, _phantom: PhantomData<T>, } impl<T: Copy + 'static> Iterator for IntoIter<T> where i64: AsPrimitive<T>, { type Item = Point2<T>; #[inline] fn next(&mut self) -> Option<Self::Item> { let x = self.x.next().or_else(|| { self.height .next() .and_then(|y| { self.y = Some(y); self.x = self.width.clone(); self.x.next() }) .or_else(|| { self.y = None; None }) }); x.and_then(|x| self.y.map(|y| (x.as_(), y.as_()))) } } #[cfg(test)] mod tests { use super::Rectangle; #[test] fn rect() { assert_eq!( Rectangle::new(0, 2, 0, 2).into_iter().collect::<Vec<_>>(), [(0, 0), (1, 0), (0, 1), (1, 1),] ) } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use super::{models, API_VERSION}; #[non_exhaustive] #[derive(Debug, thiserror :: Error)] #[allow(non_camel_case_types)] pub enum Error { #[error(transparent)] PublicMaintenanceConfigurations_List(#[from] public_maintenance_configurations::list::Error), #[error(transparent)] PublicMaintenanceConfigurations_Get(#[from] public_maintenance_configurations::get::Error), #[error(transparent)] ApplyUpdates_GetParent(#[from] apply_updates::get_parent::Error), #[error(transparent)] ApplyUpdates_Get(#[from] apply_updates::get::Error), #[error(transparent)] ApplyUpdates_CreateOrUpdateParent(#[from] apply_updates::create_or_update_parent::Error), #[error(transparent)] ApplyUpdates_CreateOrUpdate(#[from] apply_updates::create_or_update::Error), #[error(transparent)] ConfigurationAssignments_GetParent(#[from] configuration_assignments::get_parent::Error), #[error(transparent)] ConfigurationAssignments_CreateOrUpdateParent(#[from] configuration_assignments::create_or_update_parent::Error), #[error(transparent)] ConfigurationAssignments_DeleteParent(#[from] configuration_assignments::delete_parent::Error), #[error(transparent)] ConfigurationAssignments_Get(#[from] configuration_assignments::get::Error), #[error(transparent)] ConfigurationAssignments_CreateOrUpdate(#[from] configuration_assignments::create_or_update::Error), #[error(transparent)] ConfigurationAssignments_Delete(#[from] configuration_assignments::delete::Error), #[error(transparent)] ConfigurationAssignments_ListParent(#[from] configuration_assignments::list_parent::Error), #[error(transparent)] ConfigurationAssignments_List(#[from] configuration_assignments::list::Error), #[error(transparent)] MaintenanceConfigurations_Get(#[from] maintenance_configurations::get::Error), #[error(transparent)] MaintenanceConfigurations_CreateOrUpdate(#[from] maintenance_configurations::create_or_update::Error), #[error(transparent)] MaintenanceConfigurations_Update(#[from] maintenance_configurations::update::Error), #[error(transparent)] MaintenanceConfigurations_Delete(#[from] maintenance_configurations::delete::Error), #[error(transparent)] MaintenanceConfigurations_List(#[from] maintenance_configurations::list::Error), #[error(transparent)] MaintenanceConfigurationsForResourceGroup_List(#[from] maintenance_configurations_for_resource_group::list::Error), #[error(transparent)] ApplyUpdates_List(#[from] apply_updates::list::Error), #[error(transparent)] ApplyUpdateForResourceGroup_List(#[from] apply_update_for_resource_group::list::Error), #[error(transparent)] ConfigurationAssignmentsWithinSubscription_List(#[from] configuration_assignments_within_subscription::list::Error), #[error(transparent)] Operations_List(#[from] operations::list::Error), #[error(transparent)] Updates_ListParent(#[from] updates::list_parent::Error), #[error(transparent)] Updates_List(#[from] updates::list::Error), } pub mod public_maintenance_configurations { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<models::ListMaintenanceConfigurationsResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Maintenance/publicMaintenanceConfigurations", operation_config.base_path(), subscription_id ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListMaintenanceConfigurationsResult = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_name: &str, ) -> std::result::Result<models::MaintenanceConfiguration, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Maintenance/publicMaintenanceConfigurations/{}", operation_config.base_path(), subscription_id, resource_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceConfiguration = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod apply_updates { use super::{models, API_VERSION}; pub async fn get_parent( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_parent_type: &str, resource_parent_name: &str, provider_name: &str, resource_type: &str, resource_name: &str, apply_update_name: &str, ) -> std::result::Result<models::ApplyUpdate, get_parent::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/{}/{}/providers/Microsoft.Maintenance/applyUpdates/{}", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name, apply_update_name ); let mut url = url::Url::parse(url_str).map_err(get_parent::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_parent::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_parent::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_parent::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ApplyUpdate = serde_json::from_slice(rsp_body).map_err(|source| get_parent::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| get_parent::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_parent::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_parent { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_type: &str, resource_name: &str, apply_update_name: &str, ) -> std::result::Result<models::ApplyUpdate, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/providers/Microsoft.Maintenance/applyUpdates/{}", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_type, resource_name, apply_update_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ApplyUpdate = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update_parent( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_parent_type: &str, resource_parent_name: &str, resource_type: &str, resource_name: &str, ) -> std::result::Result<models::ApplyUpdate, create_or_update_parent::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/{}/{}/providers/Microsoft.Maintenance/applyUpdates/default", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name ); let mut url = url::Url::parse(url_str).map_err(create_or_update_parent::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update_parent::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(create_or_update_parent::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update_parent::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ApplyUpdate = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_parent::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_parent::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update_parent::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update_parent { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_type: &str, resource_name: &str, ) -> std::result::Result<models::ApplyUpdate, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/providers/Microsoft.Maintenance/applyUpdates/default", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_type, resource_name ); let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ApplyUpdate = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<models::ListApplyUpdate, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Maintenance/applyUpdates", operation_config.base_path(), subscription_id ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListApplyUpdate = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod configuration_assignments { use super::{models, API_VERSION}; pub async fn get_parent( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_parent_type: &str, resource_parent_name: &str, resource_type: &str, resource_name: &str, configuration_assignment_name: &str, ) -> std::result::Result<models::ConfigurationAssignment, get_parent::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/{}/{}/providers/Microsoft.Maintenance/configurationAssignments/{}", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name, configuration_assignment_name ); let mut url = url::Url::parse(url_str).map_err(get_parent::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get_parent::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get_parent::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(get_parent::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ConfigurationAssignment = serde_json::from_slice(rsp_body).map_err(|source| get_parent::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| get_parent::Error::DeserializeError(source, rsp_body.clone()))?; Err(get_parent::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get_parent { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update_parent( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_parent_type: &str, resource_parent_name: &str, resource_type: &str, resource_name: &str, configuration_assignment_name: &str, configuration_assignment: &models::ConfigurationAssignment, ) -> std::result::Result<models::ConfigurationAssignment, create_or_update_parent::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/{}/{}/providers/Microsoft.Maintenance/configurationAssignments/{}", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name, configuration_assignment_name ); let mut url = url::Url::parse(url_str).map_err(create_or_update_parent::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update_parent::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(configuration_assignment).map_err(create_or_update_parent::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder .body(req_body) .map_err(create_or_update_parent::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update_parent::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ConfigurationAssignment = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_parent::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update_parent::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update_parent::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update_parent { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete_parent( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_parent_type: &str, resource_parent_name: &str, resource_type: &str, resource_name: &str, configuration_assignment_name: &str, ) -> std::result::Result<delete_parent::Response, delete_parent::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/{}/{}/providers/Microsoft.Maintenance/configurationAssignments/{}", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name, configuration_assignment_name ); let mut url = url::Url::parse(url_str).map_err(delete_parent::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete_parent::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete_parent::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(delete_parent::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ConfigurationAssignment = serde_json::from_slice(rsp_body).map_err(|source| delete_parent::Error::DeserializeError(source, rsp_body.clone()))?; Ok(delete_parent::Response::Ok200(rsp_value)) } http::StatusCode::NO_CONTENT => Ok(delete_parent::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| delete_parent::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete_parent::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete_parent { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::ConfigurationAssignment), NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_type: &str, resource_name: &str, configuration_assignment_name: &str, ) -> std::result::Result<models::ConfigurationAssignment, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/providers/Microsoft.Maintenance/configurationAssignments/{}", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_type, resource_name, configuration_assignment_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ConfigurationAssignment = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_type: &str, resource_name: &str, configuration_assignment_name: &str, configuration_assignment: &models::ConfigurationAssignment, ) -> std::result::Result<models::ConfigurationAssignment, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/providers/Microsoft.Maintenance/configurationAssignments/{}", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_type, resource_name, configuration_assignment_name ); let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(configuration_assignment).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ConfigurationAssignment = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_type: &str, resource_name: &str, configuration_assignment_name: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/providers/Microsoft.Maintenance/configurationAssignments/{}", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_type, resource_name, configuration_assignment_name ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ConfigurationAssignment = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Ok(delete::Response::Ok200(rsp_value)) } http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::ConfigurationAssignment), NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list_parent( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_parent_type: &str, resource_parent_name: &str, resource_type: &str, resource_name: &str, ) -> std::result::Result<models::ListConfigurationAssignmentsResult, list_parent::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/{}/{}/providers/Microsoft.Maintenance/configurationAssignments", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name ); let mut url = url::Url::parse(url_str).map_err(list_parent::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_parent::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_parent::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_parent::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListConfigurationAssignmentsResult = serde_json::from_slice(rsp_body).map_err(|source| list_parent::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list_parent::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_parent::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_parent { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_type: &str, resource_name: &str, ) -> std::result::Result<models::ListConfigurationAssignmentsResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/providers/Microsoft.Maintenance/configurationAssignments", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_type, resource_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListConfigurationAssignmentsResult = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod maintenance_configurations { use super::{models, API_VERSION}; pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, ) -> std::result::Result<models::MaintenanceConfiguration, get::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.Maintenance/maintenanceConfigurations/{}", operation_config.base_path(), subscription_id, resource_group_name, resource_name ); let mut url = url::Url::parse(url_str).map_err(get::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(get::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(get::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(get::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceConfiguration = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| get::Error::DeserializeError(source, rsp_body.clone()))?; Err(get::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod get { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn create_or_update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, configuration: &models::MaintenanceConfiguration, ) -> std::result::Result<models::MaintenanceConfiguration, create_or_update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.Maintenance/maintenanceConfigurations/{}", operation_config.base_path(), subscription_id, resource_group_name, resource_name ); let mut url = url::Url::parse(url_str).map_err(create_or_update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PUT); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(create_or_update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(configuration).map_err(create_or_update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(create_or_update::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(create_or_update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceConfiguration = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body) .map_err(|source| create_or_update::Error::DeserializeError(source, rsp_body.clone()))?; Err(create_or_update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod create_or_update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, configuration: &models::MaintenanceConfiguration, ) -> std::result::Result<models::MaintenanceConfiguration, update::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.Maintenance/maintenanceConfigurations/{}", operation_config.base_path(), subscription_id, resource_group_name, resource_name ); let mut url = url::Url::parse(url_str).map_err(update::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::PATCH); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(update::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); req_builder = req_builder.header("content-type", "application/json"); let req_body = azure_core::to_json(configuration).map_err(update::Error::SerializeError)?; req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(update::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(update::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceConfiguration = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| update::Error::DeserializeError(source, rsp_body.clone()))?; Err(update::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod update { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, resource_name: &str, ) -> std::result::Result<delete::Response, delete::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/Microsoft.Maintenance/maintenanceConfigurations/{}", operation_config.base_path(), subscription_id, resource_group_name, resource_name ); let mut url = url::Url::parse(url_str).map_err(delete::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::DELETE); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(delete::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(delete::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(delete::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceConfiguration = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Ok(delete::Response::Ok200(rsp_value)) } http::StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| delete::Error::DeserializeError(source, rsp_body.clone()))?; Err(delete::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod delete { use super::{models, API_VERSION}; #[derive(Debug)] pub enum Response { Ok200(models::MaintenanceConfiguration), NoContent204, } #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<models::ListMaintenanceConfigurationsResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Maintenance/maintenanceConfigurations", operation_config.base_path(), subscription_id ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListMaintenanceConfigurationsResult = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod maintenance_configurations_for_resource_group { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, ) -> std::result::Result<models::ListMaintenanceConfigurationsResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Maintenance/maintenanceConfigurations", operation_config.base_path(), subscription_id, resource_group_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListMaintenanceConfigurationsResult = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod apply_update_for_resource_group { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, ) -> std::result::Result<models::ListApplyUpdate, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.Maintenance/applyUpdates", operation_config.base_path(), subscription_id, resource_group_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListApplyUpdate = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod configuration_assignments_within_subscription { use super::{models, API_VERSION}; pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<models::ListConfigurationAssignmentsResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/providers/Microsoft.Maintenance/configurationAssignments", operation_config.base_path(), subscription_id ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListConfigurationAssignmentsResult = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod operations { use super::{models, API_VERSION}; pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<models::OperationsListResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!("{}/providers/Microsoft.Maintenance/operations", operation_config.base_path(),); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::OperationsListResult = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } } pub mod updates { use super::{models, API_VERSION}; pub async fn list_parent( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_parent_type: &str, resource_parent_name: &str, resource_type: &str, resource_name: &str, ) -> std::result::Result<models::ListUpdatesResult, list_parent::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/{}/{}/providers/Microsoft.Maintenance/updates", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_parent_type, resource_parent_name, resource_type, resource_name ); let mut url = url::Url::parse(url_str).map_err(list_parent::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list_parent::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list_parent::Error::BuildRequestError)?; let rsp = http_client .execute_request(req) .await .map_err(list_parent::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListUpdatesResult = serde_json::from_slice(rsp_body).map_err(|source| list_parent::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list_parent::Error::DeserializeError(source, rsp_body.clone()))?; Err(list_parent::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list_parent { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, provider_name: &str, resource_type: &str, resource_name: &str, ) -> std::result::Result<models::ListUpdatesResult, list::Error> { let http_client = operation_config.http_client(); let url_str = &format!( "{}/subscriptions/{}/resourcegroups/{}/providers/{}/{}/{}/providers/Microsoft.Maintenance/updates", operation_config.base_path(), subscription_id, resource_group_name, provider_name, resource_type, resource_name ); let mut url = url::Url::parse(url_str).map_err(list::Error::ParseUrlError)?; let mut req_builder = http::request::Builder::new(); req_builder = req_builder.method(http::Method::GET); if let Some(token_credential) = operation_config.token_credential() { let token_response = token_credential .get_token(operation_config.token_credential_resource()) .await .map_err(list::Error::GetTokenError)?; req_builder = req_builder.header(http::header::AUTHORIZATION, format!("Bearer {}", token_response.token.secret())); } url.query_pairs_mut().append_pair("api-version", super::API_VERSION); let req_body = bytes::Bytes::from_static(azure_core::EMPTY_BODY); req_builder = req_builder.uri(url.as_str()); let req = req_builder.body(req_body).map_err(list::Error::BuildRequestError)?; let rsp = http_client.execute_request(req).await.map_err(list::Error::ExecuteRequestError)?; match rsp.status() { http::StatusCode::OK => { let rsp_body = rsp.body(); let rsp_value: models::ListUpdatesResult = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Ok(rsp_value) } status_code => { let rsp_body = rsp.body(); let rsp_value: models::MaintenanceError = serde_json::from_slice(rsp_body).map_err(|source| list::Error::DeserializeError(source, rsp_body.clone()))?; Err(list::Error::DefaultResponse { status_code, value: rsp_value, }) } } } pub mod list { use super::{models, API_VERSION}; #[derive(Debug, thiserror :: Error)] pub enum Error { #[error("HTTP status code {}", status_code)] DefaultResponse { status_code: http::StatusCode, value: models::MaintenanceError, }, #[error("Failed to parse request URL: {0}")] ParseUrlError(url::ParseError), #[error("Failed to build request: {0}")] BuildRequestError(http::Error), #[error("Failed to execute request: {0}")] ExecuteRequestError(azure_core::HttpError), #[error("Failed to serialize request body: {0}")] SerializeError(serde_json::Error), #[error("Failed to deserialize response: {0}, body: {1:?}")] DeserializeError(serde_json::Error, bytes::Bytes), #[error("Failed to get access token: {0}")] GetTokenError(azure_core::Error), } } }
#[doc = "Register `C1ISR` reader"] pub type R = crate::R<C1ISR_SPEC>; #[doc = "Field `ISFm` reader - CPU(n) semaphore m status bit before enable (mask)"] pub type ISFM_R = crate::FieldReader<u32>; impl R { #[doc = "Bits 0:31 - CPU(n) semaphore m status bit before enable (mask)"] #[inline(always)] pub fn isfm(&self) -> ISFM_R { ISFM_R::new(self.bits) } } #[doc = "HSEM Interrupt status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`c1isr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct C1ISR_SPEC; impl crate::RegisterSpec for C1ISR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`c1isr::R`](R) reader structure"] impl crate::Readable for C1ISR_SPEC {} #[doc = "`reset()` method sets C1ISR to value 0"] impl crate::Resettable for C1ISR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::path::Path; use std::io::BufReader; use std::io::prelude::*; use std::fs::File; use std::collections::HashMap; fn main() { solve_problem_1_phase_1(); solve_problem_1_phase_2(); } fn solve_problem_1_phase_1() -> i32 { let input = read_input(); for (num, count) in input.iter() { let remaining = 2020 - num; if input.contains_key(&remaining) && *num != remaining { println!("Result (phase1) is {} * {} = {}", num, remaining, num * remaining); return num * remaining; } else if *num == 1010 && *count > 1 { println!("Result (phase1) is {} * {} = {}", num, num, num * num); return num * num; } } return -1; } fn solve_problem_1_phase_2() -> i32 { let input = read_input(); for (num1, count_num_1) in input.iter() { // 3a = 2020 if *count_num_1 >= 3 && num1 * 3 == 2020 { println!("Result (phase2) is {} * {} * {} = {}", num1, num1, num1, num1 * num1 * num1); return num1 * num1 * num1; } // a+a+remaining=2020 if *count_num_1 >= 2 { let remaining = 2020 - 2 * num1; if input.contains_key(&remaining) { println!("Result (phase2) is {} * {} * {} = {}", num1, num1, remaining, num1 * num1 * remaining); return num1 * num1 * remaining; } } // a+b+remaining=2020 for (num2, _) in input.iter() { if *num1 != *num2 { let remaining = 2020 - num1 - num2; if input.contains_key(&remaining) { println!("Result (phase2) is {} * {} * {} = {}", num1, num2, remaining, num1 * num2 * remaining); return num1 * num2 * remaining; } } } } return -1; } fn read_input() -> HashMap<i32, i32> { let path = Path::new("day_1/src/phase_1_input.txt"); let file = BufReader::new(File::open(&path).unwrap()); let mut expenses = HashMap::new(); for line in file.lines() { let num = line.unwrap().parse::<i32>().unwrap(); if let Some(x) = expenses.get_mut(&num) { *x = *x + 1; } else { expenses.insert(num, 1); } } return expenses; }
use actix_web::HttpResponse; use cloudevents::http; use cloudevents::Event; use serde::Serialize; pub struct EventWriter {} impl http::EventWriter<HttpResponse> for EventWriter { fn write_cloud_event(res: http::HttpEvent) -> Result<HttpResponse, http::WriterError> { match res { http::HttpEvent::Binary(e) => write_binary(e), http::HttpEvent::Structured(e) => serialize_and_write(e, http::CE_JSON_CONTENT_TYPE), http::HttpEvent::Batch(vec) => serialize_and_write(vec, http::CE_BATCH_JSON_CONTENT_TYPE), } } } fn write_binary(event: Event) -> Result<HttpResponse, http::WriterError> { // Write headers let mut builder = HttpResponse::Ok(); builder.header(http::CE_ID_HEADER, event.id); builder.header(http::CE_SPECVERSION_HEADER, event.spec_version.to_string()); builder.header(http::CE_SOURCE_HEADER, event.source); builder.header(http::CE_TYPE_HEADER, event.event_type); if let Some(sub) = event.subject { builder.header(http::CE_SUBJECT_HEADER, sub); } if let Some(time) = event.time { builder.header(http::CE_TIME_HEADER, time.to_rfc3339()); } let result = if let Some(p) = event.payload { builder.content_type(p.content_type).body(p.data) } else { builder.finish() }; Ok(result) } fn serialize_and_write<T: Serialize>(value: T, content_type: &str) -> Result<HttpResponse, http::WriterError> { Ok(serde_json::to_vec(&value) .map(|j| { HttpResponse::Ok() .content_type(content_type) .body(j) })? ) }
use crate::{BotResult, CommandData, Context}; use std::sync::Arc; #[command] #[short_desc("https://youtu.be/SyJMQg3spck?t=43")] #[bucket("songs")] #[no_typing()] async fn saygoodbye(ctx: Arc<Context>, data: CommandData) -> BotResult<()> { let (lyrics, delay) = _saygoodbye(); super::song_send(lyrics, delay, ctx, data).await } pub fn _saygoodbye() -> (&'static [&'static str], u64) { let lyrics = &[ "It still kills meeee", "(it - still - kills - me)", "That I can't change thiiiings", "(that I - can't - change - things)", "But I'm still dreaming", "I'll rewrite the ending", "So you'll take back the lies", "Before we say our goodbyes", "\\~\\~\\~ say our goodbyyeees \\~\\~\\~", ]; (lyrics, 2500) }
use crate::stratum::StratumClient; use crate::worker::{start_worker, WorkerController, WorkerMessage}; use actix::{Actor, Arbiter, Context, System}; use anyhow::Result; use config::MinerConfig; use futures::channel::mpsc; use futures::stream::StreamExt; use indicatif::{MultiProgress, ProgressBar, ProgressStyle}; use logger::prelude::*; use std::thread; use types::U256; pub struct Miner { job_rx: mpsc::UnboundedReceiver<(Vec<u8>, U256)>, nonce_rx: mpsc::UnboundedReceiver<(Vec<u8>, u64)>, worker_controller: WorkerController, stratum_client: StratumClient, pb: Option<ProgressBar>, num_seals_found: u64, } impl Miner { pub async fn new(config: MinerConfig) -> Result<Self> { let mut stratum_client = StratumClient::new(&config)?; let job_rx = stratum_client.subscribe().await?; let (nonce_tx, nonce_rx) = mpsc::unbounded(); let (worker_controller, pb) = if config.enable_stderr { let mp = MultiProgress::new(); let pb = mp.add(ProgressBar::new(10)); pb.set_style(ProgressStyle::default_bar().template("{msg:.green}")); let worker_controller = start_worker(&config, nonce_tx, Some(&mp)); thread::spawn(move || { mp.join().expect("MultiProgress join failed"); }); (worker_controller, Some(pb)) } else { let worker_controller = start_worker(&config, nonce_tx, None); (worker_controller, None) }; Ok(Self { job_rx, nonce_rx, worker_controller, stratum_client, pb, num_seals_found: 0, }) } pub async fn start(&mut self) { info!("Miner client started"); loop { debug!("In miner client select loop"); futures::select! { job = self.job_rx.select_next_some() => { let (pow_header, diff) = job; self.start_mint_work(pow_header, diff).await; }, seal = self.nonce_rx.select_next_some() => { let (pow_header, nonce) = seal; self.submit_seal(pow_header, nonce).await; } } } } async fn submit_seal(&mut self, pow_header: Vec<u8>, nonce: u64) { self.worker_controller .send_message(WorkerMessage::Stop) .await; if let Err(err) = self .stratum_client .submit_seal((pow_header.clone(), nonce)) .await { error!("Submit seal to stratum failed: {:?}", err); return; } { self.num_seals_found += 1; let msg = format!( "Miner client Total seals found: {:>3}", self.num_seals_found ); if let Some(pb) = self.pb.as_ref() { pb.set_message(&msg); pb.inc(1); } else { info!("{}", msg) } } } async fn start_mint_work(&mut self, pow_header: Vec<u8>, diff: U256) { self.worker_controller .send_message(WorkerMessage::NewWork { pow_header, diff }) .await } } pub struct MinerClientActor { config: MinerConfig, } impl MinerClientActor { pub fn new(config: MinerConfig) -> Self { MinerClientActor { config } } } impl Actor for MinerClientActor { type Context = Context<Self>; fn started(&mut self, _ctx: &mut Self::Context) { let config = self.config.clone(); let arbiter = Arbiter::new(); let fut = async move { let miner_cli = Miner::new(config).await; match miner_cli { Err(e) => { error!("Start miner client failed: {:?}", e); System::current().stop(); } Ok(mut miner_cli) => miner_cli.start().await, } }; arbiter.send(Box::pin(fut)); } }
tonic::include_proto!("helloworld"); tonic::include_proto!("grpc.examples.echo"); wasm_bindgen_test_configure!(run_in_browser); use js_sys::Date; use grpc_web_client::Client; use wasm_bindgen_test::*; #[wasm_bindgen_test] async fn hello_world() { let client = Client::new("http://127.0.0.1:8080".to_string()); let mut client = greeter_client::GreeterClient::new(client); let request = tonic::Request::new(HelloRequest { name: "WebTonic".into(), }); let response = client.say_hello(request).await.unwrap().into_inner(); assert_eq!(response.message, "Hello WebTonic!"); } #[wasm_bindgen_test] async fn echo_unary() { let client = Client::new("http://127.0.0.1:8080".to_string()); let mut client = echo_client::EchoClient::new(client); let request = tonic::Request::new(EchoRequest { message: "Echo Test".to_string(), }); let response = client.unary_echo(request).await.unwrap().into_inner(); assert_eq!(response.message, "Echo Test"); } #[wasm_bindgen_test] async fn echo_server_stream() { let client = Client::new("http://127.0.0.1:8080".to_string()); let mut client = echo_client::EchoClient::new(client); let request = tonic::Request::new(EchoRequest { message: "Echo Test".to_string(), }); let mut response = client .server_streaming_echo(request) .await .unwrap() .into_inner(); assert_eq!( response.message().await.unwrap().unwrap().message, "Echo Test" ); let before_recv = Date::now(); assert_eq!( response.message().await.unwrap().unwrap().message, "Echo Test" ); let after_recv = Date::now(); assert!(after_recv - before_recv > 100.0); }
use std::{ffi::CString, io::SeekFrom}; use crate::{ items::{BlockGroupType, ChunkItem}, sizes, Checksum, DiskKey, DiskKeyType, }; use bitflags::bitflags; use enum_primitive::*; use fal::{read_u16, read_u32, read_u64, read_u8, read_uuid, write_u64, write_u8}; const SUPERBLOCK_OFFSETS: [u64; 4] = [64 * sizes::K, 64 * sizes::M, 256 * sizes::G, 1 * sizes::P]; const CHECKSUM_SIZE: usize = 32; const MAGIC: u64 = 0x4D5F53665248425F; // ASCII for "_BHRfS_M" #[derive(Debug)] pub struct Superblock { pub checksum: Checksum, pub fs_id: uuid::Uuid, pub byte_number: u64, pub flags: SuperblockFlags, pub magic: u64, pub generation: u64, pub root: u64, pub chunk_root: u64, pub log_root: u64, pub log_root_transid: u64, pub total_byte_count: u64, pub total_bytes_used: u64, pub root_dir_objectid: u64, pub device_count: u64, pub sector_size: u32, pub node_size: u32, pub unused_leaf_size: u32, pub stripe_size: u32, pub system_chunk_array_size: u32, pub chunk_root_gen: u64, pub optional_flags: u64, pub flags_for_write_support: u64, pub required_flags: u64, pub checksum_type: ChecksumType, pub root_level: u8, pub chunk_root_level: u8, pub log_root_level: u8, pub device_properties: DeviceProperties, pub device_label: CString, // TODO: Is this really a C string? pub cache_generation: u8, pub uuid_tree_generation: u8, pub metadata_uuid: uuid::Uuid, pub system_chunk_array: SystemChunkArray, pub root_backups: [RootBackup; 4], } #[derive(Debug)] pub struct SystemChunkArray(pub Vec<(DiskKey, ChunkItem)>); #[derive(Debug)] pub struct DeviceProperties { pub id: u64, pub size: u64, pub bytes_used: u64, pub io_alignment: u32, pub io_width: u32, pub sector_size: u32, pub type_and_info: u64, pub generation: u64, pub start_byte: u64, pub group: u32, pub seek_speed: u8, pub bandwidth: u8, pub uuid: uuid::Uuid, pub fs_uuid: uuid::Uuid, } enum_from_primitive! { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub enum ChecksumType { Crc32 = 0, } } impl Superblock { pub fn load<D: fal::Device>(device: &mut D) -> Self { let disk_size = device.seek(SeekFrom::End(0)).unwrap(); let mut block = [0u8; 4096]; SUPERBLOCK_OFFSETS .iter() .copied() .filter(|offset| offset + 4096 < disk_size) .map(|offset| { device.seek(SeekFrom::Start(offset)).unwrap(); device.read_exact(&mut block).unwrap(); Self::parse(&block) }) .max_by_key(|sb| sb.generation) .unwrap() } pub fn parse(block: &[u8]) -> Self { let mut checksum = [0u8; CHECKSUM_SIZE]; checksum.copy_from_slice(&block[..32]); let fs_id = read_uuid(&block, 32); let byte_number = read_u64(&block, 48); let flags = SuperblockFlags::from_bits(read_u64(&block, 56)).unwrap(); let magic = read_u64(&block, 64); assert_eq!(magic, MAGIC); let generation = read_u64(&block, 72); let root = read_u64(&block, 80); let chunk_root = read_u64(&block, 88); let log_root = read_u64(&block, 96); let log_root_transid = read_u64(&block, 104); let total_byte_count = read_u64(&block, 112); let total_bytes_used = read_u64(&block, 120); let root_dir_objectid = read_u64(&block, 128); let device_count = read_u64(&block, 136); let sector_size = read_u32(&block, 144); let node_size = read_u32(&block, 148); let unused_leaf_size = read_u32(&block, 152); let stripe_size = read_u32(&block, 156); let system_chunk_array_size = read_u32(&block, 160); let chunk_root_gen = read_u64(&block, 164); let optional_flags = read_u64(&block, 172); let flags_for_write_support = read_u64(&block, 180); let required_flags = read_u64(&block, 188); let checksum_type = ChecksumType::from_u16(read_u16(&block, 196)).unwrap(); let root_level = read_u8(&block, 198); let chunk_root_level = read_u8(&block, 199); let log_root_level = read_u8(&block, 200); let device_properties = { let id = read_u64(&block, 201); let size = read_u64(&block, 209); let bytes_used = read_u64(&block, 217); let io_alignment = read_u32(&block, 225); let io_width = read_u32(&block, 229); let sector_size = read_u32(&block, 233); let type_and_info = read_u64(&block, 237); let generation = read_u64(&block, 245); let start_byte = read_u64(&block, 253); let group = read_u32(&block, 261); let seek_speed = read_u8(&block, 265); let bandwidth = read_u8(&block, 266); let device_uuid = read_uuid(&block, 267); let fs_uuid = read_uuid(&block, 283); assert_eq!(fs_uuid, fs_id); DeviceProperties { id, size, bytes_used, io_alignment, io_width, sector_size, type_and_info, generation, start_byte, group, seek_speed, bandwidth, fs_uuid, uuid: device_uuid, } }; let device_label = { let label_bytes = &block[299..=554]; let nul_position = label_bytes .iter() .copied() .position(|byte| byte == 0) .unwrap(); let label_bytes_to_nul = &label_bytes[..nul_position]; CString::new(label_bytes_to_nul).unwrap() }; let cache_generation = read_u8(&block, 555); let uuid_tree_generation = read_u8(&block, 556); let metadata_uuid = read_uuid(&block, 557); let system_chunk_array = &block[811..=2858]; let mut root_backups = [Default::default(); 4]; for (index, backup) in root_backups.iter_mut().enumerate() { *backup = RootBackup::from_raw( &block[2859 + index * RootBackup::RAW_SIZE ..2859 + (index + 1) * RootBackup::RAW_SIZE], ); } Self { checksum: Checksum::new(checksum_type, &checksum), fs_id, byte_number, flags, magic, generation, root, chunk_root, log_root, log_root_transid, total_byte_count, total_bytes_used, root_dir_objectid, device_count, sector_size, node_size, unused_leaf_size, stripe_size, system_chunk_array_size, chunk_root_gen, optional_flags, flags_for_write_support, required_flags, checksum_type, root_level, chunk_root_level, log_root_level, device_properties, device_label, cache_generation, uuid_tree_generation, metadata_uuid, system_chunk_array: SystemChunkArray::parse( &system_chunk_array[..system_chunk_array_size as usize], ), root_backups, } } } #[derive(Clone, Copy, Debug, Default)] pub struct RootBackup { pub tree_root: u64, pub tree_root_generation: u64, pub chunk_root: u64, pub chunk_root_generation: u64, pub extent_root: u64, pub extent_root_generation: u64, pub filesystem_root: u64, pub filesystem_root_generation: u64, pub device_root: u64, pub device_root_generation: u64, pub checksum_root: u64, pub checksum_root_generation: u64, pub total_bytes: u64, pub bytes_used: u64, pub device_count: u64, pub tree_root_level: u8, pub chunk_root_level: u8, pub extent_root_level: u8, pub filesystem_root_level: u8, pub device_root_level: u8, pub checksum_root_level: u8, } impl RootBackup { pub const RAW_SIZE: usize = 168; pub fn from_raw(bytes: &[u8]) -> Self { assert!(bytes.len() >= Self::RAW_SIZE); Self { tree_root: read_u64(bytes, 0), tree_root_generation: read_u64(bytes, 8), chunk_root: read_u64(bytes, 16), chunk_root_generation: read_u64(bytes, 24), extent_root: read_u64(bytes, 32), extent_root_generation: read_u64(bytes, 40), filesystem_root: read_u64(bytes, 48), filesystem_root_generation: read_u64(bytes, 56), device_root: read_u64(bytes, 64), device_root_generation: read_u64(bytes, 72), checksum_root: read_u64(bytes, 80), checksum_root_generation: read_u64(bytes, 88), total_bytes: read_u64(bytes, 96), bytes_used: read_u64(bytes, 104), device_count: read_u64(bytes, 112), // 120..=151 unused tree_root_level: read_u8(bytes, 152), chunk_root_level: read_u8(bytes, 153), extent_root_level: read_u8(bytes, 154), filesystem_root_level: read_u8(bytes, 155), device_root_level: read_u8(bytes, 156), checksum_root_level: read_u8(bytes, 157), // 158..=167 unused } } pub fn to_raw(this: Self, bytes: &mut [u8]) { assert!(bytes.len() >= Self::RAW_SIZE); write_u64(bytes, 0, this.tree_root); write_u64(bytes, 8, this.tree_root_generation); write_u64(bytes, 16, this.chunk_root); write_u64(bytes, 24, this.chunk_root_generation); write_u64(bytes, 32, this.extent_root); write_u64(bytes, 40, this.extent_root_generation); write_u64(bytes, 48, this.filesystem_root); write_u64(bytes, 56, this.filesystem_root_generation); write_u64(bytes, 64, this.device_root); write_u64(bytes, 72, this.device_root_generation); write_u64(bytes, 80, this.checksum_root); write_u64(bytes, 88, this.checksum_root_generation); write_u64(bytes, 96, this.total_bytes); write_u64(bytes, 104, this.bytes_used); write_u64(bytes, 112, this.device_count); // 120..=151 unused write_u8(bytes, 152, this.tree_root_level); write_u8(bytes, 153, this.chunk_root_level); write_u8(bytes, 154, this.extent_root_level); write_u8(bytes, 155, this.filesystem_root_level); write_u8(bytes, 156, this.device_root_level); write_u8(bytes, 157, this.checksum_root_level); // 158..=167 unused } } impl SystemChunkArray { pub fn parse(bytes: &[u8]) -> Self { let stride = DiskKey::LEN + ChunkItem::LEN; let pairs = (0..bytes.len() / stride) .map(|i| { let key_bytes = &bytes[i * stride..i * stride + DiskKey::LEN]; let chunk_bytes = &bytes[i * stride + DiskKey::LEN..(i + 1) * stride]; let key = DiskKey::parse(key_bytes); assert_eq!(key.ty, DiskKeyType::ChunkItem); let chunk = ChunkItem::parse(chunk_bytes); assert!(chunk.ty.contains(BlockGroupType::SYSTEM)); // Only RAID 0 is supported so far. assert_eq!( chunk.stripe_count, 1, "Unimplemented RAID configuration with stripe count {}", chunk.stripe_count ); assert_eq!( chunk.sub_stripe_count, 0, "Unimplemented RAID configuration with sub stripe count (used for RAID 10) {}", chunk.sub_stripe_count ); (key, chunk) }) .collect(); Self(pairs) } } bitflags! { pub struct SuperblockFlags: u64 { const WRITTEN = 1 << 0; const RELOC = 1 << 1; const ERROR = 1 << 2; const SEEDING = 1 << 32; const METADUMP = 1 << 33; const METADUMP_V2 = 1 << 34; const CHANGING_FSID = 1 << 35; const CHANGING_FSID_V2 = 1 << 36; } }
use { crate::{ client::{self, RequestType}, entities::*, Client, }, serde_json::json, std::error::Error, }; /// Log into an existing listen.moe account pub async fn login( username: String, password: String, otp: Option<String>, ) -> Result<Client, Box<dyn Error>> { let body = json!({ "username": username, "password": password, }); let encoded_body = match serde_json::to_vec(&body) { Ok(val) => val, Err(e) => return Err(e.into()), }; let mfa_token = match client::perform_request::<GeneralMessage>( RequestType::Post(encoded_body), "/login".into(), None, ) .await { Ok((code, val)) if code != 200 => return Err(failure::err_msg(val.message).into()), Ok((_, val)) if !val.mfa => return Ok(Client(val.token)), Ok((_, val)) if val.mfa && otp.is_none() => { return Err(failure::err_msg("The account is 2FA enabled").into()) } Ok((_, val)) => val.token, Err(e) => return Err(e.into()), }; let temp_client = Client(mfa_token); let body = json!({ "token": otp, }); let encoded_body = match serde_json::to_vec(&body) { Ok(val) => val, Err(e) => return Err(e.into()), }; match client::perform_request::<GeneralMessage>( RequestType::Post(encoded_body), "/login/mfa".into(), Some(&temp_client), ) .await { Ok((code, val)) if code != 200 => Err(failure::err_msg(val.message).into()), Ok((_, val)) => Ok(Client(val.token)), Err(e) => Err(e.into()), } } /// Register a new listen.moe account /// You have to log in afterwards pub async fn register( username: String, email: String, password: String, ) -> Result<GeneralMessage, Box<dyn Error>> { let body = json!({ "username": username, "email": email, "password": password, }); let encoded_body = match serde_json::to_vec(&body) { Ok(val) => val, Err(e) => return Err(e.into()), }; match client::perform_request::<GeneralMessage>( RequestType::Post(encoded_body), "/register".into(), None, ) .await { Ok((code, val)) if code != 200 => Err(failure::err_msg(val.message).into()), Ok((_, val)) => Ok(val), Err(e) => Err(e.into()), } }
use super::*; fn do_open(path: &str, flags: u32, mode: u32) -> Result<FileDesc> { let current = current!(); let fs = current.fs().lock().unwrap(); let file = fs.open_file(path, flags, mode)?; let file_ref: Arc<Box<dyn File>> = Arc::new(file); let fd = { let creation_flags = CreationFlags::from_bits_truncate(flags); current.add_file(file_ref, creation_flags.must_close_on_spawn()) }; Ok(fd) } pub fn do_openat(dirfd: DirFd, path: &str, flags: u32, mode: u32) -> Result<FileDesc> { println!( "openat: dirfd: {:?}, path: {:?}, flags: {:#o}, mode: {:#o}", dirfd, path, flags, mode ); let path = match dirfd { DirFd::Fd(dirfd) => { let dir_path = get_dir_path(dirfd)?; dir_path + "/" + path } DirFd::Cwd => path.to_owned(), }; do_open(&path, flags, mode) }
use libpulse_binding::{sample, stream}; use libpulse_simple_binding::Simple; use std::net::{SocketAddr, UdpSocket}; use std::sync::{Arc, RwLock}; use std::thread; const SAMPLING_RATE: u32 = 48000; const FRAME_SIZE: usize = 2880; fn main() { let clients: Arc<RwLock<Vec<SocketAddr>>> = Arc::new(RwLock::new(Vec::new())); let clients_server = clients.clone(); let clients_main = clients.clone(); thread::spawn(move || start_server(clients_server)); let socket = UdpSocket::bind("0.0.0.0:8081").unwrap(); let mut audio = [0; 2 * FRAME_SIZE]; loop { grab_audio(&mut audio); println!("{:?}\n", audio.to_vec()); for client in clients_main.read().unwrap().iter() { socket.send_to(&audio, client).unwrap(); } } } fn start_server(clients: Arc<RwLock<Vec<SocketAddr>>>) { let socket = UdpSocket::bind("0.0.0.0:8080").unwrap(); let mut buf = [0; 100]; loop { let (_size, addr) = socket.recv_from(&mut buf).unwrap(); if !clients.read().unwrap().contains(&addr) { clients.write().unwrap().push(addr); } } } fn grab_audio(mut buffer: &mut [u8]) { let spec = sample::Spec { format: sample::SAMPLE_S16NE, channels: 2, rate: SAMPLING_RATE, }; let s = Simple::new( None, "onkyo", stream::Direction::Record, None, "Stream", &spec, None, None, ) .unwrap(); s.read(&mut buffer).unwrap(); }
use std::env; use std::io::BufReader; use std::io::BufRead; use std::fs::File; use std::collections::HashMap; fn gen_seq() { let mut pos: HashMap<usize, usize> = HashMap::new(); let mut prev = 0; let mut cur = 0; println!("{}", cur); let mut i = 1; loop { if pos[&cur] == 0 { cur = 0; } else { cur = i - pos[&cur]; } pos.insert(prev, i); prev = cur; println!("{}", cur); i += 1; } } fn search(filename: String) { let mut i = 0; let mut tn = 0; let mut known: HashMap<usize, usize> = HashMap::new(); let f = File::open(filename).unwrap(); let file = BufReader::new(&f); for line in file.lines() { let l = line.unwrap(); let x = l.parse::<usize>().unwrap(); if x >= i && !known.contains_key(&x) { known.insert(x, tn); } if known.contains_key(&i) { println!("\rFound {} at term {} ", i, known[&i]); known.remove(&i); i += 1; } else { print!("\rSearching for {} at term {}", i, tn); } tn += 1; } } fn main() { let args: Vec<String> = env::args().collect(); if args.len() > 1 && args[1] == "search" { search(args[2].clone()); } else { gen_seq(); } }
use regex::Regex; use std::cmp::max; use std::collections::HashMap; use std::io::{self}; fn get_happiness(names: &Vec<&str>, scores: &HashMap<&str, HashMap<&str, i32>>) -> i32 { let mut total_score = 0; for i in 0..names.len() { let left_neighbour = if i > 0 { names[i - 1] } else { names.last().unwrap() }; let right_neighbour = if i < names.len() - 1 { names[i + 1] } else { names.first().unwrap() }; let person_scores = scores.get(names[i]).unwrap(); total_score += person_scores.get(left_neighbour).unwrap(); total_score += person_scores.get(right_neighbour).unwrap(); } total_score } fn permutations(mut vec: Vec<&str>, l: usize, r: usize) -> Vec<Vec<&str>> { let mut vecs: Vec<Vec<&str>> = Vec::new(); if r == l { return vec![vec]; } else { for i in l..=r { let tmp = vec[l]; vec[l] = vec[i]; vec[i] = tmp; vecs.extend(permutations(vec.to_vec(), l + 1, r)); let tmp = vec[l]; vec[l] = vec[i]; vec[i] = tmp; } } vecs } fn main() -> io::Result<()> { let files_results = vec![("test.txt", 330, 286), ("input.txt", 664, 640)]; for (f, result_1, result_2) in files_results.into_iter() { println!("File: {}", f); let file_content: Vec<String> = std::fs::read_to_string(f)? .lines() .map(|x| x.to_string()) .collect(); let mut happiness: HashMap<&str, HashMap<&str, i32>> = HashMap::new(); let re = Regex::new(r"(\w+) would (\w+) (\d+) happiness units by sitting next to (\w+).") .unwrap(); for line in file_content.iter() { let caps = re.captures(&line).unwrap(); let name_1 = caps.get(1).map_or("", |m| m.as_str()); let name_2 = caps.get(4).map_or("", |m| m.as_str()); let cmd = caps.get(2).map_or("", |m| m.as_str()); let modifier = if cmd == "gain" { 1 } else { -1 }; let number = caps .get(3) .map_or("", |m| m.as_str()) .parse::<i32>() .unwrap() * modifier; happiness .entry(&name_1) .and_modify(|x| { x.insert(name_2, number); }) .or_insert( vec![(name_2, number), ("myself", 0)] .into_iter() .collect::<HashMap<&str, i32>>(), ); } let names: Vec<&str> = happiness.keys().cloned().collect(); let mut permuted = permutations(names[1..].to_vec(), 0, names.len() - 2); for row in &mut permuted { row.push(names[0]); } let mut max_score = 0; for perm in permuted.iter() { max_score = max(max_score, get_happiness(&perm, &happiness)); } assert_eq!(max_score, result_1); happiness.entry("myself").or_insert_with(HashMap::new); for name in names.iter() { if name != &"myself" { happiness.entry("myself").and_modify(|x| { x.insert(name, 0); }); } } let names: Vec<&str> = happiness.keys().cloned().collect(); let mut permuted = permutations(names[1..].to_vec(), 0, names.len() - 2); for row in &mut permuted { row.push(names[0]); } let mut max_score = 0; for perm in permuted.iter() { max_score = max(max_score, get_happiness(&perm, &happiness)); } assert_eq!(max_score, result_2); } Ok(()) }
use super::{Node, Priority, BLOCK_SIZE}; use itertools::Itertools; use rand::random; use std::ops::Range; pub struct ITreap<C> { root: Node<C>, } impl<C> std::ops::Index<usize> for ITreap<C> { type Output = C; /// Borrows the `i`th element. /// Cost is O(log(n/B)). fn index(&self, i: usize) -> &Self::Output { self.root.get(i).unwrap() } } impl<C> std::ops::IndexMut<usize> for ITreap<C> { /// Mutably borrows the `i`th element. /// Cost is O(log(n/B)). fn index_mut(&mut self, i: usize) -> &mut Self::Output { self.root.get_mut(i).unwrap() } } impl<C> ITreap<C> { /// Create a new empty indexed treap. pub fn new() -> Self { ITreap { root: Node::Leaf(Vec::new()), } } /// Checks that the data structure respects its constraints. pub(super) fn is_valid(&self) -> bool { self.root.is_valid(None) } /// Inserts an element at position `index`. /// Cost is O(log(n/B)+B). /// /// # Example /// /// ``` /// use itreap::ITreap; /// /// let mut t = ITreap::new(); /// /// t.insert(0, 7); // [7] /// t.insert(0, 2); // [2,7] /// t.insert(1, 3); // [2,3,7] /// /// assert!(t.iter().eq(&[2, 3, 7])) /// ``` pub fn insert(&mut self, index: usize, element: C) { self.root.insert(index, element) } /// Adds an element to the back. /// Cost is O(log(n/B)+1). /// /// # Example /// /// ``` /// use itreap::ITreap; /// /// let mut t = ITreap::new(); /// /// t.push(2); /// t.push(4); /// t.push(6); /// /// assert!(t.iter().eq(&[2, 4 ,6])) /// ``` pub fn push(&mut self, element: C) { self.insert(self.len(), element) } /// Returns the number of elements in the indexed treap. /// Cost is O(1). pub fn len(&self) -> usize { self.root.len() } /// Loops on all elements. /// Cost is O(n). pub fn iter<'a>(&'a self) -> impl Iterator<Item = &'a C> + 'a { self.between(0..self.root.len()) } /// Loop on all elements corresponding to indices in given range. /// Cost is O(log(n/B) + k) where k designates the number of elements we should loop upon. /// /// # Example /// /// ``` /// use itreap::ITreap; /// /// let t:ITreap<_> = (0..10).map(|e| e*2).collect(); /// assert!(t.between(1..4).eq(&[2, 4, 6])) /// ``` pub fn between<'a>( &'a self, selection: std::ops::Range<usize>, ) -> impl Iterator<Item = &'a C> + 'a { let mut remaining_nodes = std::iter::once((&self.root, 0..self.root.len())) .filter(|(_, r)| !intersect_ranges(r, &selection).is_empty()) .collect::<Vec<_>>(); let mut current_block = None; let mut current_block_iter = None; std::iter::from_fn(move || loop { while current_block.is_none() && !remaining_nodes.is_empty() { let (next_node, next_node_range) = remaining_nodes.pop().unwrap(); match next_node { Node::Inner(_, _, [left, right]) => { let right_start = next_node_range.start + left.len(); let right_range = right_start..next_node_range.end; let left_range = next_node_range.start..right_start; if !intersect_ranges(&right_range, &selection).is_empty() { remaining_nodes.push((right, right_range)); } if !intersect_ranges(&left_range, &selection).is_empty() { remaining_nodes.push((left, left_range)); } } Node::Leaf(block) => { current_block = Some(block); let selected = intersect_ranges(&next_node_range, &selection); let retained_elements = (selected.start - next_node_range.start) ..(selected.end - next_node_range.start); current_block_iter = current_block.as_ref().map(|b| b[retained_elements].iter()) } } } if let Some(iter) = &mut current_block_iter { let maybe_next_value = iter.next(); if let Some(next_value) = maybe_next_value { return Some(next_value); } else { current_block_iter = None; current_block = None; } } else { return None; } }) } } impl<C> std::default::Default for ITreap<C> { fn default() -> Self { ITreap::new() } } impl<C> std::iter::FromIterator<C> for ITreap<C> { /// Transform an iterator into an indexed treap. /// This will always create a perfectly balanced tree. /// Cost is O(n). fn from_iter<T: IntoIterator<Item = C>>(iter: T) -> Self { // avoid inserting elements one by one. // spread all elements directly into their final blocks let (mut tree, leaves) = iter.into_iter().chunks(BLOCK_SIZE / 2).into_iter().fold( (Vec::new(), 0), |(mut tree, leaves), chunk| { // we keep a stack of nodes // and merge the last two nodes when the get equal size let block = chunk.collect::<Vec<_>>(); tree.push(Box::new(Node::Leaf(block))); loop { let l = tree.len(); if l >= 2 && tree[l - 1].len() == tree[l - 2].len() { let right_node = tree.pop().unwrap(); let left_node = tree.pop().unwrap(); let size = left_node.len() + right_node.len(); // let's have a fake priority, we'll set it later let merged = Node::Inner(0, size, [left_node, right_node]); tree.push(Box::new(merged)); } else { break; } } (tree, leaves + 1) }, ); let right_node = tree.pop(); if let Some(mut right_node) = right_node { // build the treap while let Some(left_node) = tree.pop() { let size = left_node.len() + right_node.len(); right_node = Box::new(Node::Inner(0, size, [left_node, right_node])); } let mut treap = ITreap { root: *right_node }; // now, fix priorities let mut priorities: Vec<Priority> = std::iter::repeat_with(random).take(leaves - 1).collect(); priorities.sort_unstable(); for_each_node_breadth_first(&mut treap.root, |node| match node { Node::Inner(priority, _, _) => *priority = priorities.pop().unwrap(), _ => (), }); debug_assert!(treap.is_valid()); treap } else { Default::default() } } } fn for_each_node_breadth_first<C, F: FnMut(&mut Node<C>)>(root: &mut Node<C>, mut op: F) { let mut remaining: std::collections::VecDeque<_> = std::iter::once(root).collect(); while let Some(node) = remaining.pop_front() { op(node); match node { Node::Inner(_, _, children) => remaining.extend(children.iter_mut().map(|b| &mut **b)), _ => (), } } } fn intersect_ranges(r1: &Range<usize>, r2: &Range<usize>) -> Range<usize> { r1.start.max(r2.start)..r1.end.min(r2.end) }
use std::net::SocketAddr; use rsocket_rust::async_trait; use rsocket_rust::{error::RSocketError, transport::ServerTransport, Result}; use tokio::net::TcpListener; use crate::{client::TcpClientTransport, misc::parse_tcp_addr}; #[derive(Debug)] pub struct TcpServerTransport { addr: SocketAddr, listener: Option<TcpListener>, } impl TcpServerTransport { fn new(addr: SocketAddr) -> TcpServerTransport { TcpServerTransport { addr, listener: None, } } } #[async_trait] impl ServerTransport for TcpServerTransport { type Item = TcpClientTransport; async fn start(&mut self) -> Result<()> { if self.listener.is_some() { return Ok(()); } match TcpListener::bind(self.addr).await { Ok(listener) => { self.listener = Some(listener); debug!("listening on: {}", &self.addr); Ok(()) } Err(e) => Err(RSocketError::IO(e).into()), } } async fn next(&mut self) -> Option<Result<Self::Item>> { match self.listener.as_mut() { Some(listener) => match listener.accept().await { Ok((socket, _)) => Some(Ok(TcpClientTransport::from(socket))), Err(e) => Some(Err(RSocketError::IO(e).into())), }, None => None, } } } impl From<SocketAddr> for TcpServerTransport { fn from(addr: SocketAddr) -> TcpServerTransport { TcpServerTransport::new(addr) } } impl From<String> for TcpServerTransport { fn from(addr: String) -> TcpServerTransport { TcpServerTransport::new(parse_tcp_addr(addr).parse().unwrap()) } } impl From<&str> for TcpServerTransport { fn from(addr: &str) -> TcpServerTransport { TcpServerTransport::new(parse_tcp_addr(addr).parse().unwrap()) } }
use dialoguer::{theme::ColorfulTheme, Checkboxes}; use parser::Parser; use lexer::Lexer; use parser::Visitor; use super::printer::PrintVisitor; use super::prompt::{PromptOption, Prompt, PromptResult}; use errors::error_index::Error::UnexpectedEOF; #[derive(Default, Clone)] struct Options{ show_ast: bool, show_type_derivation: bool, emit_llvm_ir: bool } pub fn start(){ main_loop(); } fn main_loop() { let prompt = Prompt::new() .option(PromptOption::with_name("type") .short("t") .help("Displays the type of the expression provided ")) .option(PromptOption::with_name("options") .short("o") .help("Allows you to choose various options for the REPL environment")) .option(PromptOption::with_name("quit") .short("q") .help("Exits the REPL environment")); let mut options = Options::default(); options.show_ast = true; loop { match prompt.show() { PromptResult::Input(expr) => handle_expr(expr, &options), PromptResult::Command(ref c, _) if *c == "QUIT".to_string() => break, PromptResult::Command(c, rest) => handle_command(c, rest, &mut options), PromptResult::InvalidCommand(command) => () } } } fn handle_expr(expr: String, options: &Options){ let lexer = Lexer::new(expr.as_str()); let mut parser = Parser::new(lexer); let mut printer = PrintVisitor::new(); let result = parser.parse_toplevel_assignment() .or_else(|_| { parser.reset_lexer(); parser.parse_expr() }).and_then(|res|{ if parser.is_empty() { Result::Ok(res) } else { Result::Err(UnexpectedEOF) } }); match result { Ok(ast) => { if options.show_ast { printer.visit(&ast) } }, Err(e) => println!("Error parsing: {:?}",e) } } fn handle_command(command: String, rest: Option<String>, options: &mut Options){ match &*command { "HELP" => println!("help"), "TYPE" => println!("type"), "OPTIONS" => show_options(options), _ => println!("Other") } } fn show_options(options: &mut Options){ let checkboxes = &[ ("Show AST", options.show_ast), ("Show type derivation", options.show_type_derivation), ("Emit LLVM Ir", options.emit_llvm_ir) ]; *options = Options::default(); let selections = Checkboxes::with_theme(&ColorfulTheme::default()) .with_prompt("Options") .items_with_states(&checkboxes[..]) .interact() .unwrap(); { let handlers: &[Box<Fn(&mut Options)>] = &[ Box::new(|ops| ops.show_ast = true), Box::new(|ops| ops.show_type_derivation = true), Box::new(|ops| ops.emit_llvm_ir = true) ]; if !selections.is_empty() { for selection in selections { handlers[selection](options); } } } }
fn main() -> Result<(), ()> { let date_txt: &'static str = "2019-03-21 09:50"; println!("This ifinterp implementation in Rust is a stub as of {}", date_txt); Ok(()) }
use std::fs::read_to_string; use std::{iter, thread, time}; use std::fmt::{Debug, Formatter, Error}; use itertools::Itertools; const INPUT_FILE: &str = "data/day_18.txt"; const TEST_GRID: &str = r#".#.#.# ...##. #....# ..#... #.#..# ####.."#; #[derive(Clone)] struct Grid { data: Vec<bool>, width: usize, height: usize, stuck_lights: Vec<(i32, i32)>, } impl Grid { fn new(width: usize, height: usize, stuck_lights: Vec<(i32, i32)>) -> Self { let mut data: Vec<bool> = vec![]; data.extend(iter::repeat(false).take(width * height)); Self { data, width, height, stuck_lights, } } fn from_str(s: &str, stuck_lights: Vec<(i32, i32)>) -> Self { let lines: Vec<_> = s.lines().collect(); Self { data: lines.join("").chars().map(|c| c == '#').collect(), width: lines[0].len(), height: lines.len(), stuck_lights, } } fn in_grid(&self, x: i32, y: i32) -> bool { x >= 0 && y >= 0 && x < self.width as i32 && y < self.height as i32 } fn get(&self, x: i32, y: i32) -> Option<bool> { if !self.in_grid(x, y) { return None; } if self.stuck_lights.contains(&(x, y)) { return Some(true); } let pos = (x + (y * self.width as i32)) as usize; self.data.get(pos).cloned() } fn set(&mut self, x: i32, y: i32, value: bool) { let pos = (x + y * self.width as i32) as usize; if let Some(cell) = self.data.get_mut(pos) { if self.stuck_lights.contains(&(x, y)) { *cell = true; } else { *cell = value; } } } fn neighbours_on(&self, x: i32, y: i32) -> usize { vec![ self.get(x - 1, y - 1), self.get(x, y - 1), self.get(x + 1, y - 1), self.get(x - 1, y), self.get(x + 1, y), self.get(x - 1, y + 1), self.get(x, y + 1), self.get(x + 1, y + 1), ].into_iter().filter_map(|n| n).filter(|n| n.to_owned()).count() } fn step(&mut self) { let mut new_grid = Grid::new(self.width, self.height, self.stuck_lights.clone()); for y in 0..self.height { for x in 0..self.width { let x = x as i32; let y = y as i32; let neighbours_on = self.neighbours_on(x, y); if self.get(x, y).unwrap() { new_grid.set(x, y, neighbours_on == 2 || neighbours_on == 3); } else { new_grid.set(x, y, neighbours_on == 3); } } } *self = new_grid; } fn on_lights(&self) -> usize { self.data.iter().filter(|c| c == &&true).count() } } impl Debug for Grid { fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error> { let lines = self.data .chunks(self.width) .map(|chunk| chunk.iter().cloned().map(|c| if c { "#" } else { "." }).collect::<String>()) .join("\n"); write!(f, "{}", lines) } } pub fn run() -> String { let input = read_to_string(INPUT_FILE).unwrap(); let mut grid = Grid::from_str(&input, vec![]); for _ in 0..100 { grid.step(); } grid.on_lights().to_string() } pub fn run_pt2() -> String { let input = read_to_string(INPUT_FILE).unwrap(); let mut grid = Grid::from_str(&input, vec![ (0, 0), (99, 0), (0, 99), (99, 99), ]); for _ in 0..100 { grid.step(); } grid.on_lights().to_string() } #[test] fn test_run() { let mut grid = Grid::from_str(TEST_GRID, vec![]); for _ in 0..4 { grid.step(); } assert_eq!(grid.on_lights(), 4); } #[test] fn test_run_pt2() { let mut grid = Grid::from_str(TEST_GRID, vec![ (0, 0), (5, 0), (0, 5), (5, 5), ]); for _ in 0..5 { grid.step(); } assert_eq!(grid.on_lights(), 17); } #[test] fn animated_simulation() { let input = read_to_string(INPUT_FILE).unwrap(); let mut grid = Grid::from_str(&input, vec![]); loop { grid.step(); thread::sleep(time::Duration::from_millis(50)); print!("{}[2J", 27 as char); println!("{:?}", grid); } }
/*! WORM directory abstraction. */ #[cfg(feature = "mmap")] mod mmap_directory; mod directory; mod managed_directory; mod ram_directory; mod read_only_source; mod shared_vec_slice; /// Errors specific to the directory module. pub mod error; use std::io::{BufWriter, Seek, Write}; pub use self::directory::{Directory, DirectoryClone}; pub use self::ram_directory::RAMDirectory; pub use self::read_only_source::ReadOnlySource; #[cfg(feature = "mmap")] pub use self::mmap_directory::MmapDirectory; pub(crate) use self::managed_directory::ManagedDirectory; /// Synonym of Seek + Write pub trait SeekableWrite: Seek + Write {} impl<T: Seek + Write> SeekableWrite for T {} /// Write object for Directory. /// /// `WritePtr` are required to implement both Write /// and Seek. pub type WritePtr = BufWriter<Box<SeekableWrite>>; #[cfg(test)] mod tests { use super::*; use std::io::{Seek, SeekFrom, Write}; use std::path::Path; lazy_static! { static ref TEST_PATH: &'static Path = Path::new("some_path_for_test"); } #[test] fn test_ram_directory() { let mut ram_directory = RAMDirectory::create(); test_directory(&mut ram_directory); } #[test] #[cfg(feature = "mmap")] fn test_mmap_directory() { let mut mmap_directory = MmapDirectory::create_from_tempdir().unwrap(); test_directory(&mut mmap_directory); } #[test] #[should_panic] fn ram_directory_panics_if_flush_forgotten() { let mut ram_directory = RAMDirectory::create(); let mut write_file = ram_directory.open_write(*TEST_PATH).unwrap(); assert!(write_file.write_all(&[4]).is_ok()); } fn test_simple(directory: &mut Directory) { { { let mut write_file = directory.open_write(*TEST_PATH).unwrap(); assert!(directory.exists(*TEST_PATH)); write_file.write_all(&[4]).unwrap(); write_file.write_all(&[3]).unwrap(); write_file.write_all(&[7, 3, 5]).unwrap(); write_file.flush().unwrap(); } let read_file = directory.open_read(*TEST_PATH).unwrap(); let data: &[u8] = &*read_file; assert_eq!(data, &[4u8, 3u8, 7u8, 3u8, 5u8]); } assert!(directory.delete(*TEST_PATH).is_ok()); assert!(!directory.exists(*TEST_PATH)); } fn test_seek(directory: &mut Directory) { { { let mut write_file = directory.open_write(*TEST_PATH).unwrap(); write_file.write_all(&[4, 3, 7, 3, 5]).unwrap(); write_file.seek(SeekFrom::Start(0)).unwrap(); write_file.write_all(&[3, 1]).unwrap(); write_file.flush().unwrap(); } let read_file = directory.open_read(*TEST_PATH).unwrap(); let data: &[u8] = &*read_file; assert_eq!(data, &[3u8, 1u8, 7u8, 3u8, 5u8]); } assert!(directory.delete(*TEST_PATH).is_ok()); } fn test_rewrite_forbidden(directory: &mut Directory) { { directory.open_write(*TEST_PATH).unwrap(); assert!(directory.exists(*TEST_PATH)); } { assert!(directory.open_write(*TEST_PATH).is_err()); } assert!(directory.delete(*TEST_PATH).is_ok()); } fn test_write_create_the_file(directory: &mut Directory) { { assert!(directory.open_read(*TEST_PATH).is_err()); let _w = directory.open_write(*TEST_PATH).unwrap(); assert!(directory.exists(*TEST_PATH)); assert!(directory.open_read(*TEST_PATH).is_ok()); assert!(directory.delete(*TEST_PATH).is_ok()); } } fn test_directory_delete(directory: &mut Directory) { assert!(directory.open_read(*TEST_PATH).is_err()); let mut write_file = directory.open_write(*TEST_PATH).unwrap(); write_file.write_all(&[1, 2, 3, 4]).unwrap(); write_file.flush().unwrap(); { let read_handle = directory.open_read(*TEST_PATH).unwrap(); { assert_eq!(&*read_handle, &[1u8, 2u8, 3u8, 4u8]); // Mapped files can't be deleted on Windows if !cfg!(windows) { assert!(directory.delete(*TEST_PATH).is_ok()); assert_eq!(&*read_handle, &[1u8, 2u8, 3u8, 4u8]); } assert!(directory.delete(Path::new("SomeOtherPath")).is_err()); } } if cfg!(windows) { assert!(directory.delete(*TEST_PATH).is_ok()); } assert!(directory.open_read(*TEST_PATH).is_err()); assert!(directory.delete(*TEST_PATH).is_err()); } fn test_directory(directory: &mut Directory) { test_simple(directory); test_seek(directory); test_rewrite_forbidden(directory); test_write_create_the_file(directory); test_directory_delete(directory); } }
#![no_std] #![no_main] extern crate atsamd21_hal as hal; extern crate panic_abort; extern crate cortex_m_rt; pub use hal::atsamd21e18a::*; use hal::prelude::*; pub use hal::*; use cortex_m_rt::entry; #[entry] fn main() -> ! { let mut peripherals = Peripherals::take().unwrap(); let mut pins = peripherals.PORT.split(); // Trinket 13 let mut red_led = pins.pa10.into_open_drain_output(&mut pins.port); let mut clocks = clock::GenericClockController::with_internal_32kosc( peripherals.GCLK, &mut peripherals.PM, &mut peripherals.SYSCTRL, &mut peripherals.NVMCTRL, ); let core = CorePeripherals::take().unwrap(); let mut delay = delay::Delay::new(core.SYST, &mut clocks); loop { delay.delay_ms(300u16); red_led.set_high(); delay.delay_ms(300u16); red_led.set_low(); } }
#[doc = "Register `SR2` reader"] pub type R = crate::R<SR2_SPEC>; #[doc = "Field `MSL` reader - Master/slave"] pub type MSL_R = crate::BitReader; #[doc = "Field `BUSY` reader - Bus busy"] pub type BUSY_R = crate::BitReader; #[doc = "Field `TRA` reader - Transmitter/receiver"] pub type TRA_R = crate::BitReader; #[doc = "Field `GENCALL` reader - General call address (Slave mode)"] pub type GENCALL_R = crate::BitReader; #[doc = "Field `SMBDEFAULT` reader - SMBus device default address (Slave mode)"] pub type SMBDEFAULT_R = crate::BitReader; #[doc = "Field `SMBHOST` reader - SMBus host header (Slave mode)"] pub type SMBHOST_R = crate::BitReader; #[doc = "Field `DUALF` reader - Dual flag (Slave mode)"] pub type DUALF_R = crate::BitReader; #[doc = "Field `PEC` reader - acket error checking register"] pub type PEC_R = crate::FieldReader; impl R { #[doc = "Bit 0 - Master/slave"] #[inline(always)] pub fn msl(&self) -> MSL_R { MSL_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Bus busy"] #[inline(always)] pub fn busy(&self) -> BUSY_R { BUSY_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Transmitter/receiver"] #[inline(always)] pub fn tra(&self) -> TRA_R { TRA_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 4 - General call address (Slave mode)"] #[inline(always)] pub fn gencall(&self) -> GENCALL_R { GENCALL_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - SMBus device default address (Slave mode)"] #[inline(always)] pub fn smbdefault(&self) -> SMBDEFAULT_R { SMBDEFAULT_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - SMBus host header (Slave mode)"] #[inline(always)] pub fn smbhost(&self) -> SMBHOST_R { SMBHOST_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Dual flag (Slave mode)"] #[inline(always)] pub fn dualf(&self) -> DUALF_R { DUALF_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bits 8:15 - acket error checking register"] #[inline(always)] pub fn pec(&self) -> PEC_R { PEC_R::new(((self.bits >> 8) & 0xff) as u8) } } #[doc = "SR2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr2::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SR2_SPEC; impl crate::RegisterSpec for SR2_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`sr2::R`](R) reader structure"] impl crate::Readable for SR2_SPEC {} #[doc = "`reset()` method sets SR2 to value 0"] impl crate::Resettable for SR2_SPEC { const RESET_VALUE: Self::Ux = 0; }
use wasm_bindgen::prelude::*; use wasm_bindgen::JsCast; use wasm_bindgen_futures; use wasm_bindgen_futures::JsFuture; use web_sys::Request; use web_sys::RequestInit; use web_sys::RequestMode; use web_sys::Response; pub async fn get(address: &str) -> Result<String, JsValue> { let mut opts = RequestInit::new(); opts.method("GET"); opts.mode(RequestMode::Cors); let request = Request::new_with_str_and_init(&address, &opts)?; request.headers().set("Accept", "text/plain")?; let window = web_sys::window().unwrap(); let response_value = JsFuture::from(window.fetch_with_request(&request)).await?; let response: Response = response_value.dyn_into().unwrap(); let text = JsFuture::from(response.text()?).await?; let text = text.as_string().unwrap(); Ok(text) }
use redoxfs::{archive_at, DiskSparse, FileSystem, TreePtr, BLOCK_SIZE}; use std::path::{Path, PathBuf}; use std::process::{self, Command}; use std::time::{SystemTime, UNIX_EPOCH}; use std::{fs, io}; use crate::redoxfs::RedoxFs; use crate::{installed, redoxer_dir, status_error, syscall_error, target, toolchain}; const BOOTLOADER_SIZE: usize = 2 * 1024 * 1024; const DISK_SIZE: u64 = 1024 * 1024 * 1024; static BASE_TOML: &'static str = include_str!("../res/base.toml"); static GUI_TOML: &'static str = include_str!("../res/gui.toml"); /// Redoxer is used for testing out apps in redox OS environment. /// For this reason no live image is required const INSTALL_LIVE_IMAGE: bool = false; fn bootloader() -> io::Result<PathBuf> { let bootloader_bin = redoxer_dir().join("bootloader.bin"); if !bootloader_bin.is_file() { eprintln!("redoxer: building bootloader"); let bootloader_dir = redoxer_dir().join("bootloader"); if bootloader_dir.is_dir() { fs::remove_dir_all(&bootloader_dir)?; } fs::create_dir_all(&bootloader_dir)?; let mut config = redox_installer::Config::default(); config .packages .insert("bootloader".to_string(), Default::default()); let cookbook: Option<&str> = None; redox_installer::install(config, &bootloader_dir, cookbook, INSTALL_LIVE_IMAGE) .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{}", err)))?; fs::rename( &bootloader_dir.join("boot/bootloader.bios"), &bootloader_bin, )?; } Ok(bootloader_bin) } fn base(bootloader_bin: &Path, gui: bool, fuse: bool) -> io::Result<PathBuf> { let name = if gui { "gui" } else { "base" }; let ext = if fuse { "bin" } else { "tar" }; let base_bin = redoxer_dir().join(format!("{}.{}", name, ext)); if !base_bin.is_file() { eprintln!("redoxer: building {}", name); let base_dir = redoxer_dir().join(name); if base_dir.is_dir() { fs::remove_dir_all(&base_dir)?; } fs::create_dir_all(&base_dir)?; let base_partial = redoxer_dir().join(format!("{}.{}.partial", name, ext)); if fuse { let disk = DiskSparse::create(&base_partial, DISK_SIZE).map_err(syscall_error)?; let bootloader = { let mut bootloader = fs::read(bootloader_bin)?.to_vec(); // Pad bootloader to 2 MiB while bootloader.len() < BOOTLOADER_SIZE { bootloader.push(0); } bootloader }; let ctime = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); let fs = FileSystem::create_reserved( disk, None, &bootloader, ctime.as_secs(), ctime.subsec_nanos(), ) .map_err(syscall_error)?; fs.disk.file.set_len(DISK_SIZE)?; } { let redoxfs_opt = if fuse { Some(RedoxFs::new(&base_partial, &base_dir)?) } else { None }; let config: redox_installer::Config = toml::from_str(if gui { GUI_TOML } else { BASE_TOML }) .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{}", err)))?; let cookbook: Option<&str> = None; redox_installer::install(config, &base_dir, cookbook, INSTALL_LIVE_IMAGE) .map_err(|err| io::Error::new(io::ErrorKind::Other, format!("{}", err)))?; if let Some(mut redoxfs) = redoxfs_opt { redoxfs.unmount()?; } } if !fuse { Command::new("tar") .arg("-c") .arg("-p") .arg("-f") .arg(&base_partial) .arg("-C") .arg(&base_dir) .arg(".") .status() .and_then(status_error)?; } fs::rename(&base_partial, &base_bin)?; } Ok(base_bin) } fn archive_free_space( disk_path: &Path, folder_path: &Path, bootloader_path: &Path, free_space: u64, ) -> io::Result<()> { let disk = DiskSparse::create(&disk_path, free_space).map_err(syscall_error)?; let bootloader = { let mut bootloader = fs::read(bootloader_path)?.to_vec(); // Pad bootloader to 2 MiB while bootloader.len() < BOOTLOADER_SIZE { bootloader.push(0); } bootloader }; let ctime = SystemTime::now().duration_since(UNIX_EPOCH).unwrap(); let mut fs = FileSystem::create_reserved( disk, None, &bootloader, ctime.as_secs(), ctime.subsec_nanos(), ) .map_err(syscall_error)?; let end_block = fs .tx(|tx| { // Archive_at root node archive_at(tx, folder_path, TreePtr::root()) .map_err(|err| syscall::Error::new(err.raw_os_error().unwrap()))?; // Squash alloc log tx.sync(true)?; let mut end_block = tx.header.size() / BLOCK_SIZE; /* TODO: Cut off any free blocks at the end of the filesystem let mut end_changed = true; while end_changed { end_changed = false; let allocator = fs.allocator(); let levels = allocator.levels(); for level in 0..levels.len() { let level_size = 1 << level; for &block in levels[level].iter() { if block < end_block && block + level_size >= end_block { end_block = block; end_changed = true; } } } } */ // Update header tx.header.size = (end_block * BLOCK_SIZE).into(); tx.header_changed = true; tx.sync(false)?; Ok(end_block) }) .map_err(syscall_error)?; let size = (fs.block + end_block) * BLOCK_SIZE; fs.disk.file.set_len(size)?; Ok(()) } fn inner( arguments: &[String], folder_opt: Option<String>, gui: bool, output_opt: Option<String>, ) -> io::Result<i32> { let kvm = Path::new("/dev/kvm").exists(); if !installed("qemu-system-x86_64")? { eprintln!("redoxer: qemu-system-x86 not found, please install before continuing"); process::exit(1); } let fuse = Path::new("/dev/fuse").exists(); if fuse { if !installed("fusermount")? { eprintln!("redoxer: fuse not found, please install before continuing"); process::exit(1); } } else if !installed("tar")? { eprintln!("redoxer: tar not found, please install before continuing"); process::exit(1); } let toolchain_dir = toolchain()?; let bootloader_bin = bootloader()?; let base_bin = base(&bootloader_bin, gui, fuse)?; let tempdir = tempfile::tempdir()?; let code = { let redoxer_bin = tempdir.path().join("redoxer.bin"); if fuse { Command::new("cp") .arg(&base_bin) .arg(&redoxer_bin) .status() .and_then(status_error)?; } let redoxer_dir = tempdir.path().join("redoxer"); fs::create_dir_all(&redoxer_dir)?; { let redoxfs_opt = if fuse { Some(RedoxFs::new(&redoxer_bin, &redoxer_dir)?) } else { Command::new("tar") .arg("-x") .arg("-p") .arg("--same-owner") .arg("-f") .arg(&base_bin) .arg("-C") .arg(&redoxer_dir) .arg(".") .status() .and_then(status_error)?; None }; let toolchain_lib_dir = toolchain_dir.join(target()).join("lib"); let lib_dir = redoxer_dir.join("lib"); for obj in &[ "ld64.so.1", "libc.so", "libgcc_s.so", "libgcc_s.so.1", "libstdc++.so", "libstdc++.so.6", "libstdc++.so.6.0.25", ] { eprintln!("redoxer: copying '{}' to '/lib'", obj); Command::new("rsync") .arg("--archive") .arg(&toolchain_lib_dir.join(obj)) .arg(&lib_dir) .status() .and_then(status_error)?; } let mut redoxerd_config = String::new(); for arg in arguments.iter() { // Replace absolute path to folder with /root in command name // TODO: make this activated by a flag if let Some(ref folder) = folder_opt { let folder_canonical_path = fs::canonicalize(&folder)?; let folder_canonical = folder_canonical_path.to_str().ok_or(io::Error::new( io::ErrorKind::Other, "folder path is not valid UTF-8", ))?; if arg.starts_with(&folder_canonical) { let arg_replace = arg.replace(folder_canonical, "/root"); eprintln!( "redoxer: replacing '{}' with '{}' in arguments", arg, arg_replace ); redoxerd_config.push_str(&arg_replace); redoxerd_config.push('\n'); continue; } } redoxerd_config.push_str(&arg); redoxerd_config.push('\n'); } fs::write(redoxer_dir.join("etc/redoxerd"), redoxerd_config)?; if let Some(ref folder) = folder_opt { eprintln!("redoxer: copying '{}' to '/root'", folder); let root_dir = redoxer_dir.join("root"); Command::new("rsync") .arg("--archive") .arg(&folder) .arg(&root_dir) .status() .and_then(status_error)?; } if let Some(mut redoxfs) = redoxfs_opt { redoxfs.unmount()?; } } if !fuse { archive_free_space( &redoxer_bin, &redoxer_dir, &bootloader_bin, DISK_SIZE, )?; } let redoxer_log = tempdir.path().join("redoxer.log"); let mut command = Command::new("qemu-system-x86_64"); command .arg("-cpu") .arg("max") .arg("-machine") .arg("q35") .arg("-m") .arg("2048") .arg("-smp") .arg("4") .arg("-serial") .arg("mon:stdio") .arg("-chardev") .arg(format!("file,id=log,path={}", redoxer_log.display())) .arg("-device") .arg("isa-debugcon,chardev=log") .arg("-device") .arg("isa-debug-exit") .arg("-netdev") .arg("user,id=net0") .arg("-device") .arg("e1000,netdev=net0") .arg("-drive") .arg(format!("file={},format=raw", redoxer_bin.display())); if kvm { command.arg("-accel").arg("kvm"); } if !gui { command.arg("-nographic").arg("-vga").arg("none"); } let status = command.status()?; eprintln!(); let code = match status.code() { Some(51) => { eprintln!("## redoxer (success) ##"); 0 } Some(53) => { eprintln!("## redoxer (failure) ##"); 1 } _ => { eprintln!("## redoxer (failure, qemu exit status {:?} ##", status); 2 } }; if let Some(output) = output_opt { fs::copy(&redoxer_log, output)?; } else { print!("{}", fs::read_to_string(&redoxer_log)?); } code }; tempdir.close()?; Ok(code) } fn usage() { eprintln!("redoxer exec [-f|--folder folder] [-g|--gui] [-h|--help] [-o|--output file] [--] <command> [arguments]..."); process::exit(1); } pub fn main(args: &[String]) { // Matching flags let mut matching = true; // Folder to copy let mut folder_opt = None; // Run with GUI let mut gui = false; // File to put command output into let mut output_opt = None; // Arguments to pass to command let mut arguments = Vec::new(); let mut args = args.iter().cloned().skip(2); while let Some(arg) = args.next() { match arg.as_str() { "-f" | "--folder" if matching => match args.next() { Some(folder) => { folder_opt = Some(folder); } None => { usage(); } }, "-g" | "--gui" if matching => { gui = true; } // TODO: argument for replacing the folder path with /root when found in arguments "-h" | "--help" if matching => { usage(); } "-o" | "--output" if matching => match args.next() { Some(output) => { output_opt = Some(output); } None => { usage(); } }, // TODO: "-p" | "--package" "--" if matching => { matching = false; } _ => { matching = false; arguments.push(arg); } } } if arguments.is_empty() { usage(); } match inner(&arguments, folder_opt, gui, output_opt) { Ok(code) => { process::exit(code); } Err(err) => { eprintln!("redoxer exec: {}", err); process::exit(3); } } }
#![windows_subsystem = "windows"] extern crate iui; extern crate romhack_backend; use iui::controls::{Button, HorizontalSeparator, Label, Spacer, VerticalBox}; use iui::prelude::*; use romhack_backend::{apply_patch, DontPrint}; use std::cell::RefCell; use std::path::PathBuf; use std::rc::Rc; struct State { iso: Option<PathBuf>, patch: Option<PathBuf>, ui: UI, apply: Button, } impl State { fn update(&mut self) { if self.iso.is_some() && self.patch.is_some() { self.ui.set_enabled(self.apply.clone(), true); } } } fn main() { let mut ui = UI::init().unwrap(); let mut window = Window::new(&ui, "GameCube ISO Patcher", 300, 100, WindowType::NoMenubar); let mut vbox = VerticalBox::new(&ui); vbox.set_padded(&ui, true); let mut apply_button = Button::new(&ui, "Apply"); ui.set_enabled(apply_button.clone(), false); let state = Rc::new(RefCell::new(State { iso: None, patch: None, ui: ui.clone(), apply: apply_button.clone(), })); let patch_label = Label::new(&ui, "No Patch selected"); let mut patch_button = Button::new(&ui, "Open Patch"); patch_button.on_clicked(&ui, { let ui = ui.clone(); let mut label = patch_label.clone(); let window = window.clone(); let state = state.clone(); move |_btn| { if let Some(path) = window.open_file(&ui) { label.set_text( &ui, &path .file_name() .map(|n| n.to_string_lossy()) .unwrap_or_default(), ); let mut state = state.borrow_mut(); state.patch = Some(path); state.update(); } } }); let iso_label = Label::new(&ui, "No ISO selected"); let mut iso_button = Button::new(&ui, "Open ISO"); iso_button.on_clicked(&ui, { let ui = ui.clone(); let mut label = iso_label.clone(); let window = window.clone(); let state = state.clone(); move |_btn| { if let Some(path) = window.open_file(&ui) { label.set_text( &ui, &path .file_name() .map(|n| n.to_string_lossy()) .unwrap_or_default(), ); let mut state = state.borrow_mut(); state.iso = Some(path); state.update(); } } }); apply_button.on_clicked(&ui, { let ui = ui.clone(); let window = window.clone(); let state = state.clone(); move |_btn| { let state = state.borrow(); if let (Some(patch), Some(iso)) = (&state.patch, &state.iso) { if let Some(output) = window.save_file(&ui) { apply_patch(&DontPrint, patch.to_owned(), iso.to_owned(), output).unwrap(); } } } }); vbox.append(&ui, patch_label, LayoutStrategy::Compact); vbox.append(&ui, patch_button, LayoutStrategy::Compact); vbox.append(&ui, iso_label, LayoutStrategy::Compact); vbox.append(&ui, iso_button, LayoutStrategy::Compact); vbox.append(&ui, Spacer::new(&ui), LayoutStrategy::Compact); vbox.append(&ui, HorizontalSeparator::new(&ui), LayoutStrategy::Compact); vbox.append(&ui, Spacer::new(&ui), LayoutStrategy::Compact); vbox.append(&ui, apply_button, LayoutStrategy::Compact); window.set_child(&ui, vbox); window.show(&ui); ui.main(); }
#[macro_use] extern crate log; extern crate env_logger; extern crate rustygear; extern crate rustygeard; use rustygeard::server::GearmanServer; fn main() { env_logger::init(); info!("Binding to 0.0.0.0:4730"); let address = "0.0.0.0:4730".parse().unwrap(); GearmanServer::run(address); }
//mod prefix_read; mod doc; pub mod error; mod prefix; use error::*; use skorm_curie::CurieStore; use skorm_store::RdfStore; use std::ffi::OsStr; use std::fs::File; use std::path::Path; use std::path::PathBuf; use tracing::debug; const PREFIX_FILE_NAME: &'static str = "_prefix.ttl"; pub struct Walker<'a> { path: &'a Path, root: &'a str, dirs: &'a [&'a str], } #[derive(Clone)] struct WalkerPath { path: PathBuf, rel: String, } struct WalkerDoc { dir: WalkerPath, doc: WalkerPath, } impl WalkerPath { fn new(path: PathBuf, rel: String) -> Self { Self { path, rel } } fn join(&self, path: impl AsRef<Path>) -> Self { let path = path.as_ref(); Self { path: self.path.join(path), rel: if self.rel.len() == 0 { path.display().to_string() } else { format!("{}/{}", self.rel, path.display()) }, } } } impl<'a> Walker<'a> { pub fn new(path: &'a Path, root: &'a str, dirs: &'a [&'a str]) -> Self { Self { path, root, dirs } } fn dirs(&self) -> Result<impl Iterator<Item = WalkerPath>> { let mut result = Vec::new(); result.push(WalkerPath::new(self.path.to_owned(), String::new())); for dir_name in self.dirs { let dir = result[0].join(dir_name); if dir.path.is_dir() { recursive_add_dirs(&mut result, dir)?; } } Ok(result.into_iter()) } fn prefix_docs(&self) -> Result<impl Iterator<Item = WalkerDoc>> { let mut result = Vec::new(); for dir in self.dirs()? { let prefix_file = dir.join(PREFIX_FILE_NAME); if !prefix_file.path.is_file() { debug!( file = %prefix_file.path.display(), "Creating file {}.", prefix_file.path.display()); File::create(&prefix_file.path)?; } result.push(WalkerDoc { dir, doc: prefix_file, }); } Ok(result.into_iter()) } fn docs(&self) -> Result<impl Iterator<Item = WalkerDoc>> { let mut result = Vec::new(); for dir in self.dirs()? { for entry in dir.path.read_dir()? { let entry = entry?; if entry.file_name() == PREFIX_FILE_NAME { continue; } let sub_path = dir.join(entry.file_name()); if !sub_path.path.is_file() { continue; } match entry.path().extension().and_then(OsStr::to_str) { Some("ttl") => (), _ => continue, }; result.push(WalkerDoc { dir: dir.clone(), doc: sub_path, }); } } Ok(result.into_iter()) } fn build_prefix_store(&self) -> Result<CurieStore> { prefix::build_prefix_store(self) } pub fn build_rdf_store(&self) -> Result<RdfStore> { doc::build_rdf_store(self) } } fn recursive_add_dirs(vec: &mut Vec<WalkerPath>, dir: WalkerPath) -> Result<()> { vec.push(dir); for entry in vec[vec.len() - 1].path.read_dir()? { let entry = entry?; let sub_path = vec[vec.len() - 1].join(entry.file_name()); if sub_path.path.is_dir() { recursive_add_dirs(vec, sub_path)?; } } Ok(()) }
#[macro_export] macro_rules! create_dep { ($obj:expr, $container:expr) => {{ $container.add($obj).unwrap() }}; ($obj:expr, $container:expr, $($t:tt)+) => {{ $container.add($obj).unwrap()$($t)+ }}; } #[macro_export] macro_rules! inject_dep { ($struct:ident, $container:expr) => {{ unsafe { let ptr = $container.get::<$struct>().unwrap() as *const dyn DependencyInjectTrait; let ptr = ptr as *mut dyn DependencyInjectTrait; let s = &mut *ptr; s.inject($container); } }}; } #[cfg(test)] mod tests { use std::sync::Arc; use crate::di::{DependencyInjectTrait, DIContainer, DIContainerTrait}; #[derive(Debug)] struct DIStruct; #[derive(Debug)] struct DIAwareStruct(Option<Arc<DIContainer>>); impl DIStruct { fn new() -> Self { Self {} } } impl DIAwareStruct { fn new() -> Self { Self { 0: None } } } impl DependencyInjectTrait for DIAwareStruct { fn inject(&mut self, container: Arc<DIContainer>) { self.0 = Some(container.clone()) } } #[test] fn test_create_dep() { let mut container = DIContainer::new(); // add obj to DI let obj_ptr = { let obj = create_dep!(DIStruct::new(), container); obj as *const DIStruct }; // get obj from DI let container_arc = container.init().unwrap(); let injected_obj = container_arc.get::<DIStruct>().unwrap(); assert_eq!(obj_ptr, injected_obj as *const DIStruct); } #[test] fn test_inject_dep() { let mut container = DIContainer::new(); // add obj to DI create_dep!(DIAwareStruct::new(), container); // inject DI container to aware objects let container_arc = container.init().unwrap(); let container_ptr = container_arc.as_ref() as *const DIContainer; inject_dep!(DIAwareStruct, container_arc.clone()); // get container from aware objects let injected_obj = container_arc.get::<DIAwareStruct>().unwrap(); let injected_container = injected_obj.0.as_ref().unwrap().as_ref(); assert_eq!(container_ptr, injected_container as *const DIContainer); } }
// https://projecteuler.net/problem=19 /* You are given the following information, but you may prefer to do some research for yourself. - 1 Jan 1900 was a Monday. - Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. - A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? */ fn main() { let start_time = std::time::Instant::now(); let sol = solve2(); let elapsed = start_time.elapsed().as_micros(); println!("\nSolution: {}", sol); println!("Elasped time: {} us", elapsed); } #[allow(dead_code)] fn solve1() -> u32 { let mut rv = 0; let mut day = 365; for year in 1901..2001 { // January if is_sunday(day) { rv += 1; } day += 31; // February if is_sunday(day) { rv += 1; } day += 28; if is_leap_year(year) { day += 1; } // March if is_sunday(day) { rv += 1; } day += 31; // April if is_sunday(day) { rv += 1; } day += 30; // May if is_sunday(day) { rv += 1; } day += 31; // June if is_sunday(day) { rv += 1; } day += 30; // July if is_sunday(day) { rv += 1; } day += 31; // August if is_sunday(day) { rv += 1; } day += 31; // September if is_sunday(day) { rv += 1; } day += 30; // October if is_sunday(day) { rv += 1; } day += 31; // November if is_sunday(day) { rv += 1; } day += 30; // December if is_sunday(day) { rv += 1; } day += 31; } return rv; } // more compact, but much less efficient #[allow(dead_code)] fn solve2() -> u32 { let mut rv = 0; let mut day = 365; for year in 1901..2001 { for month in 1..=12 { if is_sunday(day) { rv += 1; } day += match month { 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31, 4 | 6 | 9 | 11 => 30, 2 => if is_leap_year(year) { 29 } else { 28 }, n => panic!("Somehow got month number{}", n), }; } } return rv; } fn is_leap_year(year: u32) -> bool { if year % 4 != 0 { return false; } if year % 100 == 0 { return year % 400 == 0; } return true; } fn is_sunday(day: u32) -> bool { day % 7 == 6 }
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under both the MIT license found in the * LICENSE-MIT file in the root directory of this source tree and the Apache * License, Version 2.0 found in the LICENSE-APACHE file in the root directory * of this source tree. */ #[cfg(test)] mod tests; use byteorder::{BigEndian, ByteOrder}; use bytes::{BufMut, Bytes, BytesMut}; use bytes_ext::BytesCompat; use bytes_old::BufMut as _; use std::io::{self, Cursor}; use tokio_codec::{Decoder as _, Framed}; use tokio_io::{AsyncRead, AsyncWrite}; use tokio_proto::pipeline::{ClientProto, ServerProto}; use tokio_util::codec::{Decoder, Encoder}; pub struct FramedTransport; impl<T> ClientProto<T> for FramedTransport where T: AsyncRead + AsyncWrite + 'static, { type Request = Bytes; type Response = Cursor<bytes_old::Bytes>; type Transport = Framed<T, FramedTransportCodec>; type BindTransport = Result<Self::Transport, io::Error>; fn bind_transport(&self, io: T) -> Self::BindTransport { Ok(FramedTransportCodec.framed(io)) } } impl<T> ServerProto<T> for FramedTransport where T: AsyncRead + AsyncWrite + 'static, { type Request = Cursor<bytes_old::Bytes>; type Response = Bytes; type Transport = Framed<T, FramedTransportCodec>; type BindTransport = Result<Self::Transport, io::Error>; fn bind_transport(&self, io: T) -> Self::BindTransport { Ok(FramedTransportCodec.framed(io)) } } impl Encoder for FramedTransport { type Item = Bytes; type Error = io::Error; fn encode(&mut self, item: Self::Item, dst: &mut BytesMut) -> Result<(), Self::Error> { dst.reserve(4 + item.len()); dst.put_u32(item.len() as u32); dst.put(item); Ok(()) } } impl Decoder for FramedTransport { type Item = Cursor<Bytes>; type Error = io::Error; fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { // Wait for at least a frame header if src.len() < 4 { return Ok(None); } // Peek at first 4 bytes, don't advance src buffer let len = BigEndian::read_u32(&src[..4]) as usize; // Make sure we have all the bytes we were promised if src.len() < 4 + len { return Ok(None); } // Drain 4 bytes from src let _ = src.split_to(4).as_ref(); // Take len bytes, advancing src let res = src.split_to(len); Ok(Some(Cursor::new(res.freeze()))) } } pub struct FramedTransportCodec; impl tokio_codec::Encoder for FramedTransportCodec { type Item = Bytes; type Error = io::Error; fn encode( &mut self, item: Self::Item, dst: &mut bytes_old::BytesMut, ) -> Result<(), Self::Error> { dst.reserve(4 + item.len()); dst.put_u32_be(item.len() as u32); dst.put(BytesCompat::new(item)); Ok(()) } } impl tokio_codec::Decoder for FramedTransportCodec { type Item = Cursor<bytes_old::Bytes>; type Error = io::Error; fn decode(&mut self, src: &mut bytes_old::BytesMut) -> Result<Option<Self::Item>, Self::Error> { // Wait for at least a frame header if src.len() < 4 { return Ok(None); } // Peek at first 4 bytes, don't advance src buffer let len = BigEndian::read_u32(&src[..4]) as usize; // Make sure we have all the bytes we were promised if src.len() < 4 + len { return Ok(None); } // Drain 4 bytes from src let _ = src.split_to(4).as_ref(); // Take len bytes, advancing src let res = src.split_to(len); Ok(Some(Cursor::new(res.freeze()))) } }
mod intcode; use std::collections::HashMap; use std::fs; use std::sync::mpsc; use std::{thread, time}; fn main() { let input = fs::read_to_string("input.txt").expect("Something went wrong reading the file"); let program: Vec<i64> = input.trim_end().split(",").map(|n| n.parse().unwrap()).collect(); run_robot(program); // println!("Score: {}", score); } #[derive(Clone, Copy, Debug)] enum MovementCommand { North, South, West, East, } impl MovementCommand { fn to_int(&self) -> i64 { match self { North => 1, South => 2, West => 3, East => 4, } } } use MovementCommand::*; #[derive(Debug)] enum RobotStatus { HitWall, HasMoved, HasMovedAndFoundOxygenSystem, } use RobotStatus::*; impl RobotStatus { fn from_int(int: i64) -> RobotStatus { match int { 0 => HitWall, 1 => HasMoved, 2 => HasMovedAndFoundOxygenSystem, n => panic!("Unknown RobotStatus {}", n), } } } #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)] struct Point { x: i64, y: i64, } impl Point { fn adjacent_points(&self) -> Vec<(MovementCommand, Point)> { vec![ (North, Point { x: self.x, y: self.y + 1 }), (South, Point { x: self.x, y: self.y - 1 }), (West, Point { x: self.x - 1, y: self.y }), (East, Point { x: self.x + 1, y: self.y }), ] } fn direction_to(&self, adjacent_point: Point) -> MovementCommand { if adjacent_point.x > self.x { East } else if adjacent_point.x < self.x { West } else if adjacent_point.y > self.y { North } else { South } } } enum PointType { Wall, NoWall, OxygenSystem, } use PointType::*; fn move_in_direction(point: Point, direction: MovementCommand) -> Point { match direction { North => Point { x: point.x, y: point.y + 1 }, South => Point { x: point.x, y: point.y - 1 }, West => Point { x: point.x - 1, y: point.y }, East => Point { x: point.x + 1, y: point.y }, } } fn print_map(map: &HashMap<Point, PointType>, robot_position: Point) { let min_x = map.keys().min_by_key(|p| p.x).unwrap().x; let max_x = map.keys().max_by_key(|p| p.x).unwrap().x; let min_y = map.keys().min_by_key(|p| p.y).unwrap().y; let max_y = map.keys().max_by_key(|p| p.y).unwrap().y; for neg_y in (-max_y)..=(-min_y) { let y = -neg_y; for x in min_x..=max_x { let current_point = Point { x, y }; if let Point { x: 0, y: 0 } = current_point { print!("0"); } else if robot_position == current_point { print!("D"); } else { match map.get(&current_point) { None => print!(" "), Some(Wall) => print!("#"), Some(NoWall) => print!("."), Some(OxygenSystem) => print!("o"), } } } println!(""); } println!(""); } fn run_robot(program: Vec<i64>) -> i64 { // Open channel to send input from main thread to game thread let (main_output, robot_input) = mpsc::channel(); // Open channel to receive output from game thread in main thread let (robot_output, main_input) = mpsc::channel(); let robot_thread = thread::spawn(move || { intcode::run_intcode_with_channels(program, robot_input, robot_output); }); let mut robot_position = Point { x: 0, y: 0 }; let mut robot_direction = North; let mut robot_status = HasMoved; let mut map: HashMap<Point, PointType> = HashMap::new(); // represents the path from origin let mut path = vec![robot_position]; let mut shortest_path_length_to_oxygen = None; loop { // thread::sleep(time::Duration::from_millis(40)); // Look for an adjacent unexplored point robot_direction = match robot_position.adjacent_points().iter().find(|(_, p)| !map.contains_key(p)) { None => { // We've reached a dead end: time to go back if let None = path.pop() { println!("done"); break; } if let Some(last_position) = path.pop() { let direction = robot_position.direction_to(last_position); direction } else { println!("done"); break; } }, Some((direction, _)) => { *direction } }; // Accept a movement command via an input instruction. // Send the movement command to the repair droid. println!("Trying to move: {:?}", robot_direction); main_output.send(robot_direction.to_int()).unwrap(); // Wait for the repair droid to finish the movement operation. // Report on the status of the repair droid via an output instruction. robot_status = RobotStatus::from_int(main_input.recv().unwrap()); println!("RobotStatus: {:?}", robot_status); match robot_status { HasMoved => { // Update position robot_position = move_in_direction(robot_position, robot_direction); map.insert(robot_position, NoWall); path.push(robot_position); }, HitWall => { let wall_position = move_in_direction(robot_position, robot_direction); map.insert(wall_position, Wall); }, HasMovedAndFoundOxygenSystem => { // Update position robot_position = move_in_direction(robot_position, robot_direction); map.insert(robot_position, OxygenSystem); path.push(robot_position); shortest_path_length_to_oxygen = Some(path.len()); println!("Oxygen system at: {:?}", robot_position); println!("Path length: {:?}", path.len()); // We're done! // If we want to explore the whole map, we can take out this break // break; }, } println!("Robot position: {:?}", robot_position); println!(""); print_map(&map, robot_position); } println!("Waiting for robot to finish"); // robot_thread.join().unwrap(); // Now we have the whole map print_map(&map, robot_position); println!("Shortest path length: {}", shortest_path_length_to_oxygen.unwrap()); return shortest_path_length_to_oxygen.unwrap() as i64; }
use fantoccini::error::CmdError; use fantoccini::{Client, Locator}; use futures::future::Future; use tokio; fn main() { // expects WebDriver instance to be listening at port 4444 let client = Client::new("http://localhost:4444"); let get_started_button = r#"//a[@class="button button-download ph4 mt0 w-100" and @href="/learn/get-started"]"#; let try_without_installing_button = r#"//a[@class="button button-secondary" and @href="https://play.rust-lang.org/"]"#; let play_rust_lang_run_button = r#"//div[@class="segmented-button"]/button[1]"#; let rust_lang = client .map_err(|error| unimplemented!("failed to connect to WebDriver: {:?}", error)) .and_then(|client| client.goto("https://www.rust-lang.org/")) // client_wait is an artificial delay only used to see the browsers actions and not necessary // in your own code .and_then(|client| client_wait(client, 3000)) .and_then(move |client| client.wait_for_find(Locator::XPath(get_started_button))) .and_then(|element| element.click()) .and_then(|client| client_wait(client, 3000)) .and_then(move |client| client.wait_for_find(Locator::XPath(try_without_installing_button))) .and_then(|element| element.click()) .and_then(|client| client_wait(client, 3000)) .and_then(move |client| { client.wait_for_find(Locator::XPath(play_rust_lang_run_button)) }) .and_then(|element| element.click()) .and_then(|client| client_wait(client, 6000)) .map(|_| ()) .map_err(|error| panic!("a WebDriver command failed: {:?}", error)); tokio::run(rust_lang); } // helper function to delay the client fn client_wait(client: Client, delay: u64) -> impl Future<Item = Client, Error = CmdError> { use std::time::{Duration, Instant}; use tokio::timer::Delay; Delay::new(Instant::now() + Duration::from_millis(delay)) .and_then(|_| Ok(client)) .map_err(|error| panic!("client failed to wait with error: {:?}", error)) }
use crate::{fetch_path, ABI}; use color_eyre::eyre::{bail, eyre, Result, WrapErr}; use lazy_static::lazy_static; use regex::Regex; use std::borrow::Cow; use std::fmt; use std::fs::File; use std::io::Write; use std::path::Path; pub struct Table<'a> { pub arch: &'a str, pub path: &'a str, pub abi: &'a [ABI<'a>], } pub struct Header<'a> { pub arch: &'a str, pub headers: &'a [&'a str], pub blocklist: &'a [&'a str], } pub enum Source<'a> { /// The definitions are in a `syscall.tbl` file. Table(Table<'a>), /// The definitions are in a unistd.h header file. Header(Header<'a>), } #[derive(Debug, Clone, Eq, PartialEq, Ord, PartialOrd)] pub struct TableEntry { pub id: u32, pub name: String, pub entry_point: Option<String>, } impl TableEntry { fn ident(&self) -> Cow<str> { if self.name.as_str() == "break" { Cow::Owned(format!("r#{}", self.name)) } else { Cow::Borrowed(&self.name) } } } impl<'a> Table<'a> { async fn fetch_table(&self) -> Result<Vec<TableEntry>> { let contents = fetch_path(self.path).await?; let mut table = Vec::new(); for line in contents.lines() { let line = line.trim(); // Skip over empty lines and comments. if line.is_empty() || line.starts_with('#') { continue; } let mut fields = line.split(char::is_whitespace).filter(|x| !x.is_empty()); let id: u32 = fields .next() .ok_or_else(|| eyre!("Missing syscall number (line {line:?})"))? .parse() .wrap_err_with(|| eyre!("Failed parsing line {line:?}"))?; let abi_name = fields.next().ok_or_else(|| { eyre!("Missing syscall abi field (line {line:?})") })?; let name = fields .next() .ok_or_else(|| { eyre!("Missing syscall name field (line {line:?})") })? .into(); let entry_point = fields.next().map(Into::into); for abi in self.abi { if abi.name == abi_name { table.push(TableEntry { id: id + abi.offset, name, entry_point, }); break; } } } // The table should already be sorted, but lets make sure. table.sort(); Ok(table) } } impl<'a> Header<'a> { async fn fetch_table(&self) -> Result<Vec<TableEntry>> { lazy_static! { // Pattern for matching the syscall definition. static ref RE_SYSCALLNR: Regex = Regex::new(r"^#define\s+__NR(?:3264)?_([a-z0-9_]+)\s+(\d+)").unwrap(); static ref RE_SYSCALLNR_ARCH: Regex = Regex::new(r"^#define\s+__NR(?:3264)?_([a-z0-9_]+)\s+\(__NR_arch_specific_syscall\s*\+\s*(\d+)\)").unwrap(); } let mut table = Vec::new(); let mut arch_specific_syscall: Option<u32> = None; for header in self.headers { let contents = fetch_path(header).await?; for line in contents.lines() { let line = line.trim(); if let Some(cap) = RE_SYSCALLNR.captures(line) { let name: &str = cap[1].into(); let id: u32 = cap[2].parse()?; if name == "syscalls" { // This just keeps track of the number of syscalls in // the table and isn't a real syscall. continue; } if name == "arch_specific_syscall" { // This is a placeholder for a block of 16 syscalls // that are reserved for future use. if arch_specific_syscall.is_none() { arch_specific_syscall = Some(id); } else { bail!("__NR_arch_specific_syscall is defined multiple times") } continue; } if self.blocklist.contains(&name) { continue; } table.push(TableEntry { id, name: name.into(), entry_point: Some(format!("sys_{name}")), }); } else if let Some(cap) = RE_SYSCALLNR_ARCH.captures(line) { if let Some(offset) = arch_specific_syscall { let name: &str = cap[1].into(); let id: u32 = cap[2].parse()?; if self.blocklist.contains(&name) { continue; } table.push(TableEntry { id: id + offset, name: name.into(), entry_point: Some(format!("sys_{name}")), }) } else { bail!("__NR_arch_specific_syscall definition not found before usage. \ Try reordering `Header::headers`?"); } } } } // The table should already be sorted, but lets make sure. table.sort(); Ok(table) } } impl<'a> Source<'a> { pub fn arch(&self) -> &'a str { match self { Self::Table(table) => table.arch, Self::Header(header) => header.arch, } } async fn fetch_table(&self) -> Result<Vec<TableEntry>> { match self { Self::Table(table) => table.fetch_table().await, Self::Header(header) => header.fetch_table().await, } } /// Generates the source file. pub(crate) async fn generate(&self, dir: &Path) -> Result<()> { let arch = self.arch(); let table = self .fetch_table() .await .wrap_err_with(|| eyre!("Failed fetching table for {arch}"))?; // Generate `src/arch/{arch}.rs` let path = dir.join(format!("src/arch/{arch}.rs")); let mut file = File::create(&path).wrap_err_with(|| { eyre!("Failed to create file {}", path.display()) })?; writeln!(file, "//! Syscalls for the `{arch}` architecture.\n")?; write!(file, "{}", SyscallFile(&table))?; println!("Generated syscalls for {arch} at {}", path.display()); Ok(()) } } struct SyscallFile<'a>(&'a [TableEntry]); impl<'a> fmt::Display for SyscallFile<'a> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { writeln!(f, "// This file is automatically generated. Do not edit!")?; writeln!(f)?; writeln!(f, "syscall_enum! {{")?; writeln!(f, " pub enum Sysno {{")?; for entry in self.0 { if entry.entry_point.is_some() { writeln!( f, " /// See [{name}(2)](https://man7.org/linux/man-pages/man2/{name}.2.html) for more info on this syscall.", name = entry.ident(), )?; writeln!( f, " {name} = {id},", name = entry.ident(), id = entry.id )?; } else { // This syscall has no entry point in the kernel, so we could // technically exclude this from our list, but that will leave // gaps in the syscall table. Our match statements can be better // optimized by the compiler if we don't have gaps in the // numbering. writeln!( f, " /// NOTE: `{name}` is not implemented in the kernel.", name = entry.ident(), )?; writeln!( f, " {name} = {id},", name = entry.ident(), id = entry.id )?; } } writeln!(f, " }}")?; writeln!(f, " LAST: {};", self.0.last().unwrap().ident())?; writeln!(f, "}}")?; Ok(()) } }
#[cfg(test)] mod test; use crate::{ bson::{doc, Document}, cmap::{Command, RawCommandResponse, StreamDescription}, error::{ErrorKind, Result}, index::IndexModel, operation::{append_options, remove_empty_write_concern, OperationWithDefaults}, options::{CreateIndexOptions, WriteConcern}, results::CreateIndexesResult, Namespace, }; use super::WriteConcernOnlyBody; #[derive(Debug)] pub(crate) struct CreateIndexes { ns: Namespace, indexes: Vec<IndexModel>, options: Option<CreateIndexOptions>, } impl CreateIndexes { pub(crate) fn new( ns: Namespace, indexes: Vec<IndexModel>, options: Option<CreateIndexOptions>, ) -> Self { Self { ns, indexes, options, } } #[cfg(test)] pub(crate) fn with_indexes(indexes: Vec<IndexModel>) -> Self { Self { ns: Namespace { db: String::new(), coll: String::new(), }, indexes, options: None, } } } impl OperationWithDefaults for CreateIndexes { type O = CreateIndexesResult; type Command = Document; const NAME: &'static str = "createIndexes"; fn build(&mut self, description: &StreamDescription) -> Result<Command> { // commit quorum is not supported on < 4.4 if description.max_wire_version.unwrap_or(0) < 9 && self .options .as_ref() .map_or(false, |options| options.commit_quorum.is_some()) { return Err(ErrorKind::InvalidArgument { message: "Specifying a commit quorum to create_index(es) is not supported on \ server versions < 4.4" .to_string(), } .into()); } self.indexes.iter_mut().for_each(|i| i.update_name()); // Generate names for unnamed indexes. let indexes = bson::to_bson(&self.indexes)?; let mut body = doc! { Self::NAME: self.ns.coll.clone(), "indexes": indexes, }; remove_empty_write_concern!(self.options); append_options(&mut body, self.options.as_ref())?; Ok(Command::new( Self::NAME.to_string(), self.ns.db.clone(), body, )) } fn handle_response( &self, response: RawCommandResponse, _description: &StreamDescription, ) -> Result<Self::O> { let response: WriteConcernOnlyBody = response.body()?; response.validate()?; let index_names = self.indexes.iter().filter_map(|i| i.get_name()).collect(); Ok(CreateIndexesResult { index_names }) } fn write_concern(&self) -> Option<&WriteConcern> { self.options .as_ref() .and_then(|opts| opts.write_concern.as_ref()) } }
pub mod prelude { pub use super::HtmlFile; pub use super::Response; } use std::fs; use std::path::Path; use super::status::HttpStatus; use crate::HTML_DIR; pub enum Response { File(HttpStatus, HtmlFile), Text(HttpStatus, String), } impl Response { pub fn raw(&self) -> String { match self { Response::File(status, file) => { format!("{}\r\n\r\n{}", status.status_line(), file.contents()) } Response::Text(status, text) => { format!("{}\r\n\r\n{}", status.status_line(), text) } } } } pub struct HtmlFile(String); impl HtmlFile { pub fn new<T>(filename: T) -> Self where T: ToString, { Self(path!(HTML_DIR, filename).to_str().unwrap().to_string()) } pub fn contents(&self) -> String { fs::read_to_string(&self.0).unwrap() } }
pub mod apparent_pk; pub mod full_pk;
pub mod category; pub mod comment; pub mod drive; pub mod embed; pub mod handler; pub mod info; pub mod node; pub mod page; pub mod post; pub mod topic; pub mod user;
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] use azul::prelude::*; use rand::Rng; use std::borrow::BorrowMut; #[cfg(debug_assertions)] use std::time::Duration; const FONT_RALEWAY: &[u8] = include_bytes!("../assets/fonts/Raleway/Raleway-Regular.ttf"); macro_rules! CSS_PATH { () => { concat!(env!("CARGO_MANIFEST_DIR"), "/styles/main.css") }; } #[derive(Debug, Copy, Clone, PartialEq)] enum Cell { X, O, Empty, } #[derive(PartialEq)] enum GameStatus { Proceed, UserWon, IWon, Draw, } #[derive(Default)] struct TicTacToe { user_is_x: bool, cells: Vec<Cell>, game_status: GameStatus, } impl Default for GameStatus { fn default() -> Self { GameStatus::Proceed } } impl Layout for TicTacToe { fn layout(&self, _info: LayoutInfo<Self>) -> Dom<Self> { let board = Dom::div() .with_id("board") .with_child(self.row(1)) .with_child(self.row(2)) .with_child(self.row(3)); let control_panel: Dom<Self> = Dom::div() .with_id("control_panel") .with_child( Dom::label("Start new game as X") .with_class("button") .with_callback(On::MouseUp, Callback(new_game)), ) .with_child( Dom::label("Start new game as O") .with_class("button") .with_callback(On::MouseUp, Callback(new_game)), ) .with_child(if self.game_status == GameStatus::Proceed { Dom::div() } else if self.game_status == GameStatus::UserWon { Dom::label("You win!").with_class("banner") } else if self.game_status == GameStatus::IWon { Dom::label("I win!").with_class("banner") } else { Dom::label("Draw").with_class("banner") }); let header = Dom::label("Tic-tac-toe").with_id("header"); let main = Dom::div() .with_id("main") .with_child(control_panel) .with_child(board); Dom::div().with_child(header).with_child(main) } } impl TicTacToe { fn row(&self, x: usize) -> Dom<Self> { (0..3) .map(|y| { if self.cells[(x - 1) * 3 + y] == Cell::Empty { NodeData { node_type: NodeType::Div, ids: vec![DomString::Heap(((x - 1) * 3 + y).to_string())], classes: vec![DomString::Static("cell"), DomString::Static("empty")], callbacks: vec![(On::MouseUp.into(), Callback(place_user_counter))], ..Default::default() } } else { NodeData { node_type: NodeType::Label(if self.cells[(x - 1) * 3 + y] == Cell::X { DomString::Static("x") } else { DomString::Static("o") }), ids: vec![DomString::Heap(((x - 1) * 3 + y).to_string())], classes: vec![ DomString::Static("cell"), if self.cells[(x - 1) * 3 + y] == Cell::X { DomString::Static("x") } else { DomString::Static("o") }, ], ..Default::default() } } }) .collect::<Dom<Self>>() .with_class("row") } } fn place_user_counter( app_state: &mut AppState<TicTacToe>, event: &mut CallbackInfo<TicTacToe>, ) -> UpdateScreen { // Get position of parent let x = event .get_index_in_parent(event.target_parent().unwrap()) .unwrap() .0; // Get position in parent let y = event.target_index_in_parent().unwrap(); println!("clicked cell = {}", x * 3 + y); let mut app = app_state.data.borrow_mut().lock().unwrap(); // Change the cell to the user's counter app.cells[x * 3 + y] = if app.user_is_x { Cell::X } else { Cell::O }; let cells = app.cells.clone(); let user_is_x = app.user_is_x.clone(); app.game_status = check_game_status(&cells, &user_is_x); if app.game_status == GameStatus::Proceed { // If the game hasn't ended yet, make our move let opponents_counter = place_opponent_counter(&cells, &user_is_x); println!("opponent's move: {}", opponents_counter); app.cells[opponents_counter] = if app.user_is_x { Cell::O } else { Cell::X }; // Check if we won the game let cells = app.cells.clone(); app.game_status = check_game_status(&cells, &user_is_x); } Redraw } fn place_opponent_counter(cells: &Vec<Cell>, user_is_x: &bool) -> usize { let mut x_counters = vec![]; let mut o_counters = vec![]; /*let neighbours: [Vec<usize>; 9] = [ vec![1, 3, 4], vec![0, 2, 3, 4, 5], vec![1, 4, 5], vec![0, 1, 4, 6, 7], vec![0, 1, 2, 3, 5, 6, 7, 8], vec![1, 2, 4, 7, 8], vec![3, 4, 7], vec![3, 4, 5, 6, 8], vec![4, 5, 7], ];*/ let possible_win_positions: [Vec<usize>; 9] = [ vec![1, 3, 4], vec![4], vec![1, 4, 5], vec![4], vec![], vec![4], vec![3, 4, 7], vec![4], vec![4, 5, 7], ]; for (i, cell) in cells.iter().enumerate() { if *cell == Cell::X { x_counters.push(i); } else if *cell == Cell::O { o_counters.push(i); } } let (opponents_counters, users_counters) = if *user_is_x { (o_counters, x_counters) } else { (x_counters, o_counters) }; println!("our counters = {:?}", opponents_counters); println!("user's counters = {:?}", users_counters); if opponents_counters.len() >= 2 { // If we've placed at least 2 counters so there's a chance to win for cell_index in opponents_counters.iter() { // Iterate over our placed counters println!( "neighbours of {} to check: {:?}", cell_index, possible_win_positions[*cell_index] ); for neighbour in possible_win_positions[*cell_index].iter() { if opponents_counters.contains(neighbour) && !users_counters.contains(&(neighbour * 2 - cell_index)) && neighbour * 2 - cell_index < 9 { // The next cell in the line isn't occupied by the user and isn't outside the board // Return the index of the next cell to complete the line and win return neighbour * 2 - cell_index; } } } } println!("our counters = {:?}", opponents_counters); println!("user's counters = {:?}", users_counters); if users_counters.len() >= 2 { // If the user has placed at least 2 counters so there's a chance they could win for cell_index in users_counters.iter() { // Iterate over the counters they've placed println!( "neighbours of {} to check: {:?}", cell_index, possible_win_positions[*cell_index] ); for neighbour in possible_win_positions[*cell_index].iter() { println!("Does the user have {}? {}", neighbour, users_counters.contains(neighbour)); println!("Do we have {}? {}", neighbour * 2 - cell_index, opponents_counters.contains(&(neighbour * 2 - cell_index))); if users_counters.contains(neighbour) && !opponents_counters.contains(&(neighbour * 2 - cell_index)) && neighbour * 2 - cell_index < 9 { // The next cell in the line isn't occupied by us and isn't outside the grid // Return the index of the next cell to stop the user from winning this way return neighbour * 2 - cell_index; } } } } // Select a random empty cell to place the opponent's counter let mut rng = rand::thread_rng(); let cell = rng.gen_range(0, 9); if cells[cell] == Cell::Empty { // We have found an empty cell, return its index return cell; } // The cell wasn't empty, try again return place_opponent_counter(cells, user_is_x); } fn check_game_status(cells: &Vec<Cell>, user_is_x: &bool) -> GameStatus { let mut x_counters = vec![]; let mut o_counters = vec![]; let mut empty_cells = vec![]; let neighbours: [Vec<usize>; 9] = [ vec![1, 3, 4], vec![0, 2, 3, 4, 5], vec![1, 4, 5], vec![0, 1, 4, 6, 7], vec![0, 1, 2, 3, 5, 6, 7, 8], vec![1, 2, 4, 7, 8], vec![3, 4, 7], vec![3, 4, 5, 6, 8], vec![4, 5, 7], ]; let forward_neighbours: [Vec<usize>; 8] = [ vec![1, 3, 4], vec![2, 3, 4, 5], vec![4, 5], vec![4, 6, 7], vec![5, 6, 7, 8], vec![7, 8], vec![7], vec![8], ]; for (i, cell) in cells.iter().enumerate() { if *cell == Cell::X { x_counters.push(i); } else if *cell == Cell::O { o_counters.push(i); } else { empty_cells.push(i); } } for counter in [x_counters.clone(), o_counters].iter() { // Iterate over both the players if counter.len() >= 3 { // If this player has placed at least 3 counters, so there's a possibility they won for cell_index in counter[0..counter.len() - 2].iter() { // Skip checking for the last two indices because a winning pattern needs to have 2 counters after it for neighbour in forward_neighbours[*cell_index].iter() { if counter.contains(neighbour) { if !neighbours[*cell_index].contains(&(neighbour * 2 - cell_index)) && counter.contains(&(neighbour * 2 - cell_index)) { if counter[0] == x_counters[0] { return if *user_is_x { GameStatus::UserWon } else { GameStatus::IWon }; } else { return if *user_is_x { GameStatus::IWon } else { GameStatus::UserWon }; } } } } } } } if empty_cells.len() == 0 { // All the cells have been filled, and neither players have won, which means it's a draw return GameStatus::Draw; } GameStatus::Proceed } fn new_game( app_state: &mut AppState<TicTacToe>, event: &mut CallbackInfo<TicTacToe>, ) -> UpdateScreen { let mut app = app_state.data.borrow_mut().lock().unwrap(); // Set user's counter app.user_is_x = [true, false][event.target_index_in_parent().unwrap()]; let cells = vec![ Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, ]; app.cells = cells.clone(); app.game_status = GameStatus::Proceed; if !app.user_is_x { app.cells[place_opponent_counter(&cells, &false)] = Cell::X; } Redraw } fn main() { let mut app = App::new( TicTacToe { user_is_x: true, cells: vec![ Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, Cell::Empty, ], game_status: GameStatus::Proceed, }, AppConfig::default(), ) .unwrap(); let mut window_create_options = WindowCreateOptions::default(); window_create_options.state.title = String::from("Tic-tac-toe"); window_create_options.state.is_maximized = true; #[cfg(debug_assertions)] let window = { let hot_reloader = css::hot_reload(CSS_PATH!(), Duration::from_millis(500)); app.create_hot_reload_window(window_create_options, hot_reloader).unwrap() }; #[cfg(not(debug_assertions))] let window = { let css = css::from_str(include_str!(CSS_PATH!())).unwrap(); app.create_window(window_create_options, css).unwrap() }; let font_id = app.add_css_font_id("Raleway-Regular"); app.add_font(font_id, FontSource::Embedded(FONT_RALEWAY)); app.run(window).unwrap(); }
//! Developer note: //! //! This is a set of embed builders for rich embeds. //! //! These are used in the [`Context::send_message`] and //! [`ExecuteWebhook::embeds`] methods, both as part of builders. //! //! The only builder that should be exposed is [`CreateEmbed`]. The rest of //! these have no real reason for being exposed, but are for completeness' sake. //! //! Documentation for embeds can be found [here]. //! //! [`Context::send_message`]: ../../client/struct.Context.html#method.send_message //! [`CreateEmbed`]: struct.CreateEmbed.html //! [`ExecuteWebhook::embeds`]: struct.ExecuteWebhook.html#method.embeds //! [here]: https://discordapp.com/developers/docs/resources/channel#embed-object use serde_json::builder::ObjectBuilder; use serde_json::Value; use std::collections::BTreeMap; use std::default::Default; use ::utils::Colour; /// A builder to create a fake [`Embed`] object, for use with the /// [`Context::send_message`] and [`ExecuteWebhook::embeds`] methods. /// /// # Examples /// /// Refer to the documentation for [`Context::send_message`] for a very in-depth /// example on how to use this. /// /// [`Context::send_message`]: ../../client/struct.Context.html#method.send_message /// [`Embed`]: ../../model/struct.Embed.html /// [`ExecuteWebhook::embeds`]: struct.ExecuteWebhook.html#method.embeds pub struct CreateEmbed(pub BTreeMap<String, Value>); impl CreateEmbed { /// Set the author of the embed. /// /// Refer to the documentation for [`CreateEmbedAuthor`] for more /// information. /// /// [`CreateEmbedAuthor`]: struct.CreateEmbedAuthor.html pub fn author<F>(mut self, f: F) -> Self where F: FnOnce(CreateEmbedAuthor) -> CreateEmbedAuthor { let author = f(CreateEmbedAuthor::default()).0.build(); self.0.insert("author".to_owned(), author); CreateEmbed(self.0) } /// Set the colour of the left-hand side of the embed. /// /// This is an alias of [`colour`]. /// /// [`colour`]: #method.colour pub fn color<C: Into<Colour>>(self, colour: C) -> Self { self.colour(colour.into()) } /// Set the colour of the left-hand side of the embed. pub fn colour<C: Into<Colour>>(mut self, colour: C) -> Self { self.0.insert("color".to_owned(), Value::U64(colour.into().value as u64)); CreateEmbed(self.0) } /// Set the description of the embed. pub fn description(mut self, description: &str) -> Self { self.0.insert("description".to_owned(), Value::String(description.to_owned())); CreateEmbed(self.0) } /// Set a field. Note that this will not overwrite other fields, and will /// add to them. /// /// Refer to the documentation for [`CreateEmbedField`] for more /// information. /// /// [`CreateEmbedField`]: struct.CreateEmbedField.html pub fn field<F>(mut self, f: F) -> Self where F: FnOnce(CreateEmbedField) -> CreateEmbedField { let field = f(CreateEmbedField::default()).0.build(); { let key = "fields".to_owned(); let entry = self.0.remove(&key).unwrap_or_else(|| Value::Array(vec![])); let mut arr = match entry { Value::Array(inner) => inner, _ => { // The type of `entry` should always be a `Value::Array`. // // Theoretically this never happens, but you never know. // // In the event that it does, just return the current value. return CreateEmbed(self.0); }, }; arr.push(field); self.0.insert("fields".to_owned(), Value::Array(arr)); } CreateEmbed(self.0) } /// Set the footer of the embed. /// /// Refer to the documentation for [`CreateEmbedFooter`] for more /// information. /// /// [`CreateEmbedFooter`]: struct.CreateEmbedFooter.html pub fn footer<F>(mut self, f: F) -> Self where F: FnOnce(CreateEmbedFooter) -> CreateEmbedFooter { let footer = f(CreateEmbedFooter::default()).0.build(); self.0.insert("footer".to_owned(), footer); CreateEmbed(self.0) } /// Set the image associated with the embed. /// /// Refer to the documentation for [`CreateEmbedImage`] for more /// information. /// /// [`CreateEmbedImage`]: struct.CreateEmbedImage.html pub fn image<F>(mut self, f: F) -> Self where F: FnOnce(CreateEmbedImage) -> CreateEmbedImage { let image = f(CreateEmbedImage::default()).0.build(); self.0.insert("image".to_owned(), image); CreateEmbed(self.0) } /// Set the thumbnail of the embed. /// /// Refer to the documentation for [`CreateEmbedThumbnail`] for more /// information. /// /// [`CreateEmbedThumbnail`]: struct.CreateEmbedThumbnail.html pub fn thumbnail<F>(mut self, f: F) -> Self where F: FnOnce(CreateEmbedThumbnail) -> CreateEmbedThumbnail { let thumbnail = f(CreateEmbedThumbnail::default()).0.build(); self.0.insert("thumbnail".to_owned(), thumbnail); CreateEmbed(self.0) } /// Set the timestamp. pub fn timestamp(mut self, timestamp: &str) -> Self { self.0.insert("timestamp".to_owned(), Value::String(timestamp.to_owned())); CreateEmbed(self.0) } /// Set the title of the embed. pub fn title(mut self, title: &str) -> Self { self.0.insert("title".to_owned(), Value::String(title.to_owned())); CreateEmbed(self.0) } /// Set the URL to direct to when clicking on the title. pub fn url(mut self, url: &str) -> Self { self.0.insert("url".to_owned(), Value::String(url.to_owned())); CreateEmbed(self.0) } } impl Default for CreateEmbed { /// Creates a builder with default values, setting the `type` to `rich`. fn default() -> CreateEmbed { let mut map = BTreeMap::new(); map.insert("type".to_owned(), Value::String("rich".to_owned())); CreateEmbed(map) } } /// A builder to create a fake [`Embed`] object's author, for use with the /// [`CreateEmbed::author`] method. /// /// Requires that you specify a [`name`]. /// /// [`Embed`]: ../../model/struct.Embed.html /// [`CreateEmbed::author`]: struct.CreateEmbed.html#method.author /// [`name`]: #method.name pub struct CreateEmbedAuthor(pub ObjectBuilder); impl CreateEmbedAuthor { /// Set the URL of the author's icon. pub fn icon_url(self, icon_url: &str) -> Self { CreateEmbedAuthor(self.0.insert("icon_url", icon_url)) } /// Set the author's name. pub fn name(self, name: &str) -> Self { CreateEmbedAuthor(self.0.insert("name", name)) } /// Set the author's URL. pub fn url(self, url: &str) -> Self { CreateEmbedAuthor(self.0.insert("url", url)) } } impl Default for CreateEmbedAuthor { /// Creates a builder with no default values. fn default() -> CreateEmbedAuthor { CreateEmbedAuthor(ObjectBuilder::new()) } } /// A builder to create a fake [`Embed`] object's field, for use with the /// [`CreateEmbed::field`] method. /// /// This does not require any field be set. `inline` is set to `true` by /// default. /// /// [`Embed`]: ../../model/struct.Embed.html /// [`CreateEmbed::field`]: struct.CreateEmbed.html#method.field pub struct CreateEmbedField(pub ObjectBuilder); impl CreateEmbedField { /// Set whether the field is inlined. pub fn inline(self, inline: bool) -> Self { CreateEmbedField(self.0.insert("inline", inline)) } /// Set the field's name. pub fn name(self, name: &str) -> Self { CreateEmbedField(self.0.insert("name", name)) } /// Set the field's value. pub fn value(self, value: &str) -> Self { CreateEmbedField(self.0.insert("value", value)) } } impl Default for CreateEmbedField { /// Creates a builder with default values, setting the value of `inline` to /// `true`. fn default() -> CreateEmbedField { CreateEmbedField(ObjectBuilder::new().insert("inline", true)) } } /// A builder to create a fake [`Embed`] object's footer, for use with the /// [`CreateEmbed::footer`] method. /// /// This does not require any field be set. /// /// [`Embed`]: ../../model/struct.Embed.html /// [`CreateEmbed::footer`]: struct.CreateEmbed.html#method.footer pub struct CreateEmbedFooter(pub ObjectBuilder); impl CreateEmbedFooter { /// Set the icon URL's value. This only supports HTTP(S). pub fn icon_url(self, icon_url: &str) -> Self { CreateEmbedFooter(self.0.insert("icon_url", icon_url)) } /// Set the footer's text. pub fn text(self, text: &str) -> Self { CreateEmbedFooter(self.0.insert("text", text)) } } impl Default for CreateEmbedFooter { /// Creates a builder with no default values. fn default() -> CreateEmbedFooter { CreateEmbedFooter(ObjectBuilder::new()) } } /// A builder to create a fake [`Embed`] object's image, for use with the /// [`CreateEmbed::image`] method. /// /// This does not require any field be set. /// /// [`Embed`]: ../../model/struct.Embed.html /// [`CreateEmbed::image`]: struct.CreateEmbed.html#method.image pub struct CreateEmbedImage(pub ObjectBuilder); impl CreateEmbedImage { /// Set the display height of the image. pub fn height(self, height: u64) -> Self { CreateEmbedImage(self.0.insert("height", height)) } /// Set the image's URL. This only supports HTTP(S). pub fn url(self, url: &str) -> Self { CreateEmbedImage(self.0.insert("url", url)) } /// Set the display width of the image. pub fn width(self, width: u64) -> Self { CreateEmbedImage(self.0.insert("widht", width)) } } impl Default for CreateEmbedImage { /// Creates a builder with no default values. fn default() -> CreateEmbedImage { CreateEmbedImage(ObjectBuilder::new()) } } /// A builder to create a fake [`Embed`] object's thumbnail, for use with the /// [`CreateEmbed::thumbnail`] method. /// /// Requires that you specify a [`url`]. /// /// [`Embed`]: ../../model/struct.Embed.html /// [`CreateEmbed::thumbnail`]: struct.CreateEmbed.html#method.thumbnail /// [`url`]: #method.url pub struct CreateEmbedThumbnail(pub ObjectBuilder); impl CreateEmbedThumbnail { /// Set the height of the thumbnail, in pixels. pub fn height(self, height: u64) -> Self { CreateEmbedThumbnail(self.0.insert("height", height)) } /// Set the URL of the thumbnail. This only supports HTTP(S). /// /// _Must_ be specified. pub fn url(self, url: &str) -> Self { CreateEmbedThumbnail(self.0.insert("url", url)) } /// Set the width of the thumbnail, in pixels. pub fn width(self, width: u64) -> Self { CreateEmbedThumbnail(self.0.insert("width", width)) } } impl Default for CreateEmbedThumbnail { /// Creates a builder with no default values. fn default() -> CreateEmbedThumbnail { CreateEmbedThumbnail(ObjectBuilder::new()) } }
use std::borrow::Cow; use darling::ast::Fields; use proc_macro2::{Span, TokenStream}; use quote::{quote, quote_spanned, ToTokens, TokenStreamExt}; use syn::{self, Attribute, Generics, Ident, Path}; use crate::util; /// Receiver for trait impl; this gets the struct ident and the fields /// in the struct. pub struct TraitImpl<'a> { pub ident: &'a Ident, pub attrs: &'a [Attribute], /// The generics on the input struct. In keeping with Rust's own implementation /// of `derive(Debug)` et al, we'll require that each of these implements `Default` /// for our emitted impl to apply. pub generics: Cow<'a, Generics>, pub fields: Fields<Field<'a>>, } impl<'a> TraitImpl<'a> { fn body(&self) -> TokenStream { if self.fields.style.is_struct() { let fields = self.fields.iter(); quote! { Self { #(#fields),* } } } else { let ident = &self.ident; let fields = self.fields.iter(); quote! { #ident(#(#fields),*) } } } } impl<'a> ToTokens for TraitImpl<'a> { fn to_tokens(&self, tokens: &mut TokenStream) { let body = self.body(); let ident = &self.ident; let attrs = self.attrs.iter(); let generics = if has_type_params(&self.generics) { Cow::Owned(compute_impl_bounds( util::trait_path(Span::call_site()), self.generics.clone().into_owned(), )) } else { self.generics.clone() }; let (impl_gen, ty_gen, where_clause) = generics.split_for_impl(); let trait_path = util::trait_path(Span::call_site()); // We add the "automatically_derived" attribute so that we don't make warnings // for unused code; see the compiler code below: // https://github.com/rust-lang/rust/blob/1.27.2/src/librustc/middle/liveness.rs#L366-L374 tokens.append_all(&[quote! { #[automatically_derived] #(#attrs)* impl #impl_gen #trait_path for #ident #ty_gen #where_clause { fn default() -> Self { #body } } }]); } } /// Checks if a set of generics has type parameters fn has_type_params(generics: &Generics) -> bool { generics.type_params().next().is_some() } fn compute_impl_bounds(bound: Path, mut generics: Generics) -> Generics { if !has_type_params(&generics) { return generics; } let added_bound = syn::TypeParamBound::Trait(syn::TraitBound { paren_token: None, modifier: syn::TraitBoundModifier::None, lifetimes: None, path: bound, }); for typ in generics.type_params_mut() { typ.bounds.push(added_bound.clone()); } generics } /// State required to generate initializer code for a struct field inside the body of /// `Default::default` pub struct Field<'a> { /// The position of this field in the input source; this is used to place errors in /// case the generated code has incorrect types. pub span: Span, /// The field identifier. This can be `None` for newtype and tuple struct fields. pub ident: Option<&'a Ident>, /// The path of the zero-argument function to invoke for the field's default value pub path: Cow<'a, Path>, } impl<'a> ToTokens for Field<'a> { fn to_tokens(&self, tokens: &mut TokenStream) { let Field { span, ref ident, ref path, } = *self; if let Some(ident) = ident { tokens.extend(quote_spanned!(span=> #ident: #path())); } else { tokens.extend(quote_spanned!(span=> #path())); } } }
use std::env::var; use std::fmt; use std::fmt::{Display, Formatter}; use std::fs::read_to_string; use std::path::PathBuf; use anyhow::{Context, Result}; use serde::de::DeserializeOwned; use serde::Serialize; use crate::cfg::global::GLOBAL_FILE_NAME; use crate::cfg::{GlobalCfg, LocalCfg}; use crate::utils::find::find_in_parents; use crate::utils::write_all::write_all_dir; #[derive(Debug)] pub struct FileCfg<C> where C: Serialize + DeserializeOwned, { file: Option<PathBuf>, cfg: C, } impl<C> FileCfg<C> where C: Serialize + DeserializeOwned, { pub fn load(file: &PathBuf) -> Result<FileCfg<C>> { let str = read_to_string(&file)?; let cfg = serde_yaml::from_str(str.as_str()) .context(format!("fail to parse {}", file.to_string_lossy()))?; Ok(Self { cfg, file: Some(file.to_path_buf()), }) } pub fn new(file: &PathBuf, cfg: C) -> Result<FileCfg<C>> { if !file.is_absolute() { return Err(anyhow!("cfg file path must be an abosulte path")); } Ok(Self { file: Some(file.to_path_buf()), cfg, }) } pub fn save(&self) -> Result<()> { let path = self.file.as_ref().context("cfg file has not path")?; let str = serde_yaml::to_string(&self.cfg).context("fail to parse cfg")?; write_all_dir(path, &str).context("fail to write cfg file")?; Ok(()) } pub fn file(&self) -> Result<&PathBuf> { self.file.as_ref().context("local cfg has no path") } pub fn borrow(&self) -> &C { &self.cfg } pub fn borrow_mut(&mut self) -> &mut C { &mut self.cfg } } fn local_cfg_file(dir: &PathBuf) -> PathBuf { let local_cfg_file = var("SHORT_LOCAL_CFG_FILE").map_or("short.yaml".to_string(), |v| v); dir.join(local_cfg_file) } pub fn load_local_cfg(dir: &PathBuf) -> Result<FileCfg<LocalCfg>> { let local_cfg_file = local_cfg_file(dir); let local_cfg = get_local_cfg(&local_cfg_file).context(format!( "cfg file not found {}", local_cfg_file.to_string_lossy() ))?; Ok(local_cfg) } pub fn new_local_cfg(dir: &PathBuf) -> Result<FileCfg<LocalCfg>> { let local_cfg_file = local_cfg_file(dir); if let Ok(_) = get_local_cfg(&local_cfg_file) { return Err(anyhow!("local cfg {:?} already exist", local_cfg_file)); } FileCfg::new(&local_cfg_file, LocalCfg::new()) } pub fn global_cfg_directory(dir: &PathBuf) -> PathBuf { let global_cfg_dir = var("SHORT_GLOBAL_CFG_DIR").map_or(".short/".to_string(), |v| v); dir.join(global_cfg_dir) } pub fn load_or_new_global_cfg(dir: &PathBuf) -> Result<FileCfg<GlobalCfg>> { let global_dir = global_cfg_directory(dir); let global_cfg_file = global_dir.join(GLOBAL_FILE_NAME.to_string()); // TODO : Think about return error relative to syntax or log it. let global = get_global_cfg(&global_cfg_file).map_or( FileCfg::new(&global_cfg_file, GlobalCfg::new()).context(format!( "fail to create new global cfg file {:?}", global_cfg_file ))?, |v| v, ); Ok(global) } pub fn get_local_cfg(file: &PathBuf) -> Result<FileCfg<LocalCfg>> { let dir = file.parent().context(format!( "fail to reach directory of local cfg file {}", file.to_string_lossy() ))?; let file_name = file .file_name() .context(format!( "fail te get file name of local cfg file {}", file.to_string_lossy() ))? .to_str() .context(format!( "cfg file name mut be contain only utf-8 char : {}", file.to_string_lossy() ))? .to_string(); let path = find_in_parents(dir.to_path_buf(), file_name).context("fail to found local cfg")?; FileCfg::load(&path) } pub fn get_global_cfg(file: &PathBuf) -> Result<FileCfg<GlobalCfg>> { FileCfg::load(file) } impl From<LocalCfg> for FileCfg<LocalCfg> { fn from(cfg: LocalCfg) -> Self { Self { cfg, file: None } } } impl From<GlobalCfg> for FileCfg<GlobalCfg> { fn from(cfg: GlobalCfg) -> Self { Self { cfg, file: None } } } impl<C> Display for FileCfg<C> where C: Serialize + DeserializeOwned, { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { if let Ok(content) = serde_yaml::to_string(&self.cfg).map_err(|_err| fmt::Error {}) { write!(f, "{}", content)?; } Ok(()) } } #[cfg(test)] mod test { use std::path::PathBuf; use anyhow::Result; use cli_integration_test::IntegrationTestEnvironment; use predicates::prelude::Predicate; use predicates::str::contains; use crate::cfg::file::{load_local_cfg, FileCfg}; use crate::cfg::LocalCfg; fn init_env() -> IntegrationTestEnvironment { let mut e = IntegrationTestEnvironment::new("cmd_help"); e.add_file("setup_1/template.yaml", ""); e.add_file( "short.yaml", r"#--- setups: setup_1: public_env_dir: 'setup_1/' file: ./run.sh #", ); e.setup(); e } #[test] fn load() { let e = init_env(); let file_cfg: Result<FileCfg<LocalCfg>> = FileCfg::load(&e.path().unwrap().join("short.yaml")); let file_cfg = file_cfg.unwrap(); let path = file_cfg.file.unwrap().clone(); assert!(contains("short.yaml").eval(path.to_string_lossy().as_ref())); } #[test] fn load_local() { let e = init_env(); let file_local_cfg = load_local_cfg(&e.path().unwrap().join("setup_1/short.yaml")); let file_local_cfg = file_local_cfg.unwrap(); let path = file_local_cfg.file.unwrap().clone(); assert!(contains("short.yaml").eval(path.to_string_lossy().as_ref())); } #[test] fn local_new_file() { let e = init_env(); let local_cfg = LocalCfg::new(); FileCfg::new(&PathBuf::from("example"), local_cfg).unwrap_err(); let local_cfg = LocalCfg::new(); let _file_cfg_local = FileCfg::new(&e.path().unwrap().join(PathBuf::from("example")), local_cfg).unwrap(); } }
use minifb::{Key, WindowOptions, Window, Scale, KeyRepeat}; const CHAR_0: [u8; 5] = [ 0b01100000, 0b10010000, 0b10010000, 0b10010000, 0b01100000, ]; const CHAR_1: [u8; 5] = [ 0b00100000, 0b01100000, 0b00100000, 0b00100000, 0b01110000, ]; const SPRITE: [u8; 5] = [ 0b00100100, 0b00100100, 0b00000000, 0b10000001, 0b01111110, ]; #[derive(Debug)] pub struct Point { x: usize, y: usize, } impl Point { pub fn new(x: usize, y: usize) -> Point { Point { x, y, } } } pub struct Buffer { width: usize, height: usize, pixels: Vec<u32>, pub dirty: bool, } impl Buffer { pub fn new(width: usize, height: usize, pixels: Option<Vec<u32>>) -> Buffer { let mut empty_pixels = Vec::new(); for _ in 0..(width * height) { empty_pixels.push(0u32); } Buffer { width, height, pixels: match pixels { Some(p) => p, None => empty_pixels, }, dirty: true, } } pub fn blit(&mut self, buffer: &Buffer, offset: Point) { let draw_idx = offset.x + offset.y * self.width; for (idx, pixel) in buffer.pixels.iter().enumerate() { let target_x = idx % buffer.width; let target_y = (idx - target_x) / buffer.width; /* println!( "{}: {} + {}, {} + {}, {} * {}, {} * {}", idx, offset.x, target_x, offset.y, target_y, self.width, self.height, buffer.width, buffer.height ); */ if offset.x + target_x > buffer.width || offset.y + target_y > buffer.height { continue; } let draw_idx = offset.x + target_x + (offset.y + target_y) * self.width; self.pixels[draw_idx] = *pixel; } self.dirty = true; } pub fn clear(&mut self) { let mut empty_pixels = Vec::new(); for _ in 0..(self.width * self.height) { empty_pixels.push(0u32); } self.pixels = empty_pixels; } } pub struct Screen { buffer: Buffer, pub game_buffer: Buffer, pub debug_buffer: Buffer, pub window: Window, } impl Screen { pub fn new( game_width: usize, game_height: usize, debug_width: usize, debug_height: usize) -> Screen { let total_width = game_width + debug_width; let total_height = game_height + debug_height; let buffer = Buffer::new(total_width, total_height, None); let game_buffer = Buffer::new(game_width, game_height, None); let debug_buffer = Buffer::new(debug_width, debug_height, None); // Prepare frame buffer let mut window = Window::new( "CHIP-8 - ESC to exit", total_width, total_height, WindowOptions { resize: false, scale: Scale::X4, ..WindowOptions::default() }) .unwrap_or_else(|e| { panic!("{}", e); }); Screen { buffer, game_buffer, debug_buffer, window, } } pub fn update(&mut self) { // Blit game_buffer and debug_buffer to buffer if self.game_buffer.dirty { println!("Draw game"); self.buffer.blit(&self.game_buffer, Point::new(0, 0)); self.game_buffer.dirty = false; } if self.debug_buffer.dirty { println!("Draw game"); self.buffer.blit(&self.debug_buffer, Point::new(self.game_buffer.width, 0)); self.debug_buffer.dirty = false; } if self.buffer.dirty { // Update window with buffer self.window.update_with_buffer(&self.buffer.pixels); // Clear dirty flag self.buffer.dirty = false; } else { // TODO: Update window self.window.update(); } } }
#![feature(core)] //! //! # Usage //! //! ```test_harness //! extern crate "youtube3-dev" as youtube3; //! extern crate hyper; //! //! # #[test] //! # fn test() { //! # // TODO - generate ! //! # } //! ``` use std::marker::PhantomData; use std::cell::RefCell; use std::borrow::BorrowMut; use std::default::Default; use hyper; use oauth2; mod common; pub mod videos; /// Central instance to access all youtube related services pub struct YouTube<C, NC, A> { client: RefCell<C>, auth: RefCell<A>, _m: PhantomData<NC> } impl<'a, C, NC, A> YouTube<C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut<hyper::Client<NC>> + 'a, A: oauth2::GetToken { pub fn new(client: C, authenticator: A) -> YouTube<C, NC, A> { YouTube { client: RefCell::new(client), auth: RefCell::new(authenticator), _m: PhantomData, } } pub fn videos(&'a self) -> videos::Service<'a, C, NC, A> { videos::Service::new(&self) } pub fn channel_sections(&'a self) -> ChannelSectionMethodsBuilder<'a, C, NC, A> { ChannelSectionMethodsBuilder { hub: &self } } } pub fn new<C, NC, A>(client: C, authenticator: A) -> YouTube<C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut<hyper::Client<NC>>, A: oauth2::GetToken { YouTube::new(client, authenticator) } #[cfg(test)] mod tests { use super::*; use hyper; use oauth2; use std::default::Default; #[test] fn instantiate() { let secret = <oauth2::ApplicationSecret as Default>::default(); let auth = oauth2::Authenticator::new( &secret, oauth2::DefaultAuthenticatorDelegate, hyper::Client::new(), <oauth2::MemoryStorage as Default>::default(), None); let yt = YouTube::new(hyper::Client::new(), auth); let v = yt.videos().insert("snippet", &Default::default()); } #[test] fn helper_test() { use std::default::Default; use oauth2::{Authenticator, DefaultAuthenticatorDelegate, ApplicationSecret, MemoryStorage}; let secret: ApplicationSecret = Default::default(); let auth = Authenticator::new(&secret, DefaultAuthenticatorDelegate, hyper::Client::new(), <MemoryStorage as Default>::default(), None); let mut hub = YouTube::new(hyper::Client::new(), auth); let result = hub.channel_sections().insert() .delegate(&mut DefaultDelegate) .doit(); } } pub struct ChannelSectionMethodsBuilder<'a, C, NC, A> where NC: 'a, C: 'a, A: 'a, { hub: &'a YouTube<C, NC, A>, } impl<'a, C, NC, A> ChannelSectionMethodsBuilder<'a, C, NC, A> { /// Create a builder to help you perform the following task: /// /// Adds a channelSection for the authenticated user's channel. pub fn insert(&self) -> ChannelSectionInsertMethodBuilder<'a, C, NC, A> { ChannelSectionInsertMethodBuilder { hub: self.hub, _delegate: Default::default(), _part: None, } } } pub struct ChannelSectionInsertMethodBuilder<'a, C, NC, A> where NC: 'a, C: 'a, A: 'a, { hub: &'a YouTube<C, NC, A>, _delegate: Option<&'a mut Delegate>, _part: Option<String>, } impl<'a, C, NC, A> ChannelSectionInsertMethodBuilder<'a, C, NC, A> where NC: hyper::net::NetworkConnector, C: BorrowMut<hyper::Client<NC>> + 'a, A: oauth2::GetToken { /// Perform the operation you have build so far. /// TODO: Build actual call pub fn doit(mut self) -> () { let mut params: Vec<(&str, String)> = Vec::with_capacity(1); if self._part.is_none() { self._part = Some("parts from request value".to_string()); } if self._delegate.is_some() { self._delegate.as_mut().unwrap().connection_error(hyper::HttpError::HttpStatusError); } } pub fn delegate(mut self, new_value: &'a mut Delegate) -> ChannelSectionInsertMethodBuilder<'a, C, NC, A> { self._delegate = Some(new_value); self } } pub trait Delegate { /// Called whenever there is an HttpError, usually if there are network problems. /// /// Return retry information. fn connection_error(&mut self, hyper::HttpError) -> oauth2::Retry { oauth2::Retry::Abort } } #[derive(Default)] pub struct DefaultDelegate; impl Delegate for DefaultDelegate {}
use tui::backend::Backend; use tui::Frame; use tui::layout::{Corner, Rect}; use tui::widgets::{Block, Borders, Widget}; use crate::format::MessageFormat; use crate::tui::App; use crate::tui::notification_list::{Notification, NotificationsList}; pub fn draw_retain_tab<B>(f: &mut Frame<B>, area: Rect, app: &App, format: MessageFormat) where B: Backend, { let retained_messages = app .retained_messages .iter() .map(|(_, notification)| Notification::new(notification)); NotificationsList::new(retained_messages) .format(format.payload_format) .block(Block::default().borders(Borders::ALL)) .start_corner(Corner::TopLeft) .render(f, area); }
use super::{AuthTokenExtractor, Response}; use crate::agent; use crate::server::Server; use axum::extract::Extension; use axum::Json; use hyper::StatusCode; use log::{error, info}; use std::sync::Arc; pub async fn promote_handler( auth_token: AuthTokenExtractor, server: Extension<Arc<Server>>, ) -> (StatusCode, Json<Response>) { if auth_token.0 != server.config.server.auth_key { return ( StatusCode::UNAUTHORIZED, Json(Response::error("Invalid auth key".to_string())), ); } info!("Performing promotion..."); server.alert_client.info("Performing promotion..."); match agent::promote(&server.config).await { Ok(()) => { info!("Promotion successful"); server.alert_client.info("Promotion successful"); (StatusCode::OK, Json(Response::success())) } Err(e) => { error!("Error promoting node: {}", e); server.alert_client.error(format!("Error promoting node: {}", e).as_str()); (StatusCode::INTERNAL_SERVER_ERROR, Json(Response::error(e.to_string()))) } } }
mod fish; fn main() { let mut }
#![allow(unused_variables)] #![allow(dead_code)] fn main() { // ----------- Part 01 -------------- struct User { name: String, email: String, dead: bool, } // order isn't required let mut user001 = User { email: String::from("numberOne@example.com"), name: String::from("John Doe"), dead: false, }; // access, modify user001.name; user001.name = String::from("Elizabeth Olsen"); // as return val fn build_user(email: String, name: String) -> User { User { email: email, name: name, dead: true, } } let another_user = build_user( String::from("aol@exp.com"), String::from("Alisha") ); another_user.name; another_user.email; // same name as param fn build_user_shorthand(email: String, name: String) -> User { User { name, // instead of 'name: name' email, dead: false, } } // using other instances' attrs let user002 = User { email: String::from("aa@bb.com"), name: String::from("Eliot Alderson"), dead: user001.dead }; // a much better way using other inst' attrs let user003 = User { email: String::from("cc@dd.com"), ..user002 // all the remaining attrs! }; // ----------- Part 02 -------------- /* Tuple structs which only got types -> tuple got a name -> struct only got type */ struct ColorRGB(i32, i32, i32); struct AxisXY(i32, i32); let rand_color = ColorRGB(255, 255, 255); let rand_point = AxisXY(10, -10); let color_r = rand_color.0; // aha, still 'dot' notation // ----------- Part 03 -------------- /* #TODO More on Chapter 10 1. unit-like structs without any fields :P 2. lifetime about structs */ }
extern crate amethyst; use amethyst::{Application, Event, State, Trans, VirtualKeyCode, WindowEvent}; use amethyst::asset_manager::AssetManager; use amethyst::config::Element; use amethyst::ecs::World; use amethyst::gfx_device::DisplayConfig; use amethyst::renderer::Pipeline; struct GameState; impl State for GameState { fn on_start(&mut self, _: &mut World, _: &mut AssetManager, pipe: &mut Pipeline) { use amethyst::renderer::pass::Clear; use amethyst::renderer::Layer; let clear_layer = Layer::new("main", vec![ Clear::new([0.0, 0.0, 0.0, 1.0]), ]); pipe.layers.push(clear_layer); } fn handle_events(&mut self, events: &[WindowEvent], _: &mut World, _: &mut AssetManager, _: &mut Pipeline) -> Trans { for e in events { match e.payload { Event::KeyboardInput(_, _, Some(VirtualKeyCode::Escape)) => return Trans::Quit, Event::Closed => return Trans::Quit, _ => (), } } Trans::None } } fn main() { let path = "./resources/config.yml"; let cfg = DisplayConfig::from_file(path).expect("Could not find config!"); let mut game = Application::build(GameState, cfg).done(); game.run(); }
use diesel::prelude::*; use std::collections::HashMap; use crate::models::*; use crate::schema::settings::dsl::*; use crate::{database, errors::MetaphraseError}; use actix_web::web; use actix_web::Responder; pub async fn index() -> Result<impl Responder, MetaphraseError> { let connection = database::establish_connection()?; let results = settings .load::<Setting>(&connection) .expect("Error loading settings"); let mut configuration = HashMap::new(); for setting in &results { let settings_for_key = configuration .entry(setting.key.clone()) .or_insert_with(Vec::<String>::new); settings_for_key.push(setting.value.clone()); } Ok(web::Json(configuration)) }
// Copyright 2020 IOTA Stiftung // SPDX-License-Identifier: Apache-2.0 use wasmlib::*; //@formatter:off pub struct Auction { pub color: ScColor, // color of tokens for sale pub creator: ScAgentId, // issuer of start_auction transaction pub deposit: i64, // deposit by auction owner to cover the SC fees pub description: String, // auction description pub duration: i64, // auction duration in minutes pub highest_bid: i64, // the current highest bid amount pub highest_bidder: ScAgentId, // the current highest bidder pub minimum_bid: i64, // minimum bid amount pub num_tokens: i64, // number of tokens for sale pub owner_margin: i64, // auction owner's margin in promilles pub when_started: i64, // timestamp when auction started } //@formatter:on impl Auction { pub fn from_bytes(bytes: &[u8]) -> Auction { let mut decode = BytesDecoder::new(bytes); Auction { color: decode.color(), creator: decode.agent_id(), deposit: decode.int(), description: decode.string(), duration: decode.int(), highest_bid: decode.int(), highest_bidder: decode.agent_id(), minimum_bid: decode.int(), num_tokens: decode.int(), owner_margin: decode.int(), when_started: decode.int(), } } pub fn to_bytes(&self) -> Vec<u8> { let mut encode = BytesEncoder::new(); encode.color(&self.color); encode.agent_id(&self.creator); encode.int(self.deposit); encode.string(&self.description); encode.int(self.duration); encode.int(self.highest_bid); encode.agent_id(&self.highest_bidder); encode.int(self.minimum_bid); encode.int(self.num_tokens); encode.int(self.owner_margin); encode.int(self.when_started); return encode.data(); } } //@formatter:off pub struct Bid { pub amount: i64, // cumulative amount of bids from same bidder pub index: i64, // index of bidder in bidder list pub timestamp: i64, // timestamp of most recent bid } //@formatter:on impl Bid { pub fn from_bytes(bytes: &[u8]) -> Bid { let mut decode = BytesDecoder::new(bytes); Bid { amount: decode.int(), index: decode.int(), timestamp: decode.int(), } } pub fn to_bytes(&self) -> Vec<u8> { let mut encode = BytesEncoder::new(); encode.int(self.amount); encode.int(self.index); encode.int(self.timestamp); return encode.data(); } }
use crate::net::UnixStream; #[cfg(debug_assertions)] use crate::poll::SelectorId; use crate::unix::SocketAddr; use crate::{event, sys, Interest, Registry, Token}; use std::io; use std::os::unix::io::{AsRawFd, FromRawFd, IntoRawFd, RawFd}; use std::os::unix::net; use std::path::Path; /// A non-blocking Unix domain socket server. #[derive(Debug)] pub struct UnixListener { sys: sys::UnixListener, #[cfg(debug_assertions)] selector_id: SelectorId, } impl UnixListener { fn new(sys: sys::UnixListener) -> UnixListener { UnixListener { sys, #[cfg(debug_assertions)] selector_id: SelectorId::new(), } } /// Creates a new `UnixListener` bound to the specified socket. pub fn bind<P: AsRef<Path>>(path: P) -> io::Result<UnixListener> { let sys = sys::UnixListener::bind(path.as_ref())?; Ok(UnixListener::new(sys)) } /// Creates a new `UnixListener` from a standard `net::UnixListener`. /// /// This function is intended to be used to wrap a Unix listener from the /// standard library in the Mio equivalent. The conversion assumes nothing /// about the underlying listener; it is left up to the user to set it in /// non-blocking mode. pub fn from_std(listener: net::UnixListener) -> UnixListener { let sys = sys::UnixListener::from_std(listener); UnixListener { sys, #[cfg(debug_assertions)] selector_id: SelectorId::new(), } } /// Accepts a new incoming connection to this listener. /// /// The call is responsible for ensuring that the listening socket is in /// non-blocking mode. pub fn accept(&self) -> io::Result<(UnixStream, SocketAddr)> { let (sys, sockaddr) = self.sys.accept()?; Ok((UnixStream::new(sys), sockaddr)) } /// Creates a new independently owned handle to the underlying socket. /// /// The returned `UnixListener` is a reference to the same socket that this /// object references. Both handles can be used to accept incoming /// connections and options set on one listener will affect the other. pub fn try_clone(&self) -> io::Result<UnixListener> { let sys = self.sys.try_clone()?; Ok(UnixListener::new(sys)) } /// Returns the local socket address of this listener. pub fn local_addr(&self) -> io::Result<sys::SocketAddr> { self.sys.local_addr() } /// Returns the value of the `SO_ERROR` option. pub fn take_error(&self) -> io::Result<Option<io::Error>> { self.sys.take_error() } } impl event::Source for UnixListener { fn register( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { #[cfg(debug_assertions)] self.selector_id.associate_selector(registry)?; self.sys.register(registry, token, interests) } fn reregister( &mut self, registry: &Registry, token: Token, interests: Interest, ) -> io::Result<()> { self.sys.reregister(registry, token, interests) } fn deregister(&mut self, registry: &Registry) -> io::Result<()> { self.sys.deregister(registry) } } #[cfg(unix)] impl AsRawFd for UnixListener { fn as_raw_fd(&self) -> RawFd { self.sys.as_raw_fd() } } #[cfg(unix)] impl IntoRawFd for UnixListener { fn into_raw_fd(self) -> RawFd { self.sys.into_raw_fd() } } #[cfg(unix)] impl FromRawFd for UnixListener { /// Converts a `std` `RawFd` to a `mio` `UnixListener`. /// /// The caller is responsible for ensuring that the socket is in /// non-blocking mode. unsafe fn from_raw_fd(fd: RawFd) -> UnixListener { UnixListener::new(FromRawFd::from_raw_fd(fd)) } }
#![no_main] #[macro_use] extern crate libfuzzer_sys; extern crate gbl; use gbl::{AppImage, Gbl, P256KeyPair}; #[rustfmt::skip] // FIXME: https://github.com/rust-lang/rustfmt/issues/3234 fuzz_target!(|data: &[u8]| { if let Ok(app_img) = AppImage::parse(data) { let keypair = P256KeyPair::from_pem(include_str!("../../test-data/signing-key")).unwrap(); if let Ok(app_img) = app_img.sign(&keypair) { assert!(app_img.is_signed()); Gbl::from_app_image(app_img).to_bytes(); } } });
use std::{ collections::{ HashMap, VecDeque }, borrow::Borrow }; use super::{ IfExpr, BasicExpr, TypedExpr, ExprValue, BinOp, UnaryOp }; use crate::parser::token::Token; #[derive(Clone, Debug, PartialEq, Eq)] pub enum Type { Unit, Bool, Int, Double, Function(Vec<Type>, Box<Type>) } impl Type { pub fn is_integer(&self) -> bool { match self { Type::Int => true, _ => false } } pub fn is_float(&self) -> bool { match self { Type::Double => true, _ => false } } } /// Structure to store type information, support pushing and pop scopes in a stack #[derive(Clone)] pub struct SymbolTable { scopes: VecDeque<HashMap<String, Type>> } impl SymbolTable { pub fn new() -> SymbolTable { let mut table = SymbolTable { scopes: VecDeque::new() }; //Create the root scope table.scopes.push_back(HashMap::new()); table } pub fn push_scope(&mut self) { self.scopes.push_back(HashMap::new()); } pub fn pop_scope(&mut self) { if self.scopes.len() < 2 { panic!("Attempt to pop root scope from symbol table"); } let _ = self.scopes.pop_back(); } pub fn insert(&mut self, name: &String, kind: &Type) { self.scopes.back_mut().unwrap().insert(name.clone(), kind.clone()); } pub fn lookup<'a>(&'a mut self, name: &String) -> Option<&'a Type> { for scope in self.scopes.iter().rev() { if scope.contains_key(name) { return scope.get(name) } } None } } pub struct TypeChecker { symbol_table: SymbolTable } pub type TypeError = (Type, Type); pub type TypeResult<T> = Result<T, TypeError>; impl TypeChecker { pub fn new(symbol_table: SymbolTable) -> TypeChecker { TypeChecker { symbol_table: symbol_table } } pub fn symbol_table(&mut self) -> &mut SymbolTable { &mut self.symbol_table } pub fn type_check<'a>(&mut self, value: &BasicExpr<'a>) -> TypeResult<Box<TypedExpr<'a>>> { let expr = value.borrow(); let token = value.token().clone(); let typed = match expr { ExprValue::ConstUnit => TypedExpr::const_unit(token), ExprValue::ConstInt(value) => TypedExpr::const_int(token, *value), ExprValue::ConstBool(value) => TypedExpr::const_bool(token, *value), ExprValue::BinOp(op, lhs, rhs) => self.type_check_bin_op(token, *op, lhs, rhs)?, ExprValue::UnaryOp(op, expr) => self.type_check_unary_op(token, *op, expr)?, ExprValue::Block(exprs) => self.type_check_block(token, exprs)?, ExprValue::If(IfExpr { cond, then_expr, else_expr }) => self.type_check_conditional(token, cond, then_expr, else_expr)?, ExprValue::Var(iden) => self.type_check_var(token, iden)?, ExprValue::FunctionApp(name, args) => self.type_check_func_app(token, name, args)?, _ => panic!("") }; Ok(typed) } fn type_check_bin_op<'a>(&mut self, token: Token<'a>, op: BinOp, lhs: &BasicExpr<'a>, rhs: &BasicExpr<'a>) -> TypeResult<Box<TypedExpr<'a>>> { let typed_lhs = self.type_check(lhs)?; let typed_rhs = self.type_check(rhs)?; let result_type = match op { BinOp::Add | BinOp::Sub | BinOp::Mul | BinOp::Div | BinOp::Mod => self.unify_arith(typed_lhs.kind(), typed_rhs.kind()), BinOp::Eq | BinOp::Ne | BinOp::Gt | BinOp::Lt | BinOp::Gte | BinOp::Lte => self.unify_compare(typed_lhs.kind(), typed_rhs.kind()) }?; Ok(TypedExpr::bin_op(token, result_type, op, typed_lhs, typed_rhs)) } fn type_check_unary_op<'a>(&mut self, token: Token<'a>, op: UnaryOp, expr: &BasicExpr<'a>) -> TypeResult<Box<TypedExpr<'a>>> { let typed_expr = self.type_check(expr)?; if *typed_expr.kind() != Type::Int { return Err((typed_expr.kind().clone(), Type::Int)); } Ok(TypedExpr::unary_op(token, Type::Int, op, typed_expr)) } fn type_check_block<'a>(&mut self, token: Token<'a>, exprs: &Vec<Box<BasicExpr<'a>>>) -> TypeResult<Box<TypedExpr<'a>>> { //Blocks create a new scope self.symbol_table.push_scope(); let typed_exprs = exprs.iter().map(|e| self.type_check(e)).collect::<TypeResult<Vec<Box<TypedExpr<'a>>>>>()?; self.symbol_table.pop_scope(); Ok(TypedExpr::block(token, typed_exprs)) } fn type_check_conditional<'a>(&mut self, token: Token<'a>, cond_expr: &BasicExpr<'a>, then_expr: &BasicExpr<'a>, else_expr: &BasicExpr<'a>) -> TypeResult<Box<TypedExpr<'a>>> { let typed_cond = self.type_check(cond_expr)?; let typed_then = self.type_check(then_expr)?; let typed_else = self.type_check(else_expr)?; //Conditional expression must be a boolean if *typed_cond.kind() != Type::Bool { return Err((typed_cond.kind().clone(), Type::Bool)); } //The then and else expressions must have the same type if typed_then.kind() != typed_else.kind() { return Err((typed_then.kind().clone(), typed_else.kind().clone())); } Ok(TypedExpr::conditional(token, typed_cond, typed_then, typed_else)) } fn type_check_var<'a>(&mut self, token: Token<'a>, iden: &String) -> TypeResult<Box<TypedExpr<'a>>> { let var_type = self.symbol_table.lookup(iden).expect("Undefined variable").clone(); Ok(TypedExpr::var(token, iden, var_type)) } fn type_check_func_app<'a>(&mut self, token: Token<'a>, iden: &String, args: &Vec<Box<BasicExpr<'a>>>) -> TypeResult<Box<TypedExpr<'a>>> { let typed_args = args.iter().map(|expr| self.type_check(expr)).collect::<TypeResult<Vec<Box<TypedExpr<'a>>>>>()?; let func_type = self.symbol_table.lookup(iden).expect("Undefined function").clone(); let mut ret_type = Type::Unit; if let Type::Function(arg_types, ret) = func_type { if arg_types.len() != args.len() { panic!("Function argument count mismatch"); } //Type check the passed args vs arg types let passed_types = typed_args.iter().map(|expr| expr.kind().clone()); let zipped = passed_types.zip(arg_types.iter().map(|t| t.clone())).collect::<Vec<(Type, Type)>>(); for (a, b) in zipped { if a != b { panic!("Mismatched function args"); } } ret_type = *ret.clone(); } else { panic!("Attempt to call a non-function"); } Ok(TypedExpr::function_app(token, ret_type, iden.clone(), typed_args)) } fn unify_arith<'a>(&self, lhs: &Type, rhs: &Type) -> TypeResult<Type> { match (lhs, rhs) { (Type::Int, Type::Int) => Ok(Type::Int), (Type::Double, Type::Double) => Ok(Type::Double), (Type::Int, Type::Double) | (Type::Double, Type::Int) => Ok(Type::Double), _ => Err((lhs.clone(), rhs.clone())) } } fn unify_compare<'a>(&self, lhs: &Type, rhs: &Type) -> TypeResult<Type> { match (lhs, rhs) { (Type::Int, Type::Int) | (Type::Double, Type::Double) | (Type::Int, Type::Double) | (Type::Double, Type::Int) => Ok(Type::Bool), _ => Err((lhs.clone(), rhs.clone())) } } }
use indexmap::IndexMap; use crate::pos::Spanned; #[derive(Debug, Clone)] pub enum TypeData { Identifier(String), Record(IndexMap<String, String>), Array(String), } pub type Type = Spanned<TypeData>; #[derive(Debug, Clone)] pub struct TypeDeclData { pub name: String, pub decl: Type, } pub type TypeDecl = Spanned<TypeDeclData>; #[derive(Debug, Clone)] pub struct VariableData { pub name: String, pub ty_dec: Option<String>, pub init: Expression, } pub type Variable = Spanned<VariableData>; #[derive(Debug, Clone)] pub struct FunctionData { pub name: String, pub fields: IndexMap<String, Spanned<String>>, pub ret_type: Option<String>, pub body: Expression, } pub type Function = Spanned<FunctionData>; #[derive(Debug, Clone)] pub enum DeclarationData { Type(Vec<TypeDecl>), Variable(Variable), Function(Vec<Function>), } pub type Declaration = Spanned<DeclarationData>; #[derive(Debug, Clone, Copy)] pub enum BinaryOperatorData { Multiply, Divide, Add, Subtract, Equal, NotEqual, Greater, GreaterEqual, Less, LessEqual, And, Or, } pub type BinaryOperator = Spanned<BinaryOperatorData>; #[derive(Debug, Clone, Copy)] pub enum UnaryOperatorData { Negate, } pub type UnaryOperator = Spanned<UnaryOperatorData>; #[derive(Debug, Clone)] pub enum SubscriptData { Record(String), Array(Expression), } pub type Subscript = Spanned<SubscriptData>; #[derive(Debug, Clone)] pub struct LvalueData { pub name: String, pub subscripts: Vec<Subscript>, } pub type Lvalue = Spanned<LvalueData>; #[derive(Debug, Clone)] pub enum ExpressionData { Nil, Break, Void, Integer(isize), String(String), Let(Vec<Declaration>, Vec<Expression>), Sequence(Vec<Expression>), FunctionCall(String, Vec<Expression>), Assign(Lvalue, Box<Expression>), Array { name: String, size: Box<Expression>, init: Box<Expression>, }, Record { name: String, fields: IndexMap<String, Expression>, }, BinaryOperation { op: BinaryOperator, lhs: Box<Expression>, rhs: Box<Expression>, }, UnaryOperation(UnaryOperator, Box<Expression>), While { predicate: Box<Expression>, body: Box<Expression>, }, If { predicate: Box<Expression>, consequent: Box<Expression>, alternative: Option<Box<Expression>>, }, For { binding: String, lower: Box<Expression>, upper: Box<Expression>, body: Box<Expression>, }, Lvalue(Lvalue), } pub type Expression = Spanned<ExpressionData>;
pub mod attestations;
pub mod validators;
use crate::{ cmd::oui::*, traits::{TxnEnvelope, TxnFee, TxnSign, TxnStakingFee}, }; use helium_api::ouis; use structopt::StructOpt; /// Allocates an Organizational Unique Identifier (OUI) which /// identifies endpoints for packets to sent to The transaction is not /// submitted to the system unless the '--commit' option is given. #[derive(Debug, StructOpt)] pub struct Create { /// The address(es) of the router to send packets to #[structopt(long = "address", short = "a", number_of_values(1))] addresses: Vec<PublicKey>, /// Optionally indicate last OUI. Wallet will determine /// this using API otherwise. #[structopt(long)] last_oui: Option<u64>, /// Initial device membership filter in base64 encoded form. /// Dummy filter default is given, but OUI addresses may /// overwrite this at any time. #[structopt( long, default_value = "wVwCiewtCpEKAAAAAAAAAAAAcCK3fwAAAAAAAAAAAABI7IQOAHAAAAAAAAAAAAAAAQAAADBlAAAAAAAAAAAAADEAAAA2AAAAOgAAAA" )] filter: String, /// Requested subnet size. Must be a value between 8 and 65,536 /// and a power of two. #[structopt(long)] subnet_size: u32, /// Payer for the transaction (B58 address). If not specified the /// wallet is used. #[structopt(long)] payer: Option<PublicKey>, /// Commit the transaction to the API. If the staking server is /// used as the payer the transaction must first be submitted to /// the staking server for signing and the result submitted ot the /// API. #[structopt(long)] commit: bool, } impl Create { pub async fn run(&self, opts: Opts) -> Result { let password = get_password(false)?; let wallet = load_wallet(opts.files)?; let keypair = wallet.decrypt(password.as_bytes())?; let wallet_key = keypair.public_key(); let client = new_client(api_url(wallet.public_key.network)); let oui = if let Some(oui) = self.last_oui { oui } else { ouis::last(&client).await?.oui }; let mut txn = BlockchainTxnOuiV1 { addresses: map_addresses(self.addresses.clone(), |v| v.to_vec())?, owner: keypair.public_key().into(), payer: self.payer.as_ref().map_or(vec![], |v| v.into()), oui, fee: 0, staking_fee: 1, owner_signature: vec![], payer_signature: vec![], requested_subnet_size: self.subnet_size, filter: base64::decode(&self.filter)?, }; let fees = &get_txn_fees(&client).await?; txn.fee = txn.txn_fee(fees)?; txn.staking_fee = txn.txn_staking_fee(fees)?; txn.owner_signature = txn.sign(&keypair)?; let envelope = txn.in_envelope(); match self.payer.as_ref() { key if key == Some(wallet_key) || key.is_none() => { // Payer is the wallet submit if ready to commit let status = maybe_submit_txn(self.commit, &client, &envelope).await?; print_txn(&txn, &envelope, &status, opts.format) } _ => { // Payer is something else. // can't commit this transaction but we can display it print_txn(&txn, &envelope, &None, opts.format) } } } } fn print_txn( txn: &BlockchainTxnOuiV1, envelope: &BlockchainTxn, status: &Option<PendingTxnStatus>, format: OutputFormat, ) -> Result { match format { OutputFormat::Table => { ptable!( ["Key", "Value"], ["Previous OUI", txn.oui], ["Requested Subnet Size", txn.requested_subnet_size], [ "Addresses", map_addresses(txn.addresses.clone(), |v| v.to_string())?.join("\n") ], ["Hash", status_str(status)] ); print_footer(status) } OutputFormat::Json => { let table = json!({ "previous_oui": txn.oui, "addresses": map_addresses(txn.addresses.clone(), |v| v.to_string())?, "requested_subnet_size": txn.requested_subnet_size, "hash": status_json(status), "txn": envelope.to_b64()?, }); print_json(&table) } } }
/// Should check if the inputted ABI's are valid /// Convert the String to a list of ABI's pub fn input_to_abi_vec(input: &str, bp: bool) -> Vec<String> { if input.is_empty() { return vec![]; } let list: Vec<String> = input.split(",").map(|s| s.to_string()).collect(); return parse_abi_for_buildsystem(list, bp); } /// We customize ABI based on build system. e.g. makefile uses arm64-v8a, blueprint uses arm64 pub fn parse_abi_for_buildsystem(dirty_abis: Vec<String>, bp: bool) -> Vec<String> { let mut filtered_list: Vec<String> = Vec::new(); for (_i, abi) in dirty_abis.iter().enumerate() { // If there's a default architecture supplied but it's not a valid one // e.g a typo, exit immediately, see issue #1 if !VALID_ABI.contains(&abi.as_ref()) { panic!( "{} is not a valid ABI. Use commas to separate them e.g armeabi-v7a,arm64-v8a \n\n Must be one of {:?}", abi, VALID_ABI ); } if filtered_list.contains(abi) { println!("{} is already passed once, ignoring", abi); continue; } // small mistakes that can be passed through the cli, correct them if !bp { if abi == "arm64" { filtered_list.push("arm64-v8a".to_string()); } else if abi == "arm" { filtered_list.push("armeabi-v7a".to_string()); } else { filtered_list.push(abi.to_string()); } } else { if abi == "arm64-v8a" { filtered_list.push("arm64".to_string()); } else if abi == "armeabi-v7a" { filtered_list.push("arm".to_string()); } else { filtered_list.push(abi.to_string()); } } } filtered_list } pub const VALID_ABI: &[&str] = &["armeabi-v7a", "arm64-v8a", "x86", "arm", "arm64", "x86_64"];
fn main() { let x: i32 = 5; }
use spin::RwLock; use std::collections::HashMap; use rand::prelude::*; use rand::rngs::OsRng; use x25519_dalek::PublicKey; use x25519_dalek::StaticSecret; use crate::messages; use crate::noise; use crate::peer::Peer; use crate::types::*; pub struct Device<T> { pub sk: StaticSecret, // static secret key pub pk: PublicKey, // static public key pk_map: HashMap<[u8; 32], Peer<T>>, // public key -> peer state id_map: RwLock<HashMap<u32, [u8; 32]>>, // receiver ids -> public key } /* A mutable reference to the device needs to be held during configuration. * Wrapping the device in a RwLock enables peer config after "configuration time" */ impl<T> Device<T> where T: Copy, { /// Initialize a new handshake state machine /// /// # Arguments /// /// * `sk` - x25519 scalar representing the local private key pub fn new(sk: StaticSecret) -> Device<T> { Device { pk: PublicKey::from(&sk), sk: sk, pk_map: HashMap::new(), id_map: RwLock::new(HashMap::new()), } } /// Add a new public key to the state machine /// To remove public keys, you must create a new machine instance /// /// # Arguments /// /// * `pk` - The public key to add /// * `identifier` - Associated identifier which can be used to distinguish the peers pub fn add(&mut self, pk: PublicKey, identifier: T) -> Result<(), ConfigError> { // check that the pk is not added twice if let Some(_) = self.pk_map.get(pk.as_bytes()) { return Err(ConfigError::new("Duplicate public key")); }; // check that the pk is not that of the device if *self.pk.as_bytes() == *pk.as_bytes() { return Err(ConfigError::new( "Public key corresponds to secret key of interface", )); } // map : pk -> new index self.pk_map.insert( *pk.as_bytes(), Peer::new(identifier, pk, self.sk.diffie_hellman(&pk)), ); Ok(()) } /// Remove a peer by public key /// To remove public keys, you must create a new machine instance /// /// # Arguments /// /// * `pk` - The public key of the peer to remove /// /// # Returns /// /// The call might fail if the public key is not found pub fn remove(&mut self, pk: PublicKey) -> Result<(), ConfigError> { // take write-lock on receive id table let mut id_map = self.id_map.write(); // remove the peer self.pk_map .remove(pk.as_bytes()) .ok_or(ConfigError::new("Public key not in device"))?; // pruge the id map (linear scan) id_map.retain(|_, v| v != pk.as_bytes()); Ok(()) } /// Add a psk to the peer /// /// # Arguments /// /// * `pk` - The public key of the peer /// * `psk` - The psk to set / unset /// /// # Returns /// /// The call might fail if the public key is not found pub fn psk(&mut self, pk: PublicKey, psk: Option<Psk>) -> Result<(), ConfigError> { match self.pk_map.get_mut(pk.as_bytes()) { Some(mut peer) => { peer.psk = match psk { Some(v) => v, None => [0u8; 32], }; Ok(()) } _ => Err(ConfigError::new("No such public key")), } } /// Release an id back to the pool /// /// # Arguments /// /// * `id` - The (sender) id to release pub fn release(&self, id: u32) { let mut m = self.id_map.write(); debug_assert!(m.contains_key(&id), "Releasing id not allocated"); m.remove(&id); } /// Begin a new handshake /// /// # Arguments /// /// * `pk` - Public key of peer to initiate handshake for pub fn begin(&self, pk: &PublicKey) -> Result<Vec<u8>, HandshakeError> { match self.pk_map.get(pk.as_bytes()) { None => Err(HandshakeError::UnknownPublicKey), Some(peer) => { let sender = self.allocate(peer); noise::create_initiation(self, peer, sender) } } } /// Process a handshake message. /// /// # Arguments /// /// * `msg` - Byte slice containing the message (untrusted input) pub fn process(&self, msg: &[u8]) -> Result<Output<T>, HandshakeError> { match msg.get(0) { Some(&messages::TYPE_INITIATION) => { // consume the initiation let (peer, st) = noise::consume_initiation(self, msg)?; // allocate new index for response let sender = self.allocate(peer); // create response (release id on error) noise::create_response(peer, sender, st).map_err(|e| { self.release(sender); e }) } Some(&messages::TYPE_RESPONSE) => noise::consume_response(self, msg), _ => Err(HandshakeError::InvalidMessageFormat), } } // Internal function // // Return the peer associated with the public key pub(crate) fn lookup_pk(&self, pk: &PublicKey) -> Result<&Peer<T>, HandshakeError> { self.pk_map .get(pk.as_bytes()) .ok_or(HandshakeError::UnknownPublicKey) } // Internal function // // Return the peer currently associated with the receiver identifier pub(crate) fn lookup_id(&self, id: u32) -> Result<&Peer<T>, HandshakeError> { let im = self.id_map.read(); let pk = im.get(&id).ok_or(HandshakeError::UnknownReceiverId)?; match self.pk_map.get(pk) { Some(peer) => Ok(peer), _ => unreachable!(), // if the id-lookup succeeded, the peer should exist } } // Internal function // // Allocated a new receiver identifier for the peer fn allocate(&self, peer: &Peer<T>) -> u32 { let mut rng = OsRng::new().unwrap(); loop { let id = rng.gen(); // check membership with read lock if self.id_map.read().contains_key(&id) { continue; } // take write lock and add index let mut m = self.id_map.write(); if !m.contains_key(&id) { m.insert(id, *peer.pk.as_bytes()); return id; } } } } #[cfg(test)] mod tests { use super::*; use hex; use messages::*; #[test] fn handshake() { // generate new keypairs let mut rng = OsRng::new().unwrap(); let sk1 = StaticSecret::new(&mut rng); let pk1 = PublicKey::from(&sk1); let sk2 = StaticSecret::new(&mut rng); let pk2 = PublicKey::from(&sk2); // intialize devices on both ends let mut dev1 = Device::new(sk1); let mut dev2 = Device::new(sk2); dev1.add(pk2, 1337).unwrap(); dev2.add(pk1, 2600).unwrap(); // do a few handshakes for i in 0..10 { println!("handshake : {}", i); // create initiation let msg1 = dev1.begin(&pk2).unwrap(); println!("msg1 = {}", hex::encode(&msg1[..])); println!("msg1 = {:?}", Initiation::parse(&msg1[..]).unwrap()); // process initiation and create response let (_, msg2, ks_r) = dev2.process(&msg1).unwrap(); let ks_r = ks_r.unwrap(); let msg2 = msg2.unwrap(); println!("msg2 = {}", hex::encode(&msg2[..])); println!("msg2 = {:?}", Response::parse(&msg2[..]).unwrap()); assert!(!ks_r.confirmed, "Responders key-pair is confirmed"); // process response and obtain confirmed key-pair let (_, msg3, ks_i) = dev1.process(&msg2).unwrap(); let ks_i = ks_i.unwrap(); assert!(msg3.is_none(), "Returned message after response"); assert!(ks_i.confirmed, "Initiators key-pair is not confirmed"); assert_eq!(ks_i.send, ks_r.recv, "KeyI.send != KeyR.recv"); assert_eq!(ks_i.recv, ks_r.send, "KeyI.recv != KeyR.send"); dev1.release(ks_i.send.id); dev2.release(ks_r.send.id); } } }
//! **N**ox's **A**bstract **A**bstract **M**achine //! //! Highly experimental framework to design higher-level virtual machines //! fearlessly. #![no_std] #[cfg(feature = "alloc")] extern crate alloc; pub mod builder; pub mod builtins; pub mod cpu; pub mod debug_info; mod id; pub mod tape; use crate::builder::{Build, Builder, Instruction}; use crate::builtins::Unreachable; use crate::cpu::{Addr, Dispatch, Halt}; use crate::debug_info::{DebugInfo, Dump, Dumper}; use crate::id::Id; use crate::tape::AsClearedWriter; use core::fmt::{self, Debug}; use core::marker::PhantomData as marker; use core::mem::{self, MaybeUninit}; use core::ops::Deref; use stable_deref_trait::StableDeref; /// A compiled program. pub struct Program<Cpu, Tape, Code> { cpu: Cpu, tape: Tape, debug_info: DebugInfo, code: Code, not_sync: marker<*mut ()>, } impl<Cpu, Tape, Code> Program<Cpu, Tape, Code> where Cpu: for<'ram> Dispatch<<<Code as Deref>::Target as Build<Cpu>>::Ram>, Tape: AsClearedWriter, Code: StableDeref, <Code as Deref>::Target: Build<Cpu>, { /// Returns a new program built from the given code. pub fn new( cpu: Cpu, mut tape: Tape, code: Code, ) -> Result<Program<Cpu, Tape, Code>, <<Code as Deref>::Target as Build<Cpu>>::Error> { let mut builder = Builder::new(cpu, &mut tape); code.build(&mut builder)?; builder.emit(Unreachable)?; unsafe { let debug_info = builder.into_debug_info(); Ok(Self { cpu, tape, debug_info, code, not_sync: marker, }) } } /// Runs the program with some RAM. pub fn run(&self, ram: &mut <<Code as Deref>::Target as Build<Cpu>>::Ram) { let tape = self.tape.as_ref(); unsafe { let runner = Runner::new(tape); let addr = Addr { token: &*(tape.as_ptr() as *const _), id: runner.id, }; self.cpu.dispatch(addr, runner, ram) } } /// Gets a reference to the code used by the program. #[inline(always)] pub fn code(&self) -> &Code { &self.code } } impl<Cpu, Tape, Code> fmt::Debug for Program<Cpu, Tape, Code> where Cpu: Debug, Code: Debug, Tape: AsRef<[MaybeUninit<usize>]>, { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { let dumper = unsafe { Dumper::new(self.tape.as_ref()) }; fmt.debug_struct("Machine") .field("cpu", &self.cpu) .field("code", &self.code) .field("tape", &dumper.debug(&self.debug_info)) .finish() } } /// How to execute an operation, the main piece of code for end users. pub trait Execute<'tape, Ram>: 'tape + Copy + Dump<'tape> + Sized where Ram: ?Sized, { /// Executes the operation. /// /// Operations are free to mutate both the RAM and the environment provided /// when the program was run. /// /// Use the runner to resolve tape offsets stored in the operation, and the /// program counter to continue execution to the next operation. /// /// **Note:** As the CPU is the entity responsible for dispatching /// operations and most CPUs wrap calls to that function in a separate /// unsafe function, users should probably mark this method as inline. fn execute(pc: Pc<'tape, Self>, runner: Runner<'tape>, ram: &mut Ram) -> Destination<'tape>; } /// The runner, which allows resolving tape offsets during execution. #[derive(Clone, Copy)] pub struct Runner<'tape> { tape: *const u8, #[cfg(debug_assertions)] len: usize, id: Id<'tape>, } impl<'tape> Runner<'tape> { /// Resolves a tape offset to a physical address. #[inline(always)] pub fn resolve_offset(self, offset: Offset<'tape>) -> Addr<'tape> { debug_assert!(offset.value < self.len); debug_assert!(offset.value % mem::align_of::<usize>() == 0); unsafe { let byte = self.tape.add(offset.value); Addr { token: &*(byte as *const _), id: offset.id, } } } /// Returns the error token to return from the program altogether. #[inline(always)] pub fn halt(self) -> Halt<'tape> { Halt { id: self.id } } #[inline(always)] fn new(tape: &'tape [MaybeUninit<usize>]) -> Self { Self { tape: tape.as_ptr() as *const u8, #[cfg(debug_assertions)] len: tape.len().wrapping_mul(mem::size_of::<usize>()), id: Id::default(), } } } /// The program counter. /// /// This represents the current position of the CPU in the program and /// lets the user access the contents of the operation currently executed. #[repr(transparent)] pub struct Pc<'tape, Op> { instruction: &'tape Instruction<Op>, id: Id<'tape>, } impl<'tape, Op> Pc<'tape, Op> { /// Returns the physical address of the operation currently executed. #[inline(always)] pub fn current(self) -> Addr<'tape> { Addr { token: &self.instruction.token, id: self.id, } } /// Returns the physical address of the next operation in the program. #[inline(always)] pub fn next(self) -> Addr<'tape> { unsafe { let end = (self.instruction as *const Instruction<Op>).add(1); Addr { token: &*(end as *const _), id: self.id, } } } /// Creates a new program counter out of a physical address. /// /// This is only useful for CPU (remember, virtual ones) designers. #[inline(always)] pub unsafe fn from_addr(addr: Addr<'tape>) -> Self { Self { instruction: &*(addr.token as *const _ as *const _), id: addr.id, } } } impl<'tape, Op> Clone for Pc<'tape, Op> { #[inline(always)] fn clone(&self) -> Self { *self } } impl<'tape, Op> Copy for Pc<'tape, Op> {} impl<'tape, Op> Deref for Pc<'tape, Op> { type Target = Op; #[inline(always)] fn deref(&self) -> &Self::Target { &self.instruction.op } } /// A destination for the next step the CPU should take. /// /// This type alias only exists so that simple programs need only one import /// instead of two. pub type Destination<'tape> = Result<Addr<'tape>, Halt<'tape>>; /// A tape offset. /// /// Offsets are always guaranteed to refer to the start of an operation /// in the program. They can be converted to `usize` through the `From` trait. #[derive(Clone, Copy)] #[repr(transparent)] pub struct Offset<'tape> { value: usize, id: Id<'tape>, } impl<'tape> From<Offset<'tape>> for usize { #[inline(always)] fn from(offset: Offset<'tape>) -> usize { offset.value } } impl<'tape> Debug for Offset<'tape> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { write!(fmt, "[base + {}]", self.value) } }