text
stringlengths
8
4.13M
/* * 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 */ use reqwest; use crate::apis::ResponseContent; use super::{Error, configuration}; /// struct for typed errors of method `create_host_tags` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum CreateHostTagsError { Status403(crate::models::ApiErrorResponse), Status404(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// struct for typed errors of method `delete_host_tags` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum DeleteHostTagsError { Status403(crate::models::ApiErrorResponse), Status404(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// struct for typed errors of method `get_host_tags` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum GetHostTagsError { Status403(crate::models::ApiErrorResponse), Status404(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// struct for typed errors of method `list_host_tags` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum ListHostTagsError { Status403(crate::models::ApiErrorResponse), Status404(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// struct for typed errors of method `update_host_tags` #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(untagged)] pub enum UpdateHostTagsError { Status403(crate::models::ApiErrorResponse), Status404(crate::models::ApiErrorResponse), UnknownValue(serde_json::Value), } /// This endpoint allows you to add new tags to a host, optionally specifying where these tags come from. pub async fn create_host_tags(configuration: &configuration::Configuration, host_name: &str, body: crate::models::HostTags, source: Option<&str>) -> Result<crate::models::HostTags, Error<CreateHostTagsError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/tags/hosts/{host_name}", configuration.base_path, host_name=crate::apis::urlencode(host_name)); let mut local_var_req_builder = local_var_client.post(local_var_uri_str.as_str()); if let Some(ref local_var_str) = source { local_var_req_builder = local_var_req_builder.query(&[("source", &local_var_str.to_string())]); } if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; local_var_req_builder = local_var_req_builder.json(&body); let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<CreateHostTagsError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// This endpoint allows you to remove all user-assigned tags for a single host. pub async fn delete_host_tags(configuration: &configuration::Configuration, host_name: &str, source: Option<&str>) -> Result<(), Error<DeleteHostTagsError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/tags/hosts/{host_name}", configuration.base_path, host_name=crate::apis::urlencode(host_name)); let mut local_var_req_builder = local_var_client.delete(local_var_uri_str.as_str()); if let Some(ref local_var_str) = source { local_var_req_builder = local_var_req_builder.query(&[("source", &local_var_str.to_string())]); } if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { Ok(()) } else { let local_var_entity: Option<DeleteHostTagsError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// Return the list of tags that apply to a given host. pub async fn get_host_tags(configuration: &configuration::Configuration, host_name: &str, source: Option<&str>) -> Result<crate::models::HostTags, Error<GetHostTagsError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/tags/hosts/{host_name}", configuration.base_path, host_name=crate::apis::urlencode(host_name)); let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); if let Some(ref local_var_str) = source { local_var_req_builder = local_var_req_builder.query(&[("source", &local_var_str.to_string())]); } if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<GetHostTagsError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// Return a mapping of tags to hosts for your whole infrastructure. pub async fn list_host_tags(configuration: &configuration::Configuration, source: Option<&str>) -> Result<crate::models::TagToHosts, Error<ListHostTagsError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/tags/hosts", configuration.base_path); let mut local_var_req_builder = local_var_client.get(local_var_uri_str.as_str()); if let Some(ref local_var_str) = source { local_var_req_builder = local_var_req_builder.query(&[("source", &local_var_str.to_string())]); } if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<ListHostTagsError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } } /// This endpoint allows you to update/replace all tags in an integration source with those supplied in the request. pub async fn update_host_tags(configuration: &configuration::Configuration, host_name: &str, body: crate::models::HostTags, source: Option<&str>) -> Result<crate::models::HostTags, Error<UpdateHostTagsError>> { let local_var_client = &configuration.client; let local_var_uri_str = format!("{}/api/v1/tags/hosts/{host_name}", configuration.base_path, host_name=crate::apis::urlencode(host_name)); let mut local_var_req_builder = local_var_client.put(local_var_uri_str.as_str()); if let Some(ref local_var_str) = source { local_var_req_builder = local_var_req_builder.query(&[("source", &local_var_str.to_string())]); } if let Some(ref local_var_user_agent) = configuration.user_agent { local_var_req_builder = local_var_req_builder.header(reqwest::header::USER_AGENT, local_var_user_agent.clone()); } if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-API-KEY", local_var_value); }; if let Some(ref local_var_apikey) = configuration.api_key { let local_var_key = local_var_apikey.key.clone(); let local_var_value = match local_var_apikey.prefix { Some(ref local_var_prefix) => format!("{} {}", local_var_prefix, local_var_key), None => local_var_key, }; local_var_req_builder = local_var_req_builder.header("DD-APPLICATION-KEY", local_var_value); }; local_var_req_builder = local_var_req_builder.json(&body); let local_var_req = local_var_req_builder.build()?; let local_var_resp = local_var_client.execute(local_var_req).await?; let local_var_status = local_var_resp.status(); let local_var_content = local_var_resp.text().await?; if !local_var_status.is_client_error() && !local_var_status.is_server_error() { serde_json::from_str(&local_var_content).map_err(Error::from) } else { let local_var_entity: Option<UpdateHostTagsError> = serde_json::from_str(&local_var_content).ok(); let local_var_error = ResponseContent { status: local_var_status, content: local_var_content, entity: local_var_entity }; Err(Error::ResponseError(local_var_error)) } }
#[macro_use] extern crate serde_derive; #[macro_use] extern crate envy; extern crate dotenv; #[macro_use] extern crate lazy_static; use dotenv::dotenv; use std::collections::HashMap; use std::env; use std::path::Path; /// # Example environment variables. /// /// The simple program which lookups for 3 environment variables /// (`ENV_VAR_ONE`, `ENV_VAR_TWO`, `ENV_VAR_THREE`) and for each variable prints: /// - `<absent>` if variable is not defined; /// - `<empty>` if variable is defined but is empty string; /// - value of variable in other cases. /// /// The module contains two functions: variant_envy and variant_env. /// The function of variant_envy uses crate envy. /// The function of variant_envy uses crate env. /// The test is used crate dotenv. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// /// use environment_variables::*; /// /// if let Ok(path) = env::current_dir().and_then(|a| Ok(a.join(".env"))) { /// dotenv::from_path(path); /// } else { /// assert!(false); /// } /// /// variant_envy(); /// ``` mod environment_variables { use super::*; /// The structure contains the expected environment variables. #[derive(Deserialize, Debug, PartialEq)] #[serde(default)] pub struct Config { pub one: String, pub two: String, pub three: String, #[serde(skip)] pub index: i32, } /// Implement an iterator to enumerate environment variables. impl Iterator for Config { type Item = (String, String); fn next(&mut self) -> Option<Self::Item> { self.index -= 1; match self.index { 0 => Some((String::from("ENV_VAR_ONE"), self.one.to_string())), 1 => Some((String::from("ENV_VAR_TWO"), self.two.to_string())), 2 => Some((String::from("ENV_VAR_THREE"), self.three.to_string())), _ => None, } } } /// Implement a trait Default. impl Default for Config { fn default() -> Self { Config { one: Default::default(), two: Default::default(), three: Default::default(), index: 3, } } } /// The function that uses the crate env. /// Outputs the environment variables to the `stdout` stream. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// /// use environment_variables::*; /// /// if let Ok(path) = env::current_dir().and_then(|a| Ok(a.join(".env"))) { /// dotenv::from_path(path); /// } else { /// assert!(false); /// } /// /// variant_env(); /// ``` pub fn variant_env() { let mut vars: [&str; 3] = ["ENV_VAR_THREE", "ENV_VAR_TWO", "ENV_VAR_ONE"]; let vars_map: HashMap<String, String> = vars .into_iter() .map(|&var| { env::var_os(var).map_or((var.to_uppercase(), String::from("<absent>")), |value| { ( var.to_uppercase(), value .into_string() .and_then(|string| { if string.is_empty() { Ok(String::from("<empty>")) } else { Ok(string) } }) .unwrap(), ) }) }) .collect(); for (key, val) in vars_map.iter() { println!("{}: {}", key, val); } } /// The function that uses the crate envy. /// Outputs the environment variables to the `stdout` stream. /// /// ## Examples /// /// Basic usage: /// /// ```rust /// /// use environment_variables::*; /// /// if let Ok(path) = env::current_dir().and_then(|a| Ok(a.join(".env"))) { /// dotenv::from_path(path); /// } else { /// assert!(false); /// } /// /// variant_envy(); /// ``` pub fn variant_envy() { let vars_map: HashMap<String, String> = envy::prefixed("ENV_VAR_") .from_env::<Config>() .and_then(|vars_map| { Ok(vars_map .into_iter() .map(|(key, value)| { env::var_os(&key).map_or( (key.to_uppercase(), String::from("<absent>")), |value| { ( key.to_uppercase(), value .into_string() .and_then(|string| { if string.is_empty() { Ok(String::from("<empty>")) } else { Ok(string) } }) .unwrap(), ) }, ) }) .collect()) }) .unwrap(); for (key, val) in vars_map.iter() { println!("{}: {}", key, val); } } #[cfg(test)] mod test { use super::*; #[test] fn test_env() { if let Ok(path) = env::current_dir().and_then(|a| Ok(a.join(".env"))) { dotenv::from_path(path); } else { assert!(false); } variant_env(); assert!(true); } #[test] fn test_envy() { if let Ok(path) = env::current_dir().and_then(|a| Ok(a.join(".env"))) { dotenv::from_path(path); } else { assert!(false); } variant_envy(); assert!(true); } } } fn main() { use environment_variables::*; if let Ok(path) = env::current_dir().and_then(|a| Ok(a.join(".env"))) { dotenv::from_path(path); } else { assert!(false); } println!("Variant crate envy:\n"); variant_envy(); println!("\nVariant std::env:\n"); variant_env(); }
use parenchyma::error::Result; use parenchyma::extension_package::Dependency; use parenchyma::frameworks::NativeContext as Context; use parenchyma::tensor::SharedTensor; use super::super::{Extension, Package}; use super::super::extension_package::{Backward, Forward}; impl<P> Backward for Context<P> where P: Dependency<Package> { fn log_softmax_grad( self: &Self, x: &SharedTensor, x_diff: &SharedTensor, result_diff: &mut SharedTensor) -> Result { let x_slice = x.as_slice().unwrap(); let x_diff_slice = x_diff.as_slice().unwrap(); let mut sum = 0.0; for &grad_val in x_diff_slice.iter() { sum += grad_val; } let res = x_slice.iter().zip(x_diff_slice.iter()) .map(|(x_val, x_diff_val)| { x_diff_val - x_val.exp() * sum }); result_diff.write_iter(res)?; Ok(()) } fn relu_grad( self: &Self, x: &SharedTensor, x_diff: &SharedTensor, result: &SharedTensor, result_diff: &mut SharedTensor) -> Result { let res = x.as_slice().unwrap().iter() .zip(x_diff.as_slice().unwrap().iter()) .map(|(x, dx)| if *x > 0.0 { *dx } else { 0.0 }); result_diff.write_iter(res)?; Ok(()) } fn sigmoid_grad( self: &Self, x: &SharedTensor, x_diff: &SharedTensor, result: &SharedTensor, result_diff: &mut SharedTensor) -> Result { let res = x.as_slice().unwrap().iter().zip(x_diff.as_slice().unwrap().iter()) .map(|(t, dt)| *t * (1.0 -*t) * *dt); result_diff.write_iter(res)?; Ok(()) } fn softmax_grad( self: &Self, x: &SharedTensor, x_diff: &SharedTensor, result_diff: &mut SharedTensor) -> Result { let mut dot = 0.0; let sig_data_slice = x.as_slice().unwrap(); let sig_dx_slice = x_diff.as_slice().unwrap(); for (t, dt) in sig_data_slice.iter().zip(sig_dx_slice.iter()) { dot += t * dt; } let res = sig_data_slice.iter().zip(sig_dx_slice.iter()).map(|(t, dt)| t * (dt - dot)); result_diff.write_iter(res)?; Ok(()) } fn tanh_grad( self: &Self, x: &SharedTensor, x_diff: &SharedTensor, result: &SharedTensor, result_diff: &mut SharedTensor) -> Result { let res = x.as_slice().unwrap().iter() .zip(x_diff.as_slice().unwrap().iter()) .map(|(x, dx)| (1.0 - x.powi(2)) * *dx); result_diff.write_iter(res)?; Ok(()) } } impl<P> Forward for Context<P> where P: Dependency<Package> { fn log_softmax(&self, x: &SharedTensor, result: &mut SharedTensor) -> Result { let mut max_input = ::std::f32::NEG_INFINITY; for &input in x.as_slice().unwrap() { max_input = max_input.max(input); } let mut logsum = 0.; for exp in x.as_slice().unwrap().iter().map(|t| (-(max_input - t)).exp()) { logsum += exp; } logsum = max_input + logsum.ln(); let res = x.as_slice().unwrap().iter().map(|t| t - logsum); result.write_iter(res)?; Ok(()) } fn relu(&self, x: &SharedTensor, result: &mut SharedTensor) -> Result { let res = x.as_slice().unwrap().iter().map(|elem| elem.max(0.0)); result.write_iter(res)?; Ok(()) } fn sigmoid(&self, x: &SharedTensor, result: &mut SharedTensor) -> Result { let res = x.as_slice().unwrap().iter().map(|x| 1.0 / (1.0 + (-*x).exp())); result.write_iter(res)?; Ok(()) } fn softmax(&self, x: &SharedTensor, result: &mut SharedTensor) -> Result { let mut exps = Vec::with_capacity(x.shape().capacity()); let mut sum = 0.0; for exp in x.as_slice().unwrap().iter().map(|t| t.exp()) { exps.push(exp); sum += exp; } let res = exps.iter().map(|t| t / sum); result.write_iter(res)?; Ok(()) } fn tanh(&self, x: &SharedTensor, result: &mut SharedTensor) -> Result { let res = x.as_slice().unwrap().iter().map(|elem| elem.tanh()); result.write_iter(res)?; Ok(()) } } impl<P> Extension for Context<P> where P: Dependency<Package> { // .. }
use buf_redux::Buffer; use super::slsk_buffer::SlskBuffer; pub(crate) trait Message: Send { fn as_buffer(&self) -> Buffer; } impl dyn Message { pub fn login_request(username: &'static str, password: &'static str) -> Box<LoginRequest> { Box::new(LoginRequest { username, password }) } } pub struct LoginRequest { username: &'static str, password: &'static str, } impl Message for LoginRequest { fn as_buffer(&self) -> Buffer { let md5 = md5::compute(format!("{}{}", self.username, self.password)); SlskBuffer::new() .append_u32(1) .append_string(self.username) .append_string(self.password) .append_u32(160) .append_string(format!("{:x}", md5).as_str()) .append_u32(17) .to_buffer() } }
//! This module describes the transport-agnostic concept of a transfer, //! which boils down to some metadata to uniquely identify it, as well //! as a serialized buffer of data, which encodes DSDL-based data. use crate::internal::InternalRxFrame; use crate::time::Timestamp; use crate::types::*; use crate::Priority; /// Protocol-level transfer types. #[derive(Copy, Clone, Debug, Ord, PartialOrd, Eq, PartialEq)] pub enum TransferKind { Message, Response, Request, } /// Application representation of a UAVCAN transfer. /// /// This will be passed out on successful reception of full transfers, /// as well as given to objects to encode into the correct transport. #[derive(Debug)] pub struct Transfer<'a, C: embedded_time::Clock> { // for tx -> transmission_timeout pub timestamp: Timestamp<C>, pub priority: Priority, pub transfer_kind: TransferKind, pub port_id: PortId, pub remote_node_id: Option<NodeId>, pub transfer_id: TransferId, pub payload: &'a [u8], } // I don't want to impl convert::From because I need to pull in extra data impl<'a, C: embedded_time::Clock> Transfer<'a, C> { pub fn from_frame( frame: InternalRxFrame<C>, timestamp: Timestamp<C>, payload: &'a [u8], ) -> Self { Self { timestamp, priority: frame.priority, transfer_kind: frame.transfer_kind, port_id: frame.port_id, remote_node_id: frame.source_node_id, transfer_id: frame.transfer_id, payload, } } }
enum Cell { Dead = 0, Alive = 1, } fn main() { // let cells: Vec<u32> = (0..10) // .map(|i| { // match i { // 3 => 0, // 5 => 0, // 10 => 0, // _ => 1 // } // }) // .collect(); // print!("{:?}", cells.iter().fold(String::new(), |acc, &num| acc + &num.to_string() + ",")); // let some_u8_value = 3; // match some_u8_value { // 1 => println!("one"), // 3 => println!("three"), // 5 => println!("five"), // 7 => println!("seven"), // _ => println!("nothing"), // } // for aa in (0..10) { // if aa == 1 { // println!("one") // } else if aa == 3 { // println!("three") // } else { // println!("nothing") // } // } // let ll = (0..10).map(|bb| { // match bb { // 1 => Cell::Alive, // _ => Cell::Dead, // } // }); // for aa in ll { // println!("{}",aa) // } let width = 3; let height = 3; let cells = (0..width * height) .map(|i| { // if i % 2 == 0 { // Cell::Alive // } else { // Cell::Dead // } match i { 2 => 99, _ => i, } }); for aa in cells { println!("{}",aa) } } use std::fmt; impl fmt::Display for Cell { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let aa = match self { Cell::Alive => 1, Cell::Dead => 0, }; write!(f, "{}", aa)?; Ok(()) } }
use crate::libs::js_object::Object; use crate::libs::try_ref::TryRef; use async_trait::async_trait; use js_sys::Promise; use std::rc::Rc; use wasm_bindgen::{prelude::*, JsCast}; use wasm_bindgen_futures::JsFuture; #[async_trait] trait LoadFrom<T> { async fn load_from(x: T) -> Data; } pub struct ImageData { element: Rc<web_sys::HtmlImageElement>, blob: Rc<web_sys::Blob>, url: Rc<String>, size: [f32; 2], } impl ImageData { pub fn element(&self) -> Rc<web_sys::HtmlImageElement> { Rc::clone(&self.element) } pub fn url(&self) -> Rc<String> { Rc::clone(&self.url) } pub fn size(&self) -> &[f32; 2] { &self.size } } pub enum Data { Image(Rc<ImageData>), } impl Data { pub async fn pack(&self) -> JsValue { match self { Self::Image(data) => (object! { "type": data.blob.type_(), "payload": data.blob.as_ref() }) .into(), } } pub async fn unpack(val: JsValue) -> Option<Self> { let obj = val.dyn_into::<js_sys::Object>().unwrap(); let obj = obj.dyn_into::<Object>().unwrap(); let blob_type = obj.get("type").unwrap().as_string().unwrap(); let payload = obj.get("payload").unwrap(); if let Some(array_buffer) = payload.dyn_ref::<js_sys::ArrayBuffer>() { let blob = web_sys::Blob::new_with_buffer_source_sequence_and_options( array![array_buffer].as_ref(), web_sys::BlobPropertyBag::new().type_(blob_type.as_str()), ) .unwrap(); Self::from_blob(blob).await } else if let Ok(blob) = payload.dyn_into::<web_sys::Blob>() { Self::from_blob(blob).await } else { None } } fn prefix_of<'a>(file_type: &'a str) -> &'a str { let file_type: Vec<&str> = file_type.split('/').collect(); file_type.first().map(|x| x as &str).unwrap_or("") } pub fn is_able_to_load(file_type: &str) -> bool { let prefix = Self::prefix_of(file_type); prefix == "image" } pub async fn from_blob(blob: web_sys::Blob) -> Option<Self> { if Self::prefix_of(&blob.type_()) == "image" { let image = Rc::new(crate::libs::element::html_image_element()); let object_url = web_sys::Url::create_object_url_with_blob(&blob).unwrap_or("".into()); let object_url = Rc::new(object_url); let _ = JsFuture::from(Promise::new({ let image = Rc::clone(&image); let object_url = Rc::clone(&object_url); &mut move |resolve, _| { let a = Closure::wrap(Box::new(move || { let _ = resolve.call1(&js_sys::global(), &JsValue::null()); }) as Box<dyn FnMut()>); image.set_onload(Some(&a.as_ref().unchecked_ref())); image.set_src(&object_url); a.forget(); } })) .await; let width = image.width() as f32; let height = image.height() as f32; Some(Self::Image(Rc::new(ImageData { element: image, blob: Rc::new(blob), url: object_url, size: [width, height], }))) } else { None } } } impl TryRef<Rc<ImageData>> for Data { fn try_ref(&self) -> Option<&Rc<ImageData>> { match self { Self::Image(data) => Some(data), } } }
use std::io; use std::io::Write; use std::io::BufRead; use std::fs; use std::path; use glib::user_config_dir; use crate::app::*; pub struct AppEnvironment { recent_dir: path::PathBuf } impl AppEnvironment { pub fn new() -> Result<AppEnvironment, io::Error> { let dir = AppEnvironment::recent_dir(); if !dir.exists() { AppEnvironment::init_recents_dir()?; } Ok(AppEnvironment { recent_dir: AppEnvironment::recent_dir() }) } fn recent_dir() -> path::PathBuf { let mut recent_dir = path::PathBuf::new(); #[cfg(not(debug_assertions))] recent_dir.push(user_config_dir()); recent_dir.push("film_taggy"); recent_dir } fn init_recents_dir() -> Result<(), io::Error> { fs::create_dir(AppEnvironment::recent_dir())?; let dir = AppEnvironment::recent_dir(); let recent_cameras = dir.join(path::Path::new("cameras")); let _recent_cameras_file = fs::File::create(recent_cameras)?; let recent_films = dir.join(path::Path::new("films")); let _recent_films_file = fs::File::create(recent_films)?; let recent_isos = dir.join(path::Path::new("isos")); let mut recent_isos_file = fs::File::create(recent_isos)?; recent_isos_file.write_all(include_str!("setup/isos").as_bytes())?; let recent_authors = dir.join(path::Path::new("authors")); let _recent_authors_file = fs::File::create(recent_authors)?; Ok(()) } fn read_recent(&self, list: &str) -> Result<Vec<String>, io::Error> { let file = fs::File::open(self.recent_dir.join(path::Path::new(&list)))?; io::BufReader::new(file).lines().collect() } pub fn restore_state(&self) -> Result<AppState, io::Error> { let recent_cameras = self.read_recent("cameras")?; let recent_films = self.read_recent("films")?; let recent_isos = self.read_recent("isos")?; let recent_authors = self.read_recent("authors")?; Ok(AppState { camera: None, film: None, iso: None, author: None, comment: None, set_file_index: false, files: Vec::new(), recent_cameras: recent_cameras, recent_films: recent_films, recent_isos: recent_isos, recent_authors: recent_authors }) } fn save_recent(&self, list: &str, entries: &Vec<String>) -> Result<(), io::Error> { fs::write(self.recent_dir.join(path::Path::new(&list)), entries.join("\n")) } pub fn save_state(&self, state: &AppState) -> Result<(), io::Error> { self.save_recent("cameras", &state.recent_cameras)?; self.save_recent("films", &state.recent_films)?; self.save_recent("isos", &state.recent_isos)?; self.save_recent("authors", &state.recent_authors)?; Ok(()) } }
use crate::{Context, Error, PrefixContext}; /// Evaluates Go code #[poise::command(prefix_command, discard_spare_arguments)] pub async fn go(ctx: PrefixContext<'_>) -> Result<(), Error> { poise::say_reply(ctx.into(), "No").await?; Ok(()) } /// Links to the bot GitHub repo #[poise::command(prefix_command, discard_spare_arguments, slash_command)] pub async fn source(ctx: Context<'_>) -> Result<(), Error> { poise::say_reply(ctx, r"https://github.com/kangalioo/rustbot").await?; Ok(()) } /// Show this menu #[poise::command(prefix_command, track_edits, slash_command)] pub async fn help( ctx: Context<'_>, #[description = "Specific command to show help about"] command: Option<String>, ) -> Result<(), Error> { let bottom_text = "You can still use all commands with `?`, even if it says `/` above. Type ?help command for more info on a command. You can edit your message to the bot and the bot will edit its response."; poise::samples::help( ctx, command.as_deref(), bottom_text, poise::samples::HelpResponseMode::Ephemeral, ) .await?; Ok(()) } /// Register slash commands in this guild or globally /// /// Run with no arguments to register in guild, run with argument "global" to register globally. #[poise::command(prefix_command, hide_in_help)] pub async fn register(ctx: PrefixContext<'_>, #[flag] global: bool) -> Result<(), Error> { poise::samples::register_application_commands(ctx.into(), global).await?; Ok(()) } /// Tells you how long the bot has been up for #[poise::command(prefix_command, slash_command, hide_in_help)] pub async fn uptime(ctx: Context<'_>) -> Result<(), Error> { let uptime = std::time::Instant::now() - ctx.data().bot_start_time; let div_mod = |a, b| (a / b, a % b); let seconds = uptime.as_secs(); let (minutes, seconds) = div_mod(seconds, 60); let (hours, minutes) = div_mod(minutes, 60); let (days, hours) = div_mod(hours, 24); poise::say_reply( ctx, format!("Uptime: {}d {}h {}m {}s", days, hours, minutes, seconds), ) .await?; Ok(()) } /// List servers of which the bot is a member of #[poise::command(slash_command, prefix_command, track_edits, hide_in_help)] pub async fn servers(ctx: Context<'_>) -> Result<(), Error> { poise::samples::servers(ctx).await?; Ok(()) } /// Displays the SHA-1 git revision the bot was built against #[poise::command(prefix_command, hide_in_help, discard_spare_arguments)] pub async fn revision(ctx: Context<'_>) -> Result<(), Error> { let rustbot_rev: Option<&'static str> = option_env!("RUSTBOT_REV"); poise::say_reply(ctx, format!("`{}`", rustbot_rev.unwrap_or("unknown"))).await?; Ok(()) }
#[doc = "Register `SPI2S_SR` reader"] pub type R = crate::R<SPI2S_SR_SPEC>; #[doc = "Field `RXP` reader - RXP"] pub type RXP_R = crate::BitReader; #[doc = "Field `TXP` reader - TXP"] pub type TXP_R = crate::BitReader; #[doc = "Field `DXP` reader - DXP"] pub type DXP_R = crate::BitReader; #[doc = "Field `EOT` reader - EOT"] pub type EOT_R = crate::BitReader; #[doc = "Field `TXTF` reader - TXTF"] pub type TXTF_R = crate::BitReader; #[doc = "Field `UDR` reader - UDR"] pub type UDR_R = crate::BitReader; #[doc = "Field `OVR` reader - OVR"] pub type OVR_R = crate::BitReader; #[doc = "Field `CRCE` reader - CRCE"] pub type CRCE_R = crate::BitReader; #[doc = "Field `TIFRE` reader - TIFRE"] pub type TIFRE_R = crate::BitReader; #[doc = "Field `MODF` reader - MODF"] pub type MODF_R = crate::BitReader; #[doc = "Field `TSERF` reader - TSERF"] pub type TSERF_R = crate::BitReader; #[doc = "Field `SUSP` reader - SUSP"] pub type SUSP_R = crate::BitReader; #[doc = "Field `TXC` reader - TXC"] pub type TXC_R = crate::BitReader; #[doc = "Field `RXPLVL` reader - RXPLVL"] pub type RXPLVL_R = crate::FieldReader; #[doc = "Field `RXWNE` reader - RXWNE"] pub type RXWNE_R = crate::BitReader; #[doc = "Field `CTSIZE` reader - CTSIZE"] pub type CTSIZE_R = crate::FieldReader<u16>; impl R { #[doc = "Bit 0 - RXP"] #[inline(always)] pub fn rxp(&self) -> RXP_R { RXP_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - TXP"] #[inline(always)] pub fn txp(&self) -> TXP_R { TXP_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - DXP"] #[inline(always)] pub fn dxp(&self) -> DXP_R { DXP_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - EOT"] #[inline(always)] pub fn eot(&self) -> EOT_R { EOT_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - TXTF"] #[inline(always)] pub fn txtf(&self) -> TXTF_R { TXTF_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - UDR"] #[inline(always)] pub fn udr(&self) -> UDR_R { UDR_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - OVR"] #[inline(always)] pub fn ovr(&self) -> OVR_R { OVR_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - CRCE"] #[inline(always)] pub fn crce(&self) -> CRCE_R { CRCE_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - TIFRE"] #[inline(always)] pub fn tifre(&self) -> TIFRE_R { TIFRE_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - MODF"] #[inline(always)] pub fn modf(&self) -> MODF_R { MODF_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - TSERF"] #[inline(always)] pub fn tserf(&self) -> TSERF_R { TSERF_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - SUSP"] #[inline(always)] pub fn susp(&self) -> SUSP_R { SUSP_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - TXC"] #[inline(always)] pub fn txc(&self) -> TXC_R { TXC_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bits 13:14 - RXPLVL"] #[inline(always)] pub fn rxplvl(&self) -> RXPLVL_R { RXPLVL_R::new(((self.bits >> 13) & 3) as u8) } #[doc = "Bit 15 - RXWNE"] #[inline(always)] pub fn rxwne(&self) -> RXWNE_R { RXWNE_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bits 16:31 - CTSIZE"] #[inline(always)] pub fn ctsize(&self) -> CTSIZE_R { CTSIZE_R::new(((self.bits >> 16) & 0xffff) as u16) } } #[doc = "SPI/I2S status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`spi2s_sr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SPI2S_SR_SPEC; impl crate::RegisterSpec for SPI2S_SR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`spi2s_sr::R`](R) reader structure"] impl crate::Readable for SPI2S_SR_SPEC {} #[doc = "`reset()` method sets SPI2S_SR to value 0x1002"] impl crate::Resettable for SPI2S_SR_SPEC { const RESET_VALUE: Self::Ux = 0x1002; }
extern crate otaku; extern crate clap; use otaku::config::Config; use clap::{App, Arg, SubCommand}; use std::process; use std::env; use std::path::PathBuf; static VERSION: &'static str = "0.1"; static AUTHOR: &'static str = "Matt Valentine-House <matt@eightbitraptor.com>"; fn main() { let arg_config = Arg::with_name("config") .short("c") .long("config") .help("use a custom config file (default is ~/.otaku/config.toml)") .takes_value(true); let cmd_update = SubCommand::with_name("update") .about("Updates an existing manga checkout to the latest chapters") .arg(Arg::with_name("name") .index(1) .required(true)); let application = App::new("otaku") .version(VERSION) .author(AUTHOR) .arg(arg_config) .subcommand(cmd_update); let arguments = application.get_matches(); let config_file_path = default_config_file_path(arguments.value_of("config")); let configuration = Config::from_file(&config_file_path) .map_err(|e| { println!("Error: {}", e); process::exit(1); }) .unwrap(); match arguments.subcommand() { ("update", Some(subcommand_args)) => { let name = subcommand_args.value_of("name").unwrap(); otaku::update(&name, &configuration); } (_, _) => { println!("{}", arguments.usage()); process::exit(1) } }; } fn default_config_file_path(config_file_name: Option<&str>) -> PathBuf { match config_file_name { Some(filename) => PathBuf::from(filename), None => env::home_dir().unwrap().join(".otaku").join("config.toml"), } }
//! # rlink-sink-conf //! //! A library to upgrade [rlink](https://docs.rs/rlink) task smoothly. //! //! # Example //! //! ``` //! use rlink_sink_conf::sink_config::{init_sink_config, get_sink_topic}; //! use std::collections::HashMap; //! //! let sin_conf_url = "testUrl"; //! let application_name = "tlb_base_qa"; //! let timestamp = 123 as u64; //! //! init_sink_config(sin_conf_url.to_string(), application_name.to_string()); //! //! let mut expression_param = HashMap::new(); //! expression_param.insert("timestamp".to_string(), timestamp.to_string()); //! let sink_topic = get_sink_topic(expression_param); //! ``` #[macro_use] extern crate log; #[macro_use] extern crate lazy_static; #[macro_use] extern crate serde_derive; pub mod sink_config; #[cfg(test)] mod tests { use crate::sink_config::{get_sink_topic, init_sink_config}; use std::collections::HashMap; #[test] fn it_works() { let sin_conf_url = "http://10.99.21.40:8080/upgrade/config/name"; let application_name = "test2"; let timestamp = 123 as u64; init_sink_config(sin_conf_url.to_string(), application_name.to_string()); let mut expression_param = HashMap::new(); expression_param.insert("timestamp".to_string(), timestamp.to_string()); let sink_topic = get_sink_topic(expression_param); println!("{}", sink_topic) } }
use actix_web::{ HttpResponse, web, }; use super::super::{ service, request, response, }; pub fn index(payload: web::Query<request::developper::Index>) -> HttpResponse { let (domain_developpers, total) = &service::developper::index( payload.page, payload.page_size, ); response::developper_index::response(domain_developpers, &total) }
use bitvec::vec::*; use rand::Rng; use serde::{Deserialize, Serialize}; // TODO: This boundary is way too strict, especially for very deeply nested trees. the boundary should grow exponentially with the tree const DEFAULT_BOUNDARY: u64 = 10; const DEFAULT_INITIAL_BASE: u8 = 3; // start with 2^3 /// A tree identifier uniquely locates an element in an LSeq tree. /// It represents the path that needs to be taken in order to reach /// the element. At each level we store the index of the child tree node /// as well as the id of the site that inserted that node. This resolves conflicts where /// two sites decide to pick the same child index to allocate a fresh node #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Clone, Serialize, Deserialize, Hash)] pub struct Identifier<A> { /// The path through the lseq tree pub path: Vec<(u64, Option<A>)>, } /// A generator for fresh identifiers. /// /// These identifiers represent a path in an exponential tree. At each level of the tree the amount /// of children doubles. This means that we can store a lot of nodes in a very low height! /// /// The [`crate::LSeq`] tree also has an additional restriction: at each level the minimum and maximum nodes /// cannot be chosen when allocating fresh nodes. This is to ensure there is always a free node /// that can be used to create a lower level. #[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Hash, PartialOrd, Ord)] pub struct IdentGen<A> { /// Base which determines the arity of the root tree node. The arity is doubled at each depth initial_base_bits: u8, /// Boundary for choosing a new number when allocating an identifier boundary: u64, /// We keep a cache of the strategy chosen for each level of the tree strategy_vec: BitVec, /// Site id of the trees generated by this generator pub site_id: A, } impl<A: Ord + Clone> IdentGen<A> { /// Create a fresh tree with 0 node. pub fn new(site_id: A) -> Self { Self::new_with_args(site_id, DEFAULT_INITIAL_BASE, DEFAULT_BOUNDARY) } /// Create a tree with a custom initial size. pub fn new_with_args(site_id: A, base: u8, boundary: u64) -> Self { IdentGen { initial_base_bits: base, boundary, strategy_vec: BitVec::new(), site_id, } } /// The smallest possible node in a tree. pub fn lower(&self) -> Identifier<A> { Identifier { path: vec![(0, None)], } } /// The absolute largest possible node. pub fn upper(&self) -> Identifier<A> { Identifier { path: vec![(self.arity_at(0), None)], } } /// Allocates a new identifier between `p` and `q` such that `p < z < q`. /// /// The way to think about this is to consider the problem of finding a short number between /// two decimal numbers. For example, between `0.2` and `0.4` we'd like to return `0.3`. /// But what about `0.2` and `0.3`? Well a nice property is that if we add a digit to `0.2`, the /// number produced will be larger than `0.2` but smaller than `0.3`. /// /// If you view identifiers `p` and `q` as decimal numbers `0.p` and `0.q` then all we're doing is /// finding a number between them! /// /// # Panics /// /// * `p` equal to `q`. /// * If no identifier of length less than 31 exists between `p` and `q`. pub fn alloc(&mut self, p: &Identifier<A>, q: &Identifier<A>) -> Identifier<A> { assert!(p != q, "allocation range should be non-empty"); if q < p { return self.alloc(q, p); } assert!(p < q); let mut depth = 0; // Descend both identifiers in parallel until we find room to insert an identifier loop { match (p.path.get(depth), q.path.get(depth)) { // Our descent continues... (Some(a), Some(b)) => { if a.0 == b.0 { // continue searching lower } else if a.0 + 1 < b.0 { // We take this branch if there's room between a and b to insert a new // identifier let next_index = self.index_in_range(a.0 + 1, b.0, depth); return self.replace_last(p, depth, next_index); } else { // If we end up here that means that a + 1 = b. Therefore we can't actually // insert a new node at this layer. So we start a new layer below a. return self.alloc_from_lower(p, depth + 1); } } // The upper bound ended on the previous level. // This means we can allocate a node in the range a..max_for_depth // If there isn't room at this level because a = max_for_depth then we'll keep // searching below. (Some(_), None) => { return self.alloc_from_lower(p, depth); } // The lower bound ended on the previous level, we just need to keep following the upper bound until some space // is available. (None, Some(_)) => { return self.alloc_from_upper(p, q, depth); } // The two paths are fully equal which means that the site_ids MUST be different or // we are in an invalid situation (None, None) => { let next_index = self.index_in_range(1, self.arity_at(depth), depth); return self.push_index(p, next_index); } }; depth += 1; } } // Here we have the lowest possible upper bound and we just need to traverse the lower bound // until we can find somewhere to insert a new identifier. // // This reflects the case where we want to allocate between 0.20001 and 0.3 fn alloc_from_lower(&mut self, p: &Identifier<A>, mut depth: usize) -> Identifier<A> { loop { match p.path.get(depth) { Some((ix, _)) => { if ix + 1 < self.arity_at(depth) { let next_index = self.index_in_range(ix + 1, self.arity_at(depth), depth); return self.replace_last(p, depth, next_index); } else { // Not enough room at this level, continue to the next depth } } None => { // TODO: this is the same branch as the (None, None) case above, see about factoring these out let next_index = self.index_in_range(1, self.arity_at(depth), depth); return self.push_index(p, next_index); } } depth += 1; } } // Here the problem is that we've run out of the lower path and the upper one is zero! // The idea is to keep pushing 0s onto the lower path until we can find a new level to allocate at. // // This reflects the case where we want to allocate something between 0.2 and 0.200000001 fn alloc_from_upper( &mut self, base: &Identifier<A>, q: &Identifier<A>, mut depth: usize, ) -> Identifier<A> { let mut ident = base.clone(); loop { match q.path.get(depth) { // append a 0 to the result path as well Some(b) if b.0 <= 1 => ident.path.push((0, b.1.clone())), // oo! a non-zero value _ => break, } depth += 1; } // If we actually ran out of upper bound values then we're free to choose // anything on the next level, otherwise use the upper bound we've found. let upper = match q.path.get(depth) { Some(b) => b.0, None => self.arity_at(depth), }; let next_index = self.index_in_range(1, upper, depth); let z = self.push_index(&ident, next_index); assert!(base < &z); assert!(&z < q); z } fn replace_last(&mut self, p: &Identifier<A>, depth: usize, ix: u64) -> Identifier<A> { let mut ident = p.clone(); ident.path.truncate(depth); ident.path.push((ix, Some(self.site_id.clone()))); ident } fn push_index(&mut self, p: &Identifier<A>, ix: u64) -> Identifier<A> { let mut ident = p.clone(); ident.path.push((ix, Some(self.site_id.clone()))); ident } fn arity_at(&self, depth: usize) -> u64 { let base_bits = (self.initial_base_bits as u32) + (depth as u32); assert!(base_bits < 31, "maximum depth exceeded"); 2u64.pow(base_bits) } // Generate an index in a given range at the specified depth. // Uses the allocation strategy of that depth, boundary+ or boundary- which is biased to the // lower and upper ends of the range respectively. // should allocate in the range [lower, upper) fn index_in_range(&mut self, lower: u64, upper: u64, depth: usize) -> u64 { assert!( lower < upper, "need at least one space between the bounds lower={} upper={}", lower, upper ); let mut rng = rand::rngs::OsRng; let interval = std::cmp::min(self.boundary, upper - lower); let step = if interval > 0 { rng.gen_range(0, interval) } else { 0 }; let index = if self.strategy(depth) { //boundary+ lower + step } else { //boundary- upper - step - 1 }; assert!(lower <= index); assert!(index < upper); index } fn strategy(&mut self, depth: usize) -> bool { match self.strategy_vec.get(depth) { None => { let new_strategy = rand::thread_rng().gen(); self.strategy_vec.push(new_strategy); new_strategy } Some(s) => *s, } // temp strategy. Should be a random choice at each level } } impl<A: quickcheck::Arbitrary> quickcheck::Arbitrary for Identifier<A> { fn arbitrary<G: quickcheck::Gen>(g: &mut G) -> Identifier<A> { let max_depth = 27; // TODO: where does this come from? let min_depth = 1; let chosen_depth = u8::arbitrary(g) % (max_depth - min_depth) + min_depth; let mut path = Vec::new(); for depth in 0..chosen_depth { let i = u64::arbitrary(g) % (2u64.pow((DEFAULT_INITIAL_BASE + depth).into()) + 1); path.push((i, Option::arbitrary(g))); } // our last entry can not use 0 as an index since this will not allow us to insert // anything before this identifier if path.last().unwrap().0 == 0 { path.pop(); let i = 1 + u64::arbitrary(g) % 2u64.pow((DEFAULT_INITIAL_BASE + chosen_depth).into()); assert_ne!(i, 0); path.push((i, Option::arbitrary(g))); }; Self { path } } fn shrink(&self) -> Box<dyn Iterator<Item = Self>> { if self.path.len() == 1 { Box::new(std::iter::empty()) } else { let mut path = self.path.clone(); path.pop(); Box::new(std::iter::once(Self { path })) } } } #[cfg(test)] mod test { use super::*; use quickcheck::{quickcheck, TestResult}; quickcheck! { fn prop_alloc(p: Identifier<u32>, q: Identifier<u32>) -> TestResult { if p == q { return TestResult::discard(); } let mut gen = IdentGen::new(0); let z = gen.alloc(&p, &q); TestResult::from_bool((p < z && z < q) || (q < z && z < p)) } } #[test] fn test_alloc_eq_path() { let mut gen = IdentGen::new(0); let x = Identifier { path: vec![(1, Some(0)), (1, Some(0))], }; let y = Identifier { path: vec![(1, Some(0)), (1, Some(1))], }; gen.alloc(&x, &y); let b = gen.alloc(&x, &y); assert!(x < b); assert!(b < y); } #[test] fn test_different_len_paths() { let mut gen = IdentGen::new(0); let x = Identifier { path: vec![(1, Some(0))], }; let y = Identifier { path: vec![(1, Some(0)), (15, Some(0))], }; let z = gen.alloc(&x, &y); assert!(x < z); assert!(z < y); } #[test] fn test_alloc() { let mut gen = IdentGen::new(0); let a = Identifier { path: vec![(1, Some(0))], }; let b = Identifier { path: vec![(3, Some(0))], }; assert_eq!( gen.alloc(&a, &b), Identifier { path: vec![(2, Some(0))] } ); let c = Identifier { path: vec![(1, Some(0)), (0, Some(0)), (1, Some(0))], }; let d = Identifier { path: vec![(1, Some(0)), (0, Some(0)), (3, Some(0))], }; assert_eq!( gen.alloc(&c, &d), Identifier { path: vec![(1, Some(0)), (0, Some(0)), (2, Some(0))] } ); let e = Identifier { path: vec![(1, Some(0))], }; let f = Identifier { path: vec![(2, Some(0))], }; let res = gen.alloc(&e, &f); assert!(e < res); assert!(res < f); { let mut gen = IdentGen::new(1); let a = Identifier { path: vec![(4, Some(0)), (4, Some(0))], }; let b = Identifier { path: vec![(4, Some(0)), (4, Some(0)), (1, Some(1))], }; let c = gen.alloc(&a, &b); assert!(a < c); assert!(c < b); } { let a = Identifier { path: vec![(5, Some(1)), (6, Some(1)), (6, Some(1)), (6, Some(0))], }; let b = Identifier { path: vec![ (5, Some(1)), (6, Some(1)), (6, Some(1)), (6, Some(0)), (0, Some(0)), (507, Some(0)), ], }; let c = gen.alloc(&a, &b); assert!(a < c); assert!(c < b); } } #[test] fn test_index_in_range() { let mut gen = IdentGen::new(0); assert_eq!(gen.index_in_range(0, 1, 1), 0); } #[test] fn test_alloc_between_conflicting_ids() { let mut gen = IdentGen::new(0); let a = Identifier { path: vec![(0, Some(1))], }; let b = Identifier { path: vec![(0, Some(2))], }; assert!(a < b); let z = gen.alloc(&a, &b); assert!(a < z); assert!(z < b); assert_eq!(&z.path[0..1], a.path.as_slice()); } }
#![allow(unstable)] extern crate rusql; use rusql::{rusql_exec, Rusql, LiteralValue}; fn test(sql_str: &str, expected: Vec<LiteralValue>) { let mut db = Rusql::new(); let result_table = rusql_exec(&mut db, sql_str, |_,_| {}).unwrap(); let results = result_table.data.get(&1).unwrap(); assert_eq!(&expected, results); } fn test_expect_ints(sql_str: &str, expected: Vec<isize>) { let mut db = Rusql::new(); let mut results: Vec<isize> = Vec::new(); let result_table = rusql_exec(&mut db, sql_str, |_,_| {}).unwrap(); let result_row = result_table.data.get(&1).unwrap(); for column in result_row.iter() { results.push(column.to_int()); } assert_eq!(expected, results); } #[test] fn test_literal_values() { test("SELECT 26, \"Foo\";", vec![LiteralValue::Integer(26), LiteralValue::Text("Foo".to_string())]); } #[test] fn test_equality() { test("SELECT 26=26;", vec![LiteralValue::Boolean(true)]); test("SELECT 26=27;", vec![LiteralValue::Boolean(false)]); } #[test] fn test_equality_double_equals() { test("SELECT 26==26;", vec![LiteralValue::Boolean(true)]); } #[test] fn test_equality_with_spaces() { test("SELECT 26 = 26;", vec![LiteralValue::Boolean(true)]); } #[test] fn test_addition() { test_expect_ints("SELECT 5 + 6;", vec![11]); } #[test] fn test_subtraction() { test_expect_ints("SELECT 5 - 6;", vec![-1]); } #[test] fn test_multiple_additions() { test_expect_ints("SELECT 5 + 6 + 10 + 3 + 1;", vec![25]); } #[test] fn test_multiple_subtractions() { test_expect_ints("SELECT 5 - 6 - 10 - 3 - 1;", vec![-15]); } #[test] fn test_multiple_additions_and_subtractions() { test_expect_ints("SELECT 5 + 6 - 10 + 3 - 1;", vec![3]); } #[test] fn test_unary_neg() { test_expect_ints("SELECT -5;", vec![-5]); } #[test] fn test_paren_expr() { test_expect_ints("SELECT (5-6);", vec![-1]); } #[test] fn test_neg_paren() { test_expect_ints("SELECT -(-6);", vec![6]); } #[test] fn test_neg_paren_inner_expr() { test_expect_ints("SELECT -(3-44);", vec![41]); } #[test] fn test_multiplication() { test_expect_ints("SELECT 2*6;", vec![12]); } #[test] fn test_division() { test_expect_ints("SELECT 15/3;", vec![5]); } #[test] fn test_modulo() { test_expect_ints("SELECT 15%6;", vec![3]); } #[test] fn test_not_equals() { test_expect_ints("SELECT 5!=4, 5<>4, 5!=5;", vec![1, 1, 0]); } #[test] fn test_and() { test_expect_ints("SELECT 0 AND 0, 0 AND 1, 1 AND 0, 1 AND 1;", vec![0, 0, 0, 1]); } #[test] fn test_or() { test_expect_ints("SELECT 0 OR 0, 0 OR 1, 1 OR 0, 1 OR 1;", vec![0, 1, 1, 1]); } #[test] fn test_not() { test_expect_ints("SELECT NOT 1, NOT 0, NOT (5 == 5);", vec![0, 1, 0]); } #[test] fn test_multiple_boolean_ops() { test_expect_ints("SELECT 3=3 AND 4=4, (3=3) AND (4=4);", vec![1, 1]); } #[test] fn test_less_than() { test_expect_ints("SELECT 3<4, 3<3, 3<2;", vec![1, 0, 0]); } #[test] fn test_less_than_or_eq() { test_expect_ints("SELECT 3<=4, 3<=3, 3<=2;", vec![1, 1, 0]); } #[test] fn test_greater_than() { test_expect_ints("SELECT 3>4, 3>3, 3>2;", vec![0, 0, 1]); } #[test] fn test_greater_than_or_eq() { test_expect_ints("SELECT 3>=4, 3>=3, 3>=2;", vec![0, 1, 1]); } #[test] fn test_bit_and() { test_expect_ints("SELECT 6 & 3;", vec![2]); } #[test] fn test_bit_or() { test_expect_ints("SELECT 6 | 3;", vec![7]); } #[test] fn test_right_shift() { test_expect_ints("SELECT 6 >> 1;", vec![3]); } #[test] fn test_left_shift() { test_expect_ints("SELECT 6 << 1;", vec![12]); } #[test] fn test_bit_neg() { test_expect_ints("SELECT ~7;", vec![-8]); } #[test] fn test_mult_div_associativity() { test_expect_ints("SELECT 9/3*3;", vec![9]); }
use crate::common::Ownable; use crate::common::StorageKey; use crate::series::NftSeriesSale; use chrono::{DateTime, Timelike, Utc}; use near_contract_standards::non_fungible_token::metadata::NFTContractMetadata; use near_contract_standards::non_fungible_token::metadata::NonFungibleTokenMetadataProvider; use near_contract_standards::non_fungible_token::metadata::TokenMetadata; use near_contract_standards::non_fungible_token::metadata::NFT_METADATA_SPEC; use near_contract_standards::non_fungible_token::NonFungibleToken; use near_contract_standards::non_fungible_token::{Token, TokenId}; use near_sdk::borsh::{self, BorshDeserialize, BorshSerialize}; use near_sdk::collections::LazyOption; use near_sdk::collections::LookupMap; use near_sdk::collections::UnorderedSet; use near_sdk::json_types::ValidAccountId; use std::convert::TryFrom; use std::time::{Duration, UNIX_EPOCH}; use near_sdk::Balance; use near_sdk::{ env, ext_contract, near_bindgen, AccountId, PanicOnDefault, Promise, PromiseOrValue, }; near_sdk::setup_alloc!(); #[near_bindgen] #[derive(BorshDeserialize, BorshSerialize, PanicOnDefault)] pub struct AppContract { pub tokens: NonFungibleToken, pub owner_id: AccountId, metadata: LazyOption<NFTContractMetadata>, pub pending_nft_rewards: LookupMap<AccountId, Balance>, pub series: NftSeriesSale, allowed_upgrades: UnorderedSet<UpgradeAllowance>, } #[derive(BorshDeserialize, BorshSerialize)] pub struct UpgradeAllowance { pub time: (u128, u128), pub allowed: bool, } impl UpgradeAllowance { pub fn new(time: (u128, u128), allowed: bool) -> Self { Self { time, allowed } } pub fn set_time(&mut self, time: (u128, u128), allow: bool) { self.time = time; self.allowed = allow; } } #[ext_contract(ext_nearapps)] trait ExtNearApps { fn call(tags: String, contract_name: ValidAccountId, method_name: String, args: String); } #[near_bindgen] impl AppContract { #[init] pub fn new_default_meta(owner_id: ValidAccountId) -> Self { Self::new( owner_id, NFTContractMetadata { spec: NFT_METADATA_SPEC.to_string(), name: "Upgrade NFT component".to_string(), symbol: "UPNFTCOMP".to_string(), icon: None, base_uri: Some("https://ipfs.fleek.co/ipfs".to_string()), reference: None, reference_hash: None, }, ) } #[init] pub fn new(owner_id: ValidAccountId, metadata: NFTContractMetadata) -> Self { assert!(!env::state_exists(), "Already initialized"); metadata.assert_valid(); Self { tokens: NonFungibleToken::new( StorageKey::NonFungibleToken, owner_id.clone(), Some(StorageKey::TokenMetadata), Some(StorageKey::Enumeration), Some(StorageKey::Approval), ), owner_id: owner_id.to_string(), pending_nft_rewards: LookupMap::new(b"r"), series: NftSeriesSale::new(), metadata: LazyOption::new(StorageKey::Metadata, Some(&metadata)), allowed_upgrades: UnorderedSet::new(b"u"), } } pub fn call_near_apps(self, time: U128, wallet: ValidAccountId, tags: String) { if check_correct_time(time.0 as u64) && self.wallet_contains_correct_nft(wallet.clone()) { ext_nearapps::call( tags, ValidAccountId::try_from(env::current_account_id()).unwrap(), // or who we call "method_name".to_string(), // unknown yet "args".to_string(), // unknown yet &env::current_account_id(), 0, env::prepaid_gas() / 3, // need to test how much gas is needed ); } } #[payable] pub fn refund_deposit(&mut self, storage_used: u64, extra_spend: Balance) { let required_cost = env::storage_byte_cost() * Balance::from(storage_used); let attached_depo = env::attached_deposit() - extra_spend; assert!( required_cost <= attached_depo, "Must attach {} some yocto to cover storage", required_cost, ); let refund = attached_depo - required_cost; if refund > 1 { Promise::new(env::predecessor_account_id()).transfer(refund); } } fn wallet_contains_correct_nft(self, wallet: ValidAccountId) -> bool { self.nft_supply_for_owner(wallet.clone()).0 > 0 && wallet.as_ref() == &env::predecessor_account_id() } pub fn set_allowed_timelapse(&mut self, start_time: U128, end_time: U128) { self.assert_owner(); if start_time.0 > end_time.0 { env::panic(b"start time is bigger, than endtime"); } self.allowed_upgrades .insert(&UpgradeAllowance::new((start_time.0, end_time.0), true)); } fn use_allowance(&mut self, time: u128) { let item = self.allowed_upgrades.iter().find(|allowance| { allowance.allowed && allowance.time.0 < time && allowance.time.1 > time }); if let Some(item) = item { self.allowed_upgrades.remove(&item); } } } impl Ownable for AppContract { fn owner(&self) -> AccountId { self.owner_id.clone() } fn transfer_ownership(&mut self, owner: AccountId) { self.assert_owner(); self.owner_id = owner; } } fn check_correct_time(time: u64) -> bool { let d = UNIX_EPOCH + Duration::from_secs(time); let datetime = DateTime::<Utc>::from(d); let hour = datetime.hour(); match hour { 0..=6 | 22..=23 => true, _ => env::panic("bad time".as_bytes()), } } near_contract_standards::impl_non_fungible_token_core!(AppContract, tokens); near_contract_standards::impl_non_fungible_token_approval!(AppContract, tokens); near_contract_standards::impl_non_fungible_token_enumeration!(AppContract, tokens); #[near_bindgen] impl NonFungibleTokenMetadataProvider for AppContract { fn nft_metadata(&self) -> NFTContractMetadata { self.metadata.get().unwrap() } }
// Copyright 2018-2020 argmin developers // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or // http://opensource.org/licenses/MIT>, at your option. This file may not be // copied, modified, or distributed except according to those terms. //! Benches #![feature(test)] extern crate modcholesky; extern crate openblas_src; extern crate test; #[cfg(test)] mod tests { use modcholesky::utils::{random_diagonal, random_householder}; use modcholesky::*; use ndarray; use test::{black_box, Bencher}; #[bench] fn gmw81_3x3_nd(b: &mut Bencher) { let a: ndarray::Array2<f64> = ndarray::arr2(&[[1.0, 1.0, 2.0], [1.0, 1.0, 3.0], [2.0, 3.0, 1.0]]); b.iter(|| { black_box(a.mod_cholesky_gmw81()); }); } #[bench] fn gmw81_4x4_nd(b: &mut Bencher) { let a: ndarray::Array2<f64> = ndarray::arr2(&[ [1890.3, -1705.6, -315.8, 3000.3], [-1705.6, 1538.3, 284.9, -2706.6], [-315.8, 284.9, 52.5, -501.2], [3000.3, -2706.6, -501.2, 4760.8], ]); b.iter(|| { black_box(a.mod_cholesky_gmw81()); }); } #[bench] fn gmw81_12x12_nd(b: &mut Bencher) { let dim = 12; let q1: ndarray::Array2<f64> = random_householder(dim, 2); let q2: ndarray::Array2<f64> = random_householder(dim, 9); let q3: ndarray::Array2<f64> = random_householder(dim, 90); let d: ndarray::Array2<f64> = random_diagonal(dim, (-1.0, 1000.0), 1, 23); let tmp = q1.dot(&q2.dot(&q3)); let a = tmp.dot(&d.dot(&tmp.t())); b.iter(|| { black_box(a.mod_cholesky_gmw81()); }); } #[bench] fn gmw81_128x128_nd(b: &mut Bencher) { let dim = 128; let q1: ndarray::Array2<f64> = random_householder(dim, 2); let q2: ndarray::Array2<f64> = random_householder(dim, 9); let q3: ndarray::Array2<f64> = random_householder(dim, 90); let d: ndarray::Array2<f64> = random_diagonal(dim, (-1.0, 1000.0), 1, 23); let tmp = q1.dot(&q2.dot(&q3)); let a = tmp.dot(&d.dot(&tmp.t())); b.iter(|| { black_box(a.mod_cholesky_gmw81()); }); } #[bench] fn gmw81_256x256_nd(b: &mut Bencher) { let dim = 256; let q1: ndarray::Array2<f64> = random_householder(dim, 2); let q2: ndarray::Array2<f64> = random_householder(dim, 9); let q3: ndarray::Array2<f64> = random_householder(dim, 90); let d: ndarray::Array2<f64> = random_diagonal(dim, (-1.0, 1000.0), 1, 23); let tmp = q1.dot(&q2.dot(&q3)); let a = tmp.dot(&d.dot(&tmp.t())); b.iter(|| { black_box(a.mod_cholesky_gmw81()); }); } #[bench] fn se90_3x3_nd(b: &mut Bencher) { let a: ndarray::Array2<f64> = ndarray::arr2(&[[1.0, 1.0, 2.0], [1.0, 1.0, 3.0], [2.0, 3.0, 1.0]]); b.iter(|| { black_box(a.mod_cholesky_se90()); }); } #[bench] fn se90_4x4_nd(b: &mut Bencher) { let a: ndarray::Array2<f64> = ndarray::arr2(&[ [1890.3, -1705.6, -315.8, 3000.3], [-1705.6, 1538.3, 284.9, -2706.6], [-315.8, 284.9, 52.5, -501.2], [3000.3, -2706.6, -501.2, 4760.8], ]); b.iter(|| { black_box(a.mod_cholesky_se90()); }); } #[bench] fn se90_12x12_nd(b: &mut Bencher) { let dim = 12; let q1: ndarray::Array2<f64> = random_householder(dim, 2); let q2: ndarray::Array2<f64> = random_householder(dim, 9); let q3: ndarray::Array2<f64> = random_householder(dim, 90); let d: ndarray::Array2<f64> = random_diagonal(dim, (-1.0, 1000.0), 1, 23); let tmp = q1.dot(&q2.dot(&q3)); let a = tmp.dot(&d.dot(&tmp.t())); b.iter(|| { black_box(a.mod_cholesky_se90()); }); } #[bench] fn se90_128x128_nd(b: &mut Bencher) { let dim = 128; let q1: ndarray::Array2<f64> = random_householder(dim, 2); let q2: ndarray::Array2<f64> = random_householder(dim, 9); let q3: ndarray::Array2<f64> = random_householder(dim, 90); let d: ndarray::Array2<f64> = random_diagonal(dim, (-1.0, 1000.0), 1, 23); let tmp = q1.dot(&q2.dot(&q3)); let a = tmp.dot(&d.dot(&tmp.t())); b.iter(|| { black_box(a.mod_cholesky_se90()); }); } #[bench] fn se90_256x256_nd(b: &mut Bencher) { let dim = 256; let q1: ndarray::Array2<f64> = random_householder(dim, 2); let q2: ndarray::Array2<f64> = random_householder(dim, 9); let q3: ndarray::Array2<f64> = random_householder(dim, 90); let d: ndarray::Array2<f64> = random_diagonal(dim, (-1.0, 1000.0), 1, 23); let tmp = q1.dot(&q2.dot(&q3)); let a = tmp.dot(&d.dot(&tmp.t())); b.iter(|| { black_box(a.mod_cholesky_se90()); }); } #[bench] fn se99_3x3_nd(b: &mut Bencher) { let a: ndarray::Array2<f64> = ndarray::arr2(&[[1.0, 1.0, 2.0], [1.0, 1.0, 3.0], [2.0, 3.0, 1.0]]); b.iter(|| { black_box(a.mod_cholesky_se99()); }); } #[bench] fn se99_4x4_nd(b: &mut Bencher) { let a: ndarray::Array2<f64> = ndarray::arr2(&[ [1890.3, -1705.6, -315.8, 3000.3], [-1705.6, 1538.3, 284.9, -2706.6], [-315.8, 284.9, 52.5, -501.2], [3000.3, -2706.6, -501.2, 4760.8], ]); b.iter(|| { black_box(a.mod_cholesky_se99()); }); } #[bench] fn se99_12x12_nd(b: &mut Bencher) { let dim = 12; let q1: ndarray::Array2<f64> = random_householder(dim, 2); let q2: ndarray::Array2<f64> = random_householder(dim, 9); let q3: ndarray::Array2<f64> = random_householder(dim, 90); let d: ndarray::Array2<f64> = random_diagonal(dim, (-1.0, 1000.0), 1, 23); let tmp = q1.dot(&q2.dot(&q3)); let a = tmp.dot(&d.dot(&tmp.t())); b.iter(|| { black_box(a.mod_cholesky_se99()); }); } #[bench] fn se99_128x128_nd(b: &mut Bencher) { let dim = 128; let q1: ndarray::Array2<f64> = random_householder(dim, 2); let q2: ndarray::Array2<f64> = random_householder(dim, 9); let q3: ndarray::Array2<f64> = random_householder(dim, 90); let d: ndarray::Array2<f64> = random_diagonal(dim, (-1.0, 1000.0), 1, 23); let tmp = q1.dot(&q2.dot(&q3)); let a = tmp.dot(&d.dot(&tmp.t())); b.iter(|| { black_box(a.mod_cholesky_se99()); }); } #[bench] fn se99_256x256_nd(b: &mut Bencher) { let dim = 256; let q1: ndarray::Array2<f64> = random_householder(dim, 2); let q2: ndarray::Array2<f64> = random_householder(dim, 9); let q3: ndarray::Array2<f64> = random_householder(dim, 90); let d: ndarray::Array2<f64> = random_diagonal(dim, (-1.0, 1000.0), 1, 23); let tmp = q1.dot(&q2.dot(&q3)); let a = tmp.dot(&d.dot(&tmp.t())); b.iter(|| { black_box(a.mod_cholesky_se99()); }); } }
use std::io::Read; use std::str::FromStr; use std::{fs::File, sync::Arc}; use anyhow::{anyhow, Result}; use druid::KbKey; use druid::{ Color, Data, Env, EventCtx, ExtEventSink, KeyEvent, Modifiers, Target, WidgetId, WindowId, }; use toml; use crate::{ command::LapceCommand, state::{LapceFocus, LapceTabState, LapceUIState, Mode, LAPCE_APP_STATE}, }; #[derive(PartialEq)] enum KeymapMatch { Full, Prefix, } #[derive(PartialEq, Eq, Hash, Default, Clone)] pub struct KeyPress { pub key: druid::keyboard_types::Key, pub mods: Modifiers, } #[derive(PartialEq, Eq, Hash, Clone)] pub struct KeyMap { pub key: Vec<KeyPress>, pub modes: Vec<Mode>, pub when: Option<String>, pub command: String, } pub struct KeyPressState { window_id: WindowId, tab_id: WidgetId, pending_keypress: Vec<KeyPress>, count: Option<usize>, keymaps: Vec<KeyMap>, } impl KeyPressState { pub fn new(window_id: WindowId, tab_id: WidgetId) -> KeyPressState { KeyPressState { window_id, tab_id, pending_keypress: Vec::new(), count: None, keymaps: Self::get_keymaps().unwrap_or(Vec::new()), } } fn get_keymaps() -> Result<Vec<KeyMap>> { let mut keymaps = Vec::new(); let mut f = File::open("/Users/Lulu/lapce/.lapce/keymaps.toml")?; let mut content = vec![]; f.read_to_end(&mut content)?; let toml_keymaps: toml::Value = toml::from_slice(&content)?; let toml_keymaps = toml_keymaps .get("keymaps") .and_then(|v| v.as_array()) .ok_or(anyhow!("no keymaps"))?; for toml_keymap in toml_keymaps { if let Ok(keymap) = Self::get_keymap(toml_keymap) { keymaps.push(keymap); } } Ok(keymaps) } fn get_keymap(toml_keymap: &toml::Value) -> Result<KeyMap> { let key = toml_keymap .get("key") .and_then(|v| v.as_str()) .ok_or(anyhow!("no key in keymap"))?; let mut keypresses = Vec::new(); for k in key.split(" ") { let mut keypress = KeyPress::default(); for (i, part) in k.split("+").collect::<Vec<&str>>().iter().rev().enumerate() { if i == 0 { keypress.key = match part.to_lowercase().as_ref() { "escape" => druid::keyboard_types::Key::Escape, "esc" => druid::keyboard_types::Key::Escape, "delete" => druid::keyboard_types::Key::Delete, "backspace" => druid::keyboard_types::Key::Backspace, "bs" => druid::keyboard_types::Key::Backspace, "arrowup" => druid::keyboard_types::Key::ArrowUp, "arrowdown" => druid::keyboard_types::Key::ArrowDown, "arrowright" => druid::keyboard_types::Key::ArrowRight, "arrowleft" => druid::keyboard_types::Key::ArrowLeft, "tab" => druid::keyboard_types::Key::Tab, "enter" => druid::keyboard_types::Key::Enter, "del" => druid::keyboard_types::Key::Delete, _ => druid::keyboard_types::Key::Character(part.to_string()), } } else { match part.to_lowercase().as_ref() { "ctrl" => keypress.mods.set(Modifiers::CONTROL, true), "meta" => keypress.mods.set(Modifiers::META, true), "shift" => keypress.mods.set(Modifiers::SHIFT, true), "alt" => keypress.mods.set(Modifiers::ALT, true), _ => (), } } } keypresses.push(keypress); } Ok(KeyMap { key: keypresses, modes: Self::get_modes(toml_keymap), when: toml_keymap .get("when") .and_then(|w| w.as_str()) .map(|w| w.to_string()), command: toml_keymap .get("command") .and_then(|c| c.as_str()) .map(|w| w.trim().to_string()) .unwrap_or("".to_string()), }) } fn get_modes(toml_keymap: &toml::Value) -> Vec<Mode> { toml_keymap .get("mode") .and_then(|v| v.as_str()) .map(|m| { m.chars() .filter_map(|c| match c.to_lowercase().to_string().as_ref() { "i" => Some(Mode::Insert), "n" => Some(Mode::Normal), "v" => Some(Mode::Visual), _ => None, }) .collect() }) .unwrap_or(Vec::new()) } pub fn key_down( &mut self, ctx: &mut EventCtx, ui_state: &mut LapceUIState, key_event: &KeyEvent, env: &Env, ) { if key_event.key == KbKey::Shift { return; } let mut mods = key_event.mods.clone(); mods.set(Modifiers::SHIFT, false); let keypress = KeyPress { key: key_event.key.clone(), mods, }; let mode = LAPCE_APP_STATE .get_tab_state(&self.window_id, &self.tab_id) .get_mode(); if self.handle_count(&mode, &keypress) { return; } let mut full_match_keymap = None; let mut keypresses = self.pending_keypress.clone(); keypresses.push(keypress.clone()); for keymap in self.keymaps.iter() { if let Some(match_result) = self.match_keymap_new(&mode, &keypresses, keymap) { match match_result { KeymapMatch::Full => { if full_match_keymap.is_none() { full_match_keymap = Some(keymap.clone()); } } KeymapMatch::Prefix => { self.pending_keypress.push(keypress.clone()); return; } } } } let pending_keypresses = self.pending_keypress.clone(); self.pending_keypress = Vec::new(); if let Some(keymap) = full_match_keymap { LAPCE_APP_STATE .get_tab_state(&self.window_id, &self.tab_id) .run_command(ctx, ui_state, self.take_count(), &keymap.command, env); return; } if pending_keypresses.len() > 0 { let mut full_match_keymap = None; for keymap in self.keymaps.iter() { if let Some(match_result) = self.match_keymap_new(&mode, &pending_keypresses, keymap) { if match_result == KeymapMatch::Full { if full_match_keymap.is_none() { full_match_keymap = Some(keymap.clone()); } } } } if let Some(keymap) = full_match_keymap { LAPCE_APP_STATE .get_tab_state(&self.window_id, &self.tab_id) .run_command( ctx, ui_state, self.take_count(), &keymap.command, env, ); self.key_down(ctx, ui_state, key_event, env); return; } } if mode != Mode::Insert { self.handle_count(&mode, &keypress); return; } self.count = None; if mods.is_empty() { match &key_event.key { druid::keyboard_types::Key::Character(c) => { LAPCE_APP_STATE .get_tab_state(&self.window_id, &self.tab_id) .insert(ctx, ui_state, c, env); } _ => (), } } } pub fn take_count(&mut self) -> Option<usize> { self.count.take() } fn match_keymap_new( &self, mode: &Mode, keypresses: &Vec<KeyPress>, keymap: &KeyMap, ) -> Option<KeymapMatch> { let match_result = if keymap.key.len() > keypresses.len() { if keymap.key[..keypresses.len()] == keypresses[..] { Some(KeymapMatch::Prefix) } else { None } } else if &keymap.key == keypresses { Some(KeymapMatch::Full) } else { None }; if !keymap.modes.is_empty() && !keymap.modes.contains(mode) { return None; } if let Some(condition) = &keymap.when { if !LAPCE_APP_STATE .get_tab_state(&self.window_id, &self.tab_id) .check_condition(condition) { return None; } } match_result } fn handle_count(&mut self, mode: &Mode, keypress: &KeyPress) -> bool { if mode == &Mode::Insert { return false; } match &keypress.key { druid::keyboard_types::Key::Character(c) => { if let Ok(n) = c.parse::<usize>() { if self.count.is_some() || n > 0 { self.count = Some(self.count.unwrap_or(0) * 10 + n); return true; } } } _ => (), } false } }
mod expression; mod select_item; pub(crate) use expression::ExprDb; pub(crate) use select_item::SelectDb;
use priv_prelude::*; use std; use future_utils; use spawn; /// Spawn a function into a new network namespace with a network interface described by `iface`. /// Returns a `SpawnComplete` which can be used to join the spawned thread, along with a channel which /// can be used to read/write ethernet frames to the spawned thread's interface. pub fn with_ether_iface<F, R>( handle: &Handle, iface: EtherIfaceBuilder, func: F, ) -> (SpawnComplete<R>, EtherPlug) where R: Send + 'static, F: FnOnce() -> R + Send + 'static, { let (tx, rx) = std::sync::mpsc::channel(); let spawn_complete = spawn::new_namespace(move || { trace!("building tap {:?}", iface); let (drop_tx, drop_rx) = future_utils::drop_notify(); let tap_unbound = unwrap!(iface.build_unbound()); unwrap!(tx.send((tap_unbound, drop_rx))); let ret = func(); drop(drop_tx); ret }); let (tap_unbound, drop_rx) = unwrap!(rx.recv()); let tap = tap_unbound.bind(handle); let (plug_a, plug_b) = EtherPlug::new_wire(); let task = TapTask { tap: tap, handle: handle.clone(), frame_tx: plug_a.tx, frame_rx: plug_a.rx, sending_frame: None, state: TapTaskState::Receiving { drop_rx: drop_rx, }, }; handle.spawn(task.infallible()); (spawn_complete, plug_b) } struct TapTask { tap: EtherIface, frame_tx: UnboundedSender<EtherFrame>, frame_rx: UnboundedReceiver<EtherFrame>, sending_frame: Option<EtherFrame>, handle: Handle, state: TapTaskState, } enum TapTaskState { Receiving { drop_rx: DropNotice, }, Dying(Timeout), Invalid, } impl Future for TapTask { type Item = (); type Error = Void; fn poll(&mut self) -> Result<Async<()>, Void> { let grace_period: Duration = Duration::from_millis(100); let mut received_frames = false; loop { match self.tap.poll() { Ok(Async::Ready(Some(frame))) => { let _ = self.frame_tx.unbounded_send(frame); received_frames = true; }, Ok(Async::Ready(None)) => { panic!("TAP stream ended somehow"); }, Ok(Async::NotReady) => break, Err(e) => { panic!("reading TAP device yielded an error: {}", e); }, } } loop { if let Some(frame) = self.sending_frame.take() { match self.tap.start_send(frame) { Ok(AsyncSink::Ready) => (), Ok(AsyncSink::NotReady(frame)) => { self.sending_frame = Some(frame); break; }, Err(e) => { panic!("writing TAP device yielded an error: {}", e); }, } } match self.frame_rx.poll().void_unwrap() { Async::Ready(Some(frame)) => { self.sending_frame = Some(frame); continue; }, _ => break, } } match self.tap.poll_complete() { Ok(..) => (), Err(e) => { panic!("completing TAP device write yielded an error: {}", e); }, } let mut state = mem::replace(&mut self.state, TapTaskState::Invalid); trace!("polling TapTask"); loop { match state { TapTaskState::Receiving { mut drop_rx, } => { trace!("state == receiving"); match drop_rx.poll().void_unwrap() { Async::Ready(()) => { state = TapTaskState::Dying(Timeout::new(grace_period, &self.handle)); continue; }, Async::NotReady => { state = TapTaskState::Receiving { drop_rx }; break; }, } }, TapTaskState::Dying(mut timeout) => { trace!("state == dying"); if received_frames { timeout.reset(Instant::now() + grace_period); } match timeout.poll().void_unwrap() { Async::Ready(()) => { return Ok(Async::Ready(())); }, Async::NotReady => { state = TapTaskState::Dying(timeout); break; }, } } TapTaskState::Invalid => { panic!("TapTask in invalid state!"); }, } } self.state = state; Ok(Async::NotReady) } } #[cfg(test)] mod test { use priv_prelude::*; use super::*; use rand; use std; use void; #[test] fn one_interface_send_udp() { run_test(3, || { let mut core = unwrap!(Core::new()); let handle = core.handle(); let res = core.run(future::lazy(|| { trace!("starting"); let subnet = SubnetV4::random_local(); let iface_ip = subnet.random_client_addr(); let gateway_ip = subnet.gateway_ip(); let iface = { EtherIfaceBuilder::new() .address(iface_ip) .netmask(subnet.netmask()) .route(RouteV4::new( SubnetV4::new(ipv4!("0.0.0.0"), 0), Some(gateway_ip), )) }; let payload: [u8; 8] = rand::random(); let target_ip = Ipv4Addr::random_global(); let target_port = rand::random::<u16>() / 2 + 1000; let target_addr = SocketAddrV4::new(target_ip, target_port); trace!("spawning thread"); let (spawn_complete, EtherPlug { tx, rx }) = with_ether_iface( &handle, iface, move || { let socket = unwrap!(std::net::UdpSocket::bind(addr!("0.0.0.0:0"))); unwrap!(socket.send_to(&payload[..], SocketAddr::V4(target_addr))); trace!("sent udp packet"); }, ); let gateway_mac = MacAddr::random(); rx .into_future() .map_err(|(v, _rx)| void::unreachable(v)) .and_then(move |(frame_opt, rx)| { let frame = unwrap!(frame_opt); trace!("got frame from iface: {:?}", frame); let iface_mac = frame.source_mac(); let arp = match frame.payload() { EtherPayload::Arp(arp) => arp, payload => panic!("unexpected payload: {:?}", payload), }; assert_eq!(arp.fields(), ArpFields::Request { source_mac: iface_mac, source_ip: iface_ip, dest_ip: gateway_ip, }); let frame = EtherFrame::new_from_fields_recursive( EtherFields { source_mac: gateway_mac, dest_mac: iface_mac, }, EtherPayloadFields::Arp { fields: ArpFields::Response { source_mac: gateway_mac, source_ip: gateway_ip, dest_mac: iface_mac, dest_ip: iface_ip, }, }, ); tx .send(frame) .map_err(|_e| panic!("channel hung up!")) .and_then(|_tx| { rx .into_future() .map_err(|(v, _rx)| void::unreachable(v)) }) .and_then(move |(frame_opt, _rx)| { let frame = unwrap!(frame_opt); assert_eq!(frame.fields(), EtherFields { source_mac: iface_mac, dest_mac: gateway_mac, }); let ipv4 = match frame.payload() { EtherPayload::Ipv4(ipv4) => ipv4, payload => panic!("unexpected payload: {:?}", payload), }; assert_eq!(ipv4.source_ip(), iface_ip); assert_eq!(ipv4.dest_ip(), target_ip); let udp = match ipv4.payload() { Ipv4Payload::Udp(udp) => udp, payload => panic!("unexpected payload: {:?}", payload), }; assert_eq!(udp.dest_port(), target_port); assert_eq!(&udp.payload(), &payload[..]); spawn_complete .map_err(|e| panic::resume_unwind(e)) }) }) })); res.void_unwrap() }) } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(non_camel_case_types)] #![allow(unused_imports)] use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedRegistry { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ConnectedRegistryProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProxyResource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedRegistryProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<connected_registry_properties::ProvisioningState>, pub mode: connected_registry_properties::Mode, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, #[serde(rename = "connectionState", default, skip_serializing_if = "Option::is_none")] pub connection_state: Option<connected_registry_properties::ConnectionState>, #[serde(rename = "lastActivityTime", default, skip_serializing_if = "Option::is_none")] pub last_activity_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub activation: Option<ActivationProperties>, pub parent: ParentProperties, #[serde(rename = "clientTokenIds", default, skip_serializing_if = "Vec::is_empty")] pub client_token_ids: Vec<String>, #[serde(rename = "loginServer", default, skip_serializing_if = "Option::is_none")] pub login_server: Option<LoginServerProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub logging: Option<LoggingProperties>, #[serde(rename = "statusDetails", default, skip_serializing_if = "Vec::is_empty")] pub status_details: Vec<StatusDetailProperties>, } pub mod connected_registry_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Mode { Registry, Mirror, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ConnectionState { Online, Offline, Syncing, Unhealthy, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActivationProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<activation_properties::Status>, } pub mod activation_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Active, Inactive, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ParentProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "syncProperties")] pub sync_properties: SyncProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LoginServerProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub host: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tls: Option<TlsProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct LoggingProperties { #[serde(rename = "logLevel", default, skip_serializing_if = "Option::is_none")] pub log_level: Option<logging_properties::LogLevel>, #[serde(rename = "auditLogStatus", default, skip_serializing_if = "Option::is_none")] pub audit_log_status: Option<logging_properties::AuditLogStatus>, } pub mod logging_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LogLevel { Debug, Information, Warning, Error, None, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AuditLogStatus { Enabled, Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StatusDetailProperties { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, #[serde(rename = "correlationId", default, skip_serializing_if = "Option::is_none")] pub correlation_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncProperties { #[serde(rename = "tokenId")] pub token_id: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub schedule: Option<String>, #[serde(rename = "syncWindow", default, skip_serializing_if = "Option::is_none")] pub sync_window: Option<String>, #[serde(rename = "messageTtl")] pub message_ttl: String, #[serde(rename = "lastSyncTime", default, skip_serializing_if = "Option::is_none")] pub last_sync_time: Option<String>, #[serde(rename = "gatewayEndpoint", default, skip_serializing_if = "Option::is_none")] pub gateway_endpoint: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TlsProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<tls_properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub certificate: Option<TlsCertificateProperties>, } pub mod tls_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Enabled, Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TlsCertificateProperties { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<tls_certificate_properties::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, } pub mod tls_certificate_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { LocalDirectory, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedRegistryUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ConnectedRegistryUpdateProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedRegistryUpdateProperties { #[serde(rename = "syncProperties", default, skip_serializing_if = "Option::is_none")] pub sync_properties: Option<SyncUpdateProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub logging: Option<LoggingProperties>, #[serde(rename = "clientTokenIds", default, skip_serializing_if = "Vec::is_empty")] pub client_token_ids: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SyncUpdateProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub schedule: Option<String>, #[serde(rename = "syncWindow", default, skip_serializing_if = "Option::is_none")] pub sync_window: Option<String>, #[serde(rename = "messageTtl", default, skip_serializing_if = "Option::is_none")] pub message_ttl: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ConnectedRegistryListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ConnectedRegistry>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportPipeline { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<IdentityProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ExportPipelineProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IdentityProperties { #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<identity_properties::Type>, #[serde(rename = "userAssignedIdentities", default, skip_serializing_if = "Option::is_none")] pub user_assigned_identities: Option<serde_json::Value>, } pub mod identity_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { SystemAssigned, UserAssigned, #[serde(rename = "SystemAssigned, UserAssigned")] SystemAssignedUserAssigned, None, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportPipelineProperties { pub target: ExportPipelineTargetProperties, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub options: Vec<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<export_pipeline_properties::ProvisioningState>, } pub mod export_pipeline_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserIdentityProperties { #[serde(rename = "principalId", default, skip_serializing_if = "Option::is_none")] pub principal_id: Option<String>, #[serde(rename = "clientId", default, skip_serializing_if = "Option::is_none")] pub client_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportPipelineTargetProperties { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub uri: Option<String>, #[serde(rename = "keyVaultUri")] pub key_vault_uri: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportPipelineListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ExportPipeline>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportImageParameters { pub source: ImportSource, #[serde(rename = "targetTags", default, skip_serializing_if = "Vec::is_empty")] pub target_tags: Vec<String>, #[serde(rename = "untaggedTargetRepositories", default, skip_serializing_if = "Vec::is_empty")] pub untagged_target_repositories: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub mode: Option<import_image_parameters::Mode>, } pub mod import_image_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Mode { NoForce, Force, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportSource { #[serde(rename = "resourceId", default, skip_serializing_if = "Option::is_none")] pub resource_id: Option<String>, #[serde(rename = "registryUri", default, skip_serializing_if = "Option::is_none")] pub registry_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<ImportSourceCredentials>, #[serde(rename = "sourceImage")] pub source_image: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportSourceCredentials { #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, pub password: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportPipeline { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<IdentityProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ImportPipelineProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportPipelineProperties { pub source: ImportPipelineSourceProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub trigger: Option<PipelineTriggerProperties>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub options: Vec<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<import_pipeline_properties::ProvisioningState>, } pub mod import_pipeline_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportPipelineSourceProperties { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<import_pipeline_source_properties::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub uri: Option<String>, #[serde(rename = "keyVaultUri")] pub key_vault_uri: String, } pub mod import_pipeline_source_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { AzureStorageBlobContainer, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineTriggerProperties { #[serde(rename = "sourceTrigger", default, skip_serializing_if = "Option::is_none")] pub source_trigger: Option<PipelineSourceTriggerProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineSourceTriggerProperties { pub status: pipeline_source_trigger_properties::Status, } pub mod pipeline_source_trigger_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Enabled, Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportPipelineListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ImportPipeline>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryNameCheckRequest { pub name: String, #[serde(rename = "type")] pub type_: registry_name_check_request::Type, } pub mod registry_name_check_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { #[serde(rename = "Microsoft.ContainerRegistry/registries")] MicrosoftContainerRegistryRegistries, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryNameStatus { #[serde(rename = "nameAvailable", default, skip_serializing_if = "Option::is_none")] pub name_available: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reason: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<OperationDefinition>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub origin: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<OperationDisplayDefinition>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<OperationPropertiesDefinition>, #[serde(rename = "isDataAction", default, skip_serializing_if = "Option::is_none")] pub is_data_action: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationDisplayDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub provider: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub resource: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub operation: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationPropertiesDefinition { #[serde(rename = "serviceSpecification", default, skip_serializing_if = "Option::is_none")] pub service_specification: Option<OperationServiceSpecificationDefinition>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationServiceSpecificationDefinition { #[serde(rename = "metricSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub metric_specifications: Vec<OperationMetricSpecificationDefinition>, #[serde(rename = "logSpecifications", default, skip_serializing_if = "Vec::is_empty")] pub log_specifications: Vec<OperationLogSpecificationDefinition>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationMetricSpecificationDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "displayDescription", default, skip_serializing_if = "Option::is_none")] pub display_description: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "aggregationType", default, skip_serializing_if = "Option::is_none")] pub aggregation_type: Option<String>, #[serde(rename = "internalMetricName", default, skip_serializing_if = "Option::is_none")] pub internal_metric_name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationLogSpecificationDefinition { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "displayName", default, skip_serializing_if = "Option::is_none")] pub display_name: Option<String>, #[serde(rename = "blobDuration", default, skip_serializing_if = "Option::is_none")] pub blob_duration: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRun { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PipelineRunProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<pipeline_run_properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub request: Option<PipelineRunRequest>, #[serde(default, skip_serializing_if = "Option::is_none")] pub response: Option<PipelineRunResponse>, #[serde(rename = "forceUpdateTag", default, skip_serializing_if = "Option::is_none")] pub force_update_tag: Option<String>, } pub mod pipeline_run_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunRequest { #[serde(rename = "pipelineResourceId", default, skip_serializing_if = "Option::is_none")] pub pipeline_resource_id: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub artifacts: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<PipelineRunSourceProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<PipelineRunTargetProperties>, #[serde(rename = "catalogDigest", default, skip_serializing_if = "Option::is_none")] pub catalog_digest: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<String>, #[serde(rename = "importedArtifacts", default, skip_serializing_if = "Vec::is_empty")] pub imported_artifacts: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub progress: Option<ProgressProperties>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "finishTime", default, skip_serializing_if = "Option::is_none")] pub finish_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<ImportPipelineSourceProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<ExportPipelineTargetProperties>, #[serde(rename = "catalogDigest", default, skip_serializing_if = "Option::is_none")] pub catalog_digest: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub trigger: Option<PipelineTriggerDescriptor>, #[serde(rename = "pipelineRunErrorMessage", default, skip_serializing_if = "Option::is_none")] pub pipeline_run_error_message: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunSourceProperties { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<pipeline_run_source_properties::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } pub mod pipeline_run_source_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { AzureStorageBlob, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunTargetProperties { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<pipeline_run_target_properties::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } pub mod pipeline_run_target_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { AzureStorageBlob, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ProgressProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub percentage: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineTriggerDescriptor { #[serde(rename = "sourceTrigger", default, skip_serializing_if = "Option::is_none")] pub source_trigger: Option<PipelineSourceTriggerDescriptor>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineSourceTriggerDescriptor { #[serde(default, skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PipelineRunListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<PipelineRun>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnection { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PrivateEndpointConnectionProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnectionProperties { #[serde(rename = "privateEndpoint", default, skip_serializing_if = "Option::is_none")] pub private_endpoint: Option<PrivateEndpoint>, #[serde(rename = "privateLinkServiceConnectionState", default, skip_serializing_if = "Option::is_none")] pub private_link_service_connection_state: Option<PrivateLinkServiceConnectionState>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<private_endpoint_connection_properties::ProvisioningState>, } pub mod private_endpoint_connection_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpoint { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkServiceConnectionState { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<private_link_service_connection_state::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "actionsRequired", default, skip_serializing_if = "Option::is_none")] pub actions_required: Option<private_link_service_connection_state::ActionsRequired>, } pub mod private_link_service_connection_state { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Approved, Pending, Rejected, Disconnected, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ActionsRequired { None, Recreate, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnectionListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<PrivateEndpointConnection>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Registry { #[serde(flatten)] pub resource: Resource, pub sku: Sku, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<IdentityProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegistryProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Sku { pub name: sku::Name, #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<sku::Tier>, } pub mod sku { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { Classic, Basic, Standard, Premium, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Tier { Classic, Basic, Standard, Premium, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryProperties { #[serde(rename = "loginServer", default, skip_serializing_if = "Option::is_none")] pub login_server: Option<String>, #[serde(rename = "creationDate", default, skip_serializing_if = "Option::is_none")] pub creation_date: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<registry_properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<Status>, #[serde(rename = "adminUserEnabled", default, skip_serializing_if = "Option::is_none")] pub admin_user_enabled: Option<bool>, #[serde(rename = "networkRuleSet", default, skip_serializing_if = "Option::is_none")] pub network_rule_set: Option<NetworkRuleSet>, #[serde(default, skip_serializing_if = "Option::is_none")] pub policies: Option<Policies>, #[serde(default, skip_serializing_if = "Option::is_none")] pub encryption: Option<EncryptionProperty>, #[serde(rename = "dataEndpointEnabled", default, skip_serializing_if = "Option::is_none")] pub data_endpoint_enabled: Option<bool>, #[serde(rename = "dataEndpointHostNames", default, skip_serializing_if = "Vec::is_empty")] pub data_endpoint_host_names: Vec<String>, #[serde(rename = "privateEndpointConnections", default, skip_serializing_if = "Vec::is_empty")] pub private_endpoint_connections: Vec<PrivateEndpointConnection>, #[serde(rename = "publicNetworkAccess", default, skip_serializing_if = "Option::is_none")] pub public_network_access: Option<registry_properties::PublicNetworkAccess>, #[serde(rename = "networkRuleBypassOptions", default, skip_serializing_if = "Option::is_none")] pub network_rule_bypass_options: Option<registry_properties::NetworkRuleBypassOptions>, #[serde(rename = "zoneRedundancy", default, skip_serializing_if = "Option::is_none")] pub zone_redundancy: Option<registry_properties::ZoneRedundancy>, #[serde(rename = "anonymousPullEnabled", default, skip_serializing_if = "Option::is_none")] pub anonymous_pull_enabled: Option<bool>, } pub mod registry_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PublicNetworkAccess { Enabled, Disabled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum NetworkRuleBypassOptions { AzureServices, None, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ZoneRedundancy { Enabled, Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Status { #[serde(rename = "displayStatus", default, skip_serializing_if = "Option::is_none")] pub display_status: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NetworkRuleSet { #[serde(rename = "defaultAction")] pub default_action: network_rule_set::DefaultAction, #[serde(rename = "virtualNetworkRules", default, skip_serializing_if = "Vec::is_empty")] pub virtual_network_rules: Vec<VirtualNetworkRule>, #[serde(rename = "ipRules", default, skip_serializing_if = "Vec::is_empty")] pub ip_rules: Vec<IpRule>, } pub mod network_rule_set { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DefaultAction { Allow, Deny, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Policies { #[serde(rename = "quarantinePolicy", default, skip_serializing_if = "Option::is_none")] pub quarantine_policy: Option<QuarantinePolicy>, #[serde(rename = "trustPolicy", default, skip_serializing_if = "Option::is_none")] pub trust_policy: Option<TrustPolicy>, #[serde(rename = "retentionPolicy", default, skip_serializing_if = "Option::is_none")] pub retention_policy: Option<RetentionPolicy>, #[serde(rename = "exportPolicy", default, skip_serializing_if = "Option::is_none")] pub export_policy: Option<ExportPolicy>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EncryptionProperty { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<encryption_property::Status>, #[serde(rename = "keyVaultProperties", default, skip_serializing_if = "Option::is_none")] pub key_vault_properties: Option<KeyVaultProperties>, } pub mod encryption_property { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct VirtualNetworkRule { #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option<virtual_network_rule::Action>, pub id: String, } pub mod virtual_network_rule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Action { Allow, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IpRule { #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option<ip_rule::Action>, pub value: String, } pub mod ip_rule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Action { Allow, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct QuarantinePolicy { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<quarantine_policy::Status>, } pub mod quarantine_policy { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TrustPolicy { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<trust_policy::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<trust_policy::Status>, } pub mod trust_policy { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Notary, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RetentionPolicy { #[serde(default, skip_serializing_if = "Option::is_none")] pub days: Option<i32>, #[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")] pub last_updated_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<retention_policy::Status>, } pub mod retention_policy { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportPolicy { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<export_policy::Status>, } pub mod export_policy { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KeyVaultProperties { #[serde(rename = "keyIdentifier", default, skip_serializing_if = "Option::is_none")] pub key_identifier: Option<String>, #[serde(rename = "versionedKeyIdentifier", default, skip_serializing_if = "Option::is_none")] pub versioned_key_identifier: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<String>, #[serde(rename = "keyRotationEnabled", default, skip_serializing_if = "Option::is_none")] pub key_rotation_enabled: Option<bool>, #[serde(rename = "lastKeyRotationTimestamp", default, skip_serializing_if = "Option::is_none")] pub last_key_rotation_timestamp: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<IdentityProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub sku: Option<Sku>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RegistryPropertiesUpdateParameters>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryPropertiesUpdateParameters { #[serde(rename = "adminUserEnabled", default, skip_serializing_if = "Option::is_none")] pub admin_user_enabled: Option<bool>, #[serde(rename = "networkRuleSet", default, skip_serializing_if = "Option::is_none")] pub network_rule_set: Option<NetworkRuleSet>, #[serde(default, skip_serializing_if = "Option::is_none")] pub policies: Option<Policies>, #[serde(default, skip_serializing_if = "Option::is_none")] pub encryption: Option<EncryptionProperty>, #[serde(rename = "dataEndpointEnabled", default, skip_serializing_if = "Option::is_none")] pub data_endpoint_enabled: Option<bool>, #[serde(rename = "publicNetworkAccess", default, skip_serializing_if = "Option::is_none")] pub public_network_access: Option<registry_properties_update_parameters::PublicNetworkAccess>, #[serde(rename = "networkRuleBypassOptions", default, skip_serializing_if = "Option::is_none")] pub network_rule_bypass_options: Option<registry_properties_update_parameters::NetworkRuleBypassOptions>, #[serde(rename = "anonymousPullEnabled", default, skip_serializing_if = "Option::is_none")] pub anonymous_pull_enabled: Option<bool>, } pub mod registry_properties_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PublicNetworkAccess { Enabled, Disabled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum NetworkRuleBypassOptions { AzureServices, None, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Registry>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryListCredentialsResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub passwords: Vec<RegistryPassword>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryPassword { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<registry_password::Name>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } pub mod registry_password { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "password")] Password, #[serde(rename = "password2")] Password2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegenerateCredentialParameters { pub name: regenerate_credential_parameters::Name, } pub mod regenerate_credential_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "password")] Password, #[serde(rename = "password2")] Password2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryUsageListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<RegistryUsage>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryUsage { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<i64>, #[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")] pub current_value: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<registry_usage::Unit>, } pub mod registry_usage { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Unit { Count, Bytes, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResourceListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<PrivateLinkResource>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResource { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<PrivateLinkResourceProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResourceProperties { #[serde(rename = "groupId", default, skip_serializing_if = "Option::is_none")] pub group_id: Option<String>, #[serde(rename = "requiredMembers", default, skip_serializing_if = "Vec::is_empty")] pub required_members: Vec<String>, #[serde(rename = "requiredZoneNames", default, skip_serializing_if = "Vec::is_empty")] pub required_zone_names: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Replication { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ReplicationProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReplicationProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<replication_properties::ProvisioningState>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<Status>, #[serde(rename = "regionEndpointEnabled", default, skip_serializing_if = "Option::is_none")] pub region_endpoint_enabled: Option<bool>, #[serde(rename = "zoneRedundancy", default, skip_serializing_if = "Option::is_none")] pub zone_redundancy: Option<replication_properties::ZoneRedundancy>, } pub mod replication_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ZoneRedundancy { Enabled, Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReplicationUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ReplicationUpdateParametersProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReplicationUpdateParametersProperties { #[serde(rename = "regionEndpointEnabled", default, skip_serializing_if = "Option::is_none")] pub region_endpoint_enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ReplicationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Replication>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMap { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ScopeMapProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMapProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(rename = "creationDate", default, skip_serializing_if = "Option::is_none")] pub creation_date: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<scope_map_properties::ProvisioningState>, pub actions: Vec<String>, } pub mod scope_map_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMapUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<ScopeMapPropertiesUpdateParameters>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMapPropertiesUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub description: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub actions: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ScopeMapListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<ScopeMap>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Token { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TokenProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenProperties { #[serde(rename = "creationDate", default, skip_serializing_if = "Option::is_none")] pub creation_date: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<token_properties::ProvisioningState>, #[serde(rename = "scopeMapId", default, skip_serializing_if = "Option::is_none")] pub scope_map_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<TokenCredentialsProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<token_properties::Status>, } pub mod token_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenCredentialsProperties { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub certificates: Vec<TokenCertificate>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub passwords: Vec<TokenPassword>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ActiveDirectoryObject { #[serde(rename = "objectId", default, skip_serializing_if = "Option::is_none")] pub object_id: Option<String>, #[serde(rename = "tenantId", default, skip_serializing_if = "Option::is_none")] pub tenant_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenCertificate { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<token_certificate::Name>, #[serde(default, skip_serializing_if = "Option::is_none")] pub expiry: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub thumbprint: Option<String>, #[serde(rename = "encodedPemCertificate", default, skip_serializing_if = "Option::is_none")] pub encoded_pem_certificate: Option<String>, } pub mod token_certificate { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "certificate1")] Certificate1, #[serde(rename = "certificate2")] Certificate2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenPassword { #[serde(rename = "creationTime", default, skip_serializing_if = "Option::is_none")] pub creation_time: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub expiry: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<token_password::Name>, #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, } pub mod token_password { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "password1")] Password1, #[serde(rename = "password2")] Password2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TokenUpdateProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenUpdateProperties { #[serde(rename = "scopeMapId", default, skip_serializing_if = "Option::is_none")] pub scope_map_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<token_update_properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<TokenCredentialsProperties>, } pub mod token_update_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TokenListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Token>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GenerateCredentialsParameters { #[serde(rename = "tokenId", default, skip_serializing_if = "Option::is_none")] pub token_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub expiry: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<generate_credentials_parameters::Name>, } pub mod generate_credentials_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { #[serde(rename = "password1")] Password1, #[serde(rename = "password2")] Password2, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GenerateCredentialsResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub username: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub passwords: Vec<TokenPassword>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Webhook { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WebhookProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<webhook_properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, pub actions: Vec<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<webhook_properties::ProvisioningState>, } pub mod webhook_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookCreateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, pub location: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WebhookPropertiesCreateParameters>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookPropertiesCreateParameters { #[serde(rename = "serviceUri")] pub service_uri: String, #[serde(rename = "customHeaders", default, skip_serializing_if = "Option::is_none")] pub custom_headers: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<webhook_properties_create_parameters::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, pub actions: Vec<String>, } pub mod webhook_properties_create_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<WebhookPropertiesUpdateParameters>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookPropertiesUpdateParameters { #[serde(rename = "serviceUri", default, skip_serializing_if = "Option::is_none")] pub service_uri: Option<String>, #[serde(rename = "customHeaders", default, skip_serializing_if = "Option::is_none")] pub custom_headers: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<webhook_properties_update_parameters::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub actions: Vec<String>, } pub mod webhook_properties_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "enabled")] Enabled, #[serde(rename = "disabled")] Disabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct WebhookListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Webhook>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CallbackConfig { #[serde(rename = "serviceUri")] pub service_uri: String, #[serde(rename = "customHeaders", default, skip_serializing_if = "Option::is_none")] pub custom_headers: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Event>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Event { #[serde(flatten)] pub event_info: EventInfo, #[serde(rename = "eventRequestMessage", default, skip_serializing_if = "Option::is_none")] pub event_request_message: Option<EventRequestMessage>, #[serde(rename = "eventResponseMessage", default, skip_serializing_if = "Option::is_none")] pub event_response_message: Option<EventResponseMessage>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventRequestMessage { #[serde(default, skip_serializing_if = "Option::is_none")] pub content: Option<EventContent>, #[serde(default, skip_serializing_if = "Option::is_none")] pub headers: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub method: Option<String>, #[serde(rename = "requestUri", default, skip_serializing_if = "Option::is_none")] pub request_uri: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventResponseMessage { #[serde(default, skip_serializing_if = "Option::is_none")] pub content: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub headers: Option<serde_json::Value>, #[serde(rename = "reasonPhrase", default, skip_serializing_if = "Option::is_none")] pub reason_phrase: Option<String>, #[serde(rename = "statusCode", default, skip_serializing_if = "Option::is_none")] pub status_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventContent { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<Target>, #[serde(default, skip_serializing_if = "Option::is_none")] pub request: Option<Request>, #[serde(default, skip_serializing_if = "Option::is_none")] pub actor: Option<Actor>, #[serde(default, skip_serializing_if = "Option::is_none")] pub source: Option<Source>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Target { #[serde(rename = "mediaType", default, skip_serializing_if = "Option::is_none")] pub media_type: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub size: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub digest: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub length: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub repository: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tag: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub version: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Request { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub addr: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub host: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub method: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub useragent: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Actor { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Source { #[serde(default, skip_serializing_if = "Option::is_none")] pub addr: Option<String>, #[serde(rename = "instanceID", default, skip_serializing_if = "Option::is_none")] pub instance_id: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Resource { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, pub location: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, #[serde(rename = "systemData", default, skip_serializing_if = "Option::is_none")] pub system_data: Option<SystemData>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SystemData { #[serde(rename = "createdBy", default, skip_serializing_if = "Option::is_none")] pub created_by: Option<String>, #[serde(rename = "createdByType", default, skip_serializing_if = "Option::is_none")] pub created_by_type: Option<system_data::CreatedByType>, #[serde(rename = "createdAt", default, skip_serializing_if = "Option::is_none")] pub created_at: Option<String>, #[serde(rename = "lastModifiedBy", default, skip_serializing_if = "Option::is_none")] pub last_modified_by: Option<String>, #[serde(rename = "lastModifiedByType", default, skip_serializing_if = "Option::is_none")] pub last_modified_by_type: Option<system_data::LastModifiedByType>, #[serde(rename = "lastModifiedAt", default, skip_serializing_if = "Option::is_none")] pub last_modified_at: Option<String>, } pub mod system_data { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum CreatedByType { User, Application, ManagedIdentity, Key, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LastModifiedByType { User, Application, ManagedIdentity, Key, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponse { #[serde(default, skip_serializing_if = "Option::is_none")] pub error: Option<ErrorResponseBody>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ErrorResponseBody { pub code: String, pub message: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<InnerErrorDescription>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct InnerErrorDescription { pub code: String, pub message: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentPool { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AgentPoolProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentPoolProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub os: Option<agent_pool_properties::Os>, #[serde(rename = "virtualNetworkSubnetResourceId", default, skip_serializing_if = "Option::is_none")] pub virtual_network_subnet_resource_id: Option<String>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<agent_pool_properties::ProvisioningState>, } pub mod agent_pool_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Os { Windows, Linux, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentPoolUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<AgentPoolPropertiesUpdateParameters>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentPoolPropertiesUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentPoolListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<AgentPool>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentPoolQueueStatus { #[serde(default, skip_serializing_if = "Option::is_none")] pub count: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RunRequest { #[serde(rename = "type")] pub type_: String, #[serde(rename = "isArchiveEnabled", default, skip_serializing_if = "Option::is_none")] pub is_archive_enabled: Option<bool>, #[serde(rename = "agentPoolName", default, skip_serializing_if = "Option::is_none")] pub agent_pool_name: Option<String>, #[serde(rename = "logTemplate", default, skip_serializing_if = "Option::is_none")] pub log_template: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Run { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RunProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RunProperties { #[serde(rename = "runId", default, skip_serializing_if = "Option::is_none")] pub run_id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<run_properties::Status>, #[serde(rename = "lastUpdatedTime", default, skip_serializing_if = "Option::is_none")] pub last_updated_time: Option<String>, #[serde(rename = "runType", default, skip_serializing_if = "Option::is_none")] pub run_type: Option<run_properties::RunType>, #[serde(rename = "agentPoolName", default, skip_serializing_if = "Option::is_none")] pub agent_pool_name: Option<String>, #[serde(rename = "createTime", default, skip_serializing_if = "Option::is_none")] pub create_time: Option<String>, #[serde(rename = "startTime", default, skip_serializing_if = "Option::is_none")] pub start_time: Option<String>, #[serde(rename = "finishTime", default, skip_serializing_if = "Option::is_none")] pub finish_time: Option<String>, #[serde(rename = "outputImages", default, skip_serializing_if = "Vec::is_empty")] pub output_images: Vec<ImageDescriptor>, #[serde(default, skip_serializing_if = "Option::is_none")] pub task: Option<String>, #[serde(rename = "imageUpdateTrigger", default, skip_serializing_if = "Option::is_none")] pub image_update_trigger: Option<ImageUpdateTrigger>, #[serde(rename = "sourceTrigger", default, skip_serializing_if = "Option::is_none")] pub source_trigger: Option<SourceTriggerDescriptor>, #[serde(rename = "timerTrigger", default, skip_serializing_if = "Option::is_none")] pub timer_trigger: Option<TimerTriggerDescriptor>, #[serde(default, skip_serializing_if = "Option::is_none")] pub platform: Option<PlatformProperties>, #[serde(rename = "agentConfiguration", default, skip_serializing_if = "Option::is_none")] pub agent_configuration: Option<AgentProperties>, #[serde(rename = "sourceRegistryAuth", default, skip_serializing_if = "Option::is_none")] pub source_registry_auth: Option<String>, #[serde(rename = "customRegistries", default, skip_serializing_if = "Vec::is_empty")] pub custom_registries: Vec<String>, #[serde(rename = "runErrorMessage", default, skip_serializing_if = "Option::is_none")] pub run_error_message: Option<String>, #[serde(rename = "updateTriggerToken", default, skip_serializing_if = "Option::is_none")] pub update_trigger_token: Option<String>, #[serde(rename = "logArtifact", default, skip_serializing_if = "Option::is_none")] pub log_artifact: Option<ImageDescriptor>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<run_properties::ProvisioningState>, #[serde(rename = "isArchiveEnabled", default, skip_serializing_if = "Option::is_none")] pub is_archive_enabled: Option<bool>, } pub mod run_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Queued, Started, Running, Succeeded, Failed, Canceled, Error, Timeout, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RunType { QuickBuild, QuickRun, AutoBuild, AutoRun, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImageDescriptor { #[serde(default, skip_serializing_if = "Option::is_none")] pub registry: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub repository: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tag: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub digest: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImageUpdateTrigger { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timestamp: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub images: Vec<ImageDescriptor>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SourceTriggerDescriptor { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "eventType", default, skip_serializing_if = "Option::is_none")] pub event_type: Option<String>, #[serde(rename = "commitId", default, skip_serializing_if = "Option::is_none")] pub commit_id: Option<String>, #[serde(rename = "pullRequestId", default, skip_serializing_if = "Option::is_none")] pub pull_request_id: Option<String>, #[serde(rename = "repositoryUrl", default, skip_serializing_if = "Option::is_none")] pub repository_url: Option<String>, #[serde(rename = "branchName", default, skip_serializing_if = "Option::is_none")] pub branch_name: Option<String>, #[serde(rename = "providerType", default, skip_serializing_if = "Option::is_none")] pub provider_type: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TimerTriggerDescriptor { #[serde(rename = "timerTriggerName", default, skip_serializing_if = "Option::is_none")] pub timer_trigger_name: Option<String>, #[serde(rename = "scheduleOccurrence", default, skip_serializing_if = "Option::is_none")] pub schedule_occurrence: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PlatformProperties { pub os: platform_properties::Os, #[serde(default, skip_serializing_if = "Option::is_none")] pub architecture: Option<platform_properties::Architecture>, #[serde(default, skip_serializing_if = "Option::is_none")] pub variant: Option<platform_properties::Variant>, } pub mod platform_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Os { Windows, Linux, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Architecture { #[serde(rename = "amd64")] Amd64, #[serde(rename = "x86")] X86, #[serde(rename = "386")] N386, #[serde(rename = "arm")] Arm, #[serde(rename = "arm64")] Arm64, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Variant { #[serde(rename = "v6")] V6, #[serde(rename = "v7")] V7, #[serde(rename = "v8")] V8, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AgentProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub cpu: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SourceUploadDefinition { #[serde(rename = "uploadUrl", default, skip_serializing_if = "Option::is_none")] pub upload_url: Option<String>, #[serde(rename = "relativePath", default, skip_serializing_if = "Option::is_none")] pub relative_path: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RunListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Run>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RunFilter { #[serde(rename = "runId", default, skip_serializing_if = "Option::is_none")] pub run_id: Option<String>, #[serde(rename = "runType", default, skip_serializing_if = "Option::is_none")] pub run_type: Option<run_filter::RunType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<run_filter::Status>, #[serde(rename = "createTime", default, skip_serializing_if = "Option::is_none")] pub create_time: Option<String>, #[serde(rename = "finishTime", default, skip_serializing_if = "Option::is_none")] pub finish_time: Option<String>, #[serde(rename = "outputImageManifests", default, skip_serializing_if = "Option::is_none")] pub output_image_manifests: Option<String>, #[serde(rename = "isArchiveEnabled", default, skip_serializing_if = "Option::is_none")] pub is_archive_enabled: Option<bool>, #[serde(rename = "taskName", default, skip_serializing_if = "Option::is_none")] pub task_name: Option<String>, #[serde(rename = "agentPoolName", default, skip_serializing_if = "Option::is_none")] pub agent_pool_name: Option<String>, } pub mod run_filter { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RunType { QuickBuild, QuickRun, AutoBuild, AutoRun, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Queued, Started, Running, Succeeded, Failed, Canceled, Error, Timeout, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RunUpdateParameters { #[serde(rename = "isArchiveEnabled", default, skip_serializing_if = "Option::is_none")] pub is_archive_enabled: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RunGetLogResult { #[serde(rename = "logLink", default, skip_serializing_if = "Option::is_none")] pub log_link: Option<String>, #[serde(rename = "logArtifactLink", default, skip_serializing_if = "Option::is_none")] pub log_artifact_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskRun { #[serde(flatten)] pub proxy_resource: ProxyResource, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<IdentityProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TaskRunProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskRunProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<task_run_properties::ProvisioningState>, #[serde(rename = "runRequest", default, skip_serializing_if = "Option::is_none")] pub run_request: Option<RunRequest>, #[serde(rename = "runResult", default, skip_serializing_if = "Option::is_none")] pub run_result: Option<Run>, #[serde(rename = "forceUpdateTag", default, skip_serializing_if = "Option::is_none")] pub force_update_tag: Option<String>, } pub mod task_run_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskRunUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<IdentityProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TaskRunPropertiesUpdateParameters>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskRunPropertiesUpdateParameters { #[serde(rename = "runRequest", default, skip_serializing_if = "Option::is_none")] pub run_request: Option<RunRequest>, #[serde(rename = "forceUpdateTag", default, skip_serializing_if = "Option::is_none")] pub force_update_tag: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskRunListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<TaskRun>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Task>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Task { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<IdentityProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TaskProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskProperties { #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<task_properties::ProvisioningState>, #[serde(rename = "creationDate", default, skip_serializing_if = "Option::is_none")] pub creation_date: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<task_properties::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub platform: Option<PlatformProperties>, #[serde(rename = "agentConfiguration", default, skip_serializing_if = "Option::is_none")] pub agent_configuration: Option<AgentProperties>, #[serde(rename = "agentPoolName", default, skip_serializing_if = "Option::is_none")] pub agent_pool_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timeout: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub step: Option<TaskStepProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub trigger: Option<TriggerProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<Credentials>, #[serde(rename = "logTemplate", default, skip_serializing_if = "Option::is_none")] pub log_template: Option<String>, #[serde(rename = "isSystemTask", default, skip_serializing_if = "Option::is_none")] pub is_system_task: Option<bool>, } pub mod task_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ProvisioningState { Creating, Updating, Deleting, Succeeded, Failed, Canceled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Disabled, Enabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskStepProperties { #[serde(rename = "type")] pub type_: task_step_properties::Type, #[serde(rename = "baseImageDependencies", default, skip_serializing_if = "Vec::is_empty")] pub base_image_dependencies: Vec<BaseImageDependency>, #[serde(rename = "contextPath", default, skip_serializing_if = "Option::is_none")] pub context_path: Option<String>, #[serde(rename = "contextAccessToken", default, skip_serializing_if = "Option::is_none")] pub context_access_token: Option<String>, } pub mod task_step_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Docker, FileTask, EncodedTask, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggerProperties { #[serde(rename = "timerTriggers", default, skip_serializing_if = "Vec::is_empty")] pub timer_triggers: Vec<TimerTrigger>, #[serde(rename = "sourceTriggers", default, skip_serializing_if = "Vec::is_empty")] pub source_triggers: Vec<SourceTrigger>, #[serde(rename = "baseImageTrigger", default, skip_serializing_if = "Option::is_none")] pub base_image_trigger: Option<BaseImageTrigger>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Credentials { #[serde(rename = "sourceRegistry", default, skip_serializing_if = "Option::is_none")] pub source_registry: Option<SourceRegistryCredentials>, #[serde(rename = "customRegistries", default, skip_serializing_if = "Option::is_none")] pub custom_registries: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BaseImageDependency { #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<base_image_dependency::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub registry: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub repository: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tag: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub digest: Option<String>, } pub mod base_image_dependency { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { BuildTime, RunTime, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TimerTrigger { pub schedule: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<timer_trigger::Status>, pub name: String, } pub mod timer_trigger { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Disabled, Enabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SourceTrigger { #[serde(rename = "sourceRepository")] pub source_repository: SourceProperties, #[serde(rename = "sourceTriggerEvents")] pub source_trigger_events: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<source_trigger::Status>, pub name: String, } pub mod source_trigger { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Disabled, Enabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BaseImageTrigger { #[serde(rename = "baseImageTriggerType")] pub base_image_trigger_type: base_image_trigger::BaseImageTriggerType, #[serde(rename = "updateTriggerEndpoint", default, skip_serializing_if = "Option::is_none")] pub update_trigger_endpoint: Option<String>, #[serde(rename = "updateTriggerPayloadType", default, skip_serializing_if = "Option::is_none")] pub update_trigger_payload_type: Option<base_image_trigger::UpdateTriggerPayloadType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<base_image_trigger::Status>, pub name: String, } pub mod base_image_trigger { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum BaseImageTriggerType { All, Runtime, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum UpdateTriggerPayloadType { Default, Token, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Disabled, Enabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SourceRegistryCredentials { #[serde(rename = "loginMode", default, skip_serializing_if = "Option::is_none")] pub login_mode: Option<source_registry_credentials::LoginMode>, } pub mod source_registry_credentials { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum LoginMode { None, Default, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CustomRegistryCredentials { #[serde(rename = "userName", default, skip_serializing_if = "Option::is_none")] pub user_name: Option<SecretObject>, #[serde(default, skip_serializing_if = "Option::is_none")] pub password: Option<SecretObject>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SourceProperties { #[serde(rename = "sourceControlType")] pub source_control_type: source_properties::SourceControlType, #[serde(rename = "repositoryUrl")] pub repository_url: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub branch: Option<String>, #[serde(rename = "sourceControlAuthProperties", default, skip_serializing_if = "Option::is_none")] pub source_control_auth_properties: Option<AuthInfo>, } pub mod source_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SourceControlType { Github, VisualStudioTeamService, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SecretObject { #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<secret_object::Type>, } pub mod secret_object { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Opaque, Vaultsecret, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AuthInfo { #[serde(rename = "tokenType")] pub token_type: auth_info::TokenType, pub token: String, #[serde(rename = "refreshToken", default, skip_serializing_if = "Option::is_none")] pub refresh_token: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, #[serde(rename = "expiresIn", default, skip_serializing_if = "Option::is_none")] pub expires_in: Option<i32>, } pub mod auth_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TokenType { #[serde(rename = "PAT")] Pat, OAuth, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<IdentityProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<TaskPropertiesUpdateParameters>, #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskPropertiesUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<task_properties_update_parameters::Status>, #[serde(default, skip_serializing_if = "Option::is_none")] pub platform: Option<PlatformUpdateParameters>, #[serde(rename = "agentConfiguration", default, skip_serializing_if = "Option::is_none")] pub agent_configuration: Option<AgentProperties>, #[serde(rename = "agentPoolName", default, skip_serializing_if = "Option::is_none")] pub agent_pool_name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timeout: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub step: Option<TaskStepUpdateParameters>, #[serde(default, skip_serializing_if = "Option::is_none")] pub trigger: Option<TriggerUpdateParameters>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<Credentials>, #[serde(rename = "logTemplate", default, skip_serializing_if = "Option::is_none")] pub log_template: Option<String>, } pub mod task_properties_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Disabled, Enabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PlatformUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub os: Option<platform_update_parameters::Os>, #[serde(default, skip_serializing_if = "Option::is_none")] pub architecture: Option<platform_update_parameters::Architecture>, #[serde(default, skip_serializing_if = "Option::is_none")] pub variant: Option<platform_update_parameters::Variant>, } pub mod platform_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Os { Windows, Linux, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Architecture { #[serde(rename = "amd64")] Amd64, #[serde(rename = "x86")] X86, #[serde(rename = "386")] N386, #[serde(rename = "arm")] Arm, #[serde(rename = "arm64")] Arm64, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Variant { #[serde(rename = "v6")] V6, #[serde(rename = "v7")] V7, #[serde(rename = "v8")] V8, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskStepUpdateParameters { #[serde(rename = "type")] pub type_: task_step_update_parameters::Type, #[serde(rename = "contextPath", default, skip_serializing_if = "Option::is_none")] pub context_path: Option<String>, #[serde(rename = "contextAccessToken", default, skip_serializing_if = "Option::is_none")] pub context_access_token: Option<String>, } pub mod task_step_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { Docker, FileTask, EncodedTask, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TriggerUpdateParameters { #[serde(rename = "timerTriggers", default, skip_serializing_if = "Vec::is_empty")] pub timer_triggers: Vec<TimerTriggerUpdateParameters>, #[serde(rename = "sourceTriggers", default, skip_serializing_if = "Vec::is_empty")] pub source_triggers: Vec<SourceTriggerUpdateParameters>, #[serde(rename = "baseImageTrigger", default, skip_serializing_if = "Option::is_none")] pub base_image_trigger: Option<BaseImageTriggerUpdateParameters>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TimerTriggerUpdateParameters { #[serde(default, skip_serializing_if = "Option::is_none")] pub schedule: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<timer_trigger_update_parameters::Status>, pub name: String, } pub mod timer_trigger_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Disabled, Enabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SourceTriggerUpdateParameters { #[serde(rename = "sourceRepository", default, skip_serializing_if = "Option::is_none")] pub source_repository: Option<SourceUpdateParameters>, #[serde(rename = "sourceTriggerEvents", default, skip_serializing_if = "Vec::is_empty")] pub source_trigger_events: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<source_trigger_update_parameters::Status>, pub name: String, } pub mod source_trigger_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Disabled, Enabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct BaseImageTriggerUpdateParameters { #[serde(rename = "baseImageTriggerType", default, skip_serializing_if = "Option::is_none")] pub base_image_trigger_type: Option<base_image_trigger_update_parameters::BaseImageTriggerType>, #[serde(rename = "updateTriggerEndpoint", default, skip_serializing_if = "Option::is_none")] pub update_trigger_endpoint: Option<String>, #[serde(rename = "updateTriggerPayloadType", default, skip_serializing_if = "Option::is_none")] pub update_trigger_payload_type: Option<base_image_trigger_update_parameters::UpdateTriggerPayloadType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<base_image_trigger_update_parameters::Status>, pub name: String, } pub mod base_image_trigger_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum BaseImageTriggerType { All, Runtime, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum UpdateTriggerPayloadType { Default, Token, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Disabled, Enabled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SourceUpdateParameters { #[serde(rename = "sourceControlType", default, skip_serializing_if = "Option::is_none")] pub source_control_type: Option<source_update_parameters::SourceControlType>, #[serde(rename = "repositoryUrl", default, skip_serializing_if = "Option::is_none")] pub repository_url: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub branch: Option<String>, #[serde(rename = "sourceControlAuthProperties", default, skip_serializing_if = "Option::is_none")] pub source_control_auth_properties: Option<AuthInfoUpdateParameters>, } pub mod source_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum SourceControlType { Github, VisualStudioTeamService, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct AuthInfoUpdateParameters { #[serde(rename = "tokenType", default, skip_serializing_if = "Option::is_none")] pub token_type: Option<auth_info_update_parameters::TokenType>, #[serde(default, skip_serializing_if = "Option::is_none")] pub token: Option<String>, #[serde(rename = "refreshToken", default, skip_serializing_if = "Option::is_none")] pub refresh_token: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub scope: Option<String>, #[serde(rename = "expiresIn", default, skip_serializing_if = "Option::is_none")] pub expires_in: Option<i32>, } pub mod auth_info_update_parameters { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum TokenType { #[serde(rename = "PAT")] Pat, OAuth, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DockerBuildRequest { #[serde(flatten)] pub run_request: RunRequest, #[serde(rename = "imageNames", default, skip_serializing_if = "Vec::is_empty")] pub image_names: Vec<String>, #[serde(rename = "isPushEnabled", default, skip_serializing_if = "Option::is_none")] pub is_push_enabled: Option<bool>, #[serde(rename = "noCache", default, skip_serializing_if = "Option::is_none")] pub no_cache: Option<bool>, #[serde(rename = "dockerFilePath")] pub docker_file_path: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub arguments: Vec<Argument>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timeout: Option<i32>, pub platform: PlatformProperties, #[serde(rename = "agentConfiguration", default, skip_serializing_if = "Option::is_none")] pub agent_configuration: Option<AgentProperties>, #[serde(rename = "sourceLocation", default, skip_serializing_if = "Option::is_none")] pub source_location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<Credentials>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Argument { pub name: String, pub value: String, #[serde(rename = "isSecret", default, skip_serializing_if = "Option::is_none")] pub is_secret: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileTaskRunRequest { #[serde(flatten)] pub run_request: RunRequest, #[serde(rename = "taskFilePath")] pub task_file_path: String, #[serde(rename = "valuesFilePath", default, skip_serializing_if = "Option::is_none")] pub values_file_path: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<SetValue>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timeout: Option<i32>, pub platform: PlatformProperties, #[serde(rename = "agentConfiguration", default, skip_serializing_if = "Option::is_none")] pub agent_configuration: Option<AgentProperties>, #[serde(rename = "sourceLocation", default, skip_serializing_if = "Option::is_none")] pub source_location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<Credentials>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SetValue { pub name: String, pub value: String, #[serde(rename = "isSecret", default, skip_serializing_if = "Option::is_none")] pub is_secret: Option<bool>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TaskRunRequest { #[serde(flatten)] pub run_request: RunRequest, #[serde(rename = "taskId")] pub task_id: String, #[serde(rename = "overrideTaskStepProperties", default, skip_serializing_if = "Option::is_none")] pub override_task_step_properties: Option<OverrideTaskStepProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OverrideTaskStepProperties { #[serde(rename = "contextPath", default, skip_serializing_if = "Option::is_none")] pub context_path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub file: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub arguments: Vec<Argument>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<SetValue>, #[serde(rename = "updateTriggerToken", default, skip_serializing_if = "Option::is_none")] pub update_trigger_token: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EncodedTaskRunRequest { #[serde(flatten)] pub run_request: RunRequest, #[serde(rename = "encodedTaskContent")] pub encoded_task_content: String, #[serde(rename = "encodedValuesContent", default, skip_serializing_if = "Option::is_none")] pub encoded_values_content: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<SetValue>, #[serde(default, skip_serializing_if = "Option::is_none")] pub timeout: Option<i32>, pub platform: PlatformProperties, #[serde(rename = "agentConfiguration", default, skip_serializing_if = "Option::is_none")] pub agent_configuration: Option<AgentProperties>, #[serde(rename = "sourceLocation", default, skip_serializing_if = "Option::is_none")] pub source_location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub credentials: Option<Credentials>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DockerBuildStep { #[serde(flatten)] pub task_step_properties: TaskStepProperties, #[serde(rename = "imageNames", default, skip_serializing_if = "Vec::is_empty")] pub image_names: Vec<String>, #[serde(rename = "isPushEnabled", default, skip_serializing_if = "Option::is_none")] pub is_push_enabled: Option<bool>, #[serde(rename = "noCache", default, skip_serializing_if = "Option::is_none")] pub no_cache: Option<bool>, #[serde(rename = "dockerFilePath")] pub docker_file_path: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub arguments: Vec<Argument>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileTaskStep { #[serde(flatten)] pub task_step_properties: TaskStepProperties, #[serde(rename = "taskFilePath")] pub task_file_path: String, #[serde(rename = "valuesFilePath", default, skip_serializing_if = "Option::is_none")] pub values_file_path: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<SetValue>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EncodedTaskStep { #[serde(flatten)] pub task_step_properties: TaskStepProperties, #[serde(rename = "encodedTaskContent")] pub encoded_task_content: String, #[serde(rename = "encodedValuesContent", default, skip_serializing_if = "Option::is_none")] pub encoded_values_content: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<SetValue>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DockerBuildStepUpdateParameters { #[serde(flatten)] pub task_step_update_parameters: TaskStepUpdateParameters, #[serde(rename = "imageNames", default, skip_serializing_if = "Vec::is_empty")] pub image_names: Vec<String>, #[serde(rename = "isPushEnabled", default, skip_serializing_if = "Option::is_none")] pub is_push_enabled: Option<bool>, #[serde(rename = "noCache", default, skip_serializing_if = "Option::is_none")] pub no_cache: Option<bool>, #[serde(rename = "dockerFilePath", default, skip_serializing_if = "Option::is_none")] pub docker_file_path: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub arguments: Vec<Argument>, #[serde(default, skip_serializing_if = "Option::is_none")] pub target: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FileTaskStepUpdateParameters { #[serde(flatten)] pub task_step_update_parameters: TaskStepUpdateParameters, #[serde(rename = "taskFilePath", default, skip_serializing_if = "Option::is_none")] pub task_file_path: Option<String>, #[serde(rename = "valuesFilePath", default, skip_serializing_if = "Option::is_none")] pub values_file_path: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<SetValue>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EncodedTaskStepUpdateParameters { #[serde(flatten)] pub task_step_update_parameters: TaskStepUpdateParameters, #[serde(rename = "encodedTaskContent", default, skip_serializing_if = "Option::is_none")] pub encoded_task_content: Option<String>, #[serde(rename = "encodedValuesContent", default, skip_serializing_if = "Option::is_none")] pub encoded_values_content: Option<String>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub values: Vec<SetValue>, }
mod utils; mod fraction; mod primes; mod fib; mod queue; mod poker; use crate::utils::get_all_order; use std::collections::HashMap; use std::collections::HashSet; fn main() { let mut list = vec![]; for i in 3..=8 { list.push(P::new(i)); } let order_list: Vec<Vec<usize>> = get_all_order(&vec![0, 1, 2, 3, 4, 5]); for order in order_list { let mut check_list = list.clone(); let mut pass = false; let mut i = 0; let mut p0 = check_list[order[0]].clone(); let mut p1 = check_list[order[1]].clone(); let mut p2 = check_list[order[2]].clone(); let mut p3 = check_list[order[3]].clone(); let mut p4 = check_list[order[4]].clone(); let mut p5 = check_list[order[5]].clone(); while !pass { i += 1; println!("start: {}", i); p0.join_suf(&mut p1); p1.join_suf(&mut p2); p2.join_suf(&mut p3); p3.join_suf(&mut p4); p4.join_suf(&mut p5); p5.join_suf(&mut p0); pass = p0.check() && p1.check() && p2.check() && p3.check() && p4.check() && p5.check(); } println!("{:?}", p0); println!("{:?}", p1); println!("{:?}", p2); println!("{:?}", p3); println!("{:?}", p4); println!("{:?}", p5 ); } } #[derive(Debug, Clone)] struct P { size: i32, prefix: HashSet<i32>, suffix: HashSet<i32>, pre_map: HashMap<i32, HashSet<i32>>, suf_map: HashMap<i32, HashSet<i32>>, } impl P { fn new(size: i32) -> Self { let mut p = P { size, prefix: HashSet::new(), suffix: HashSet::new(), pre_map: HashMap::new(), suf_map: HashMap::new(), }; p._generate(); p } fn join_suf(&mut self, suf: &mut Self) { let suf_pre_set = &suf.prefix; let cur_suf_set = &self.suffix; let diff = Self::_cal_diff(suf_pre_set, cur_suf_set); for v in diff { suf._rm_pre(&v); } let suf_pre_set = &suf.prefix; let diff = Self::_cal_diff(cur_suf_set, suf_pre_set); for v in diff { self._rm_suf(&v); } } fn check(&self) -> bool { self.prefix.len() <= 1 && self.suffix.len() <= 1 } fn _generate(&mut self) { let mut i = 0; loop { i += 1; let res = cal(self.size, i); if res < 1000 { continue; } if res > 9999 { break; } let (pre, suf) = (res / 100, res % 100); if suf < 10 { continue; } self.prefix.insert(pre); self.suffix.insert(suf); self.pre_map.entry(pre) .and_modify(|x: &mut HashSet<i32>| { x.insert(suf); }) .or_insert_with(|| { let mut set = HashSet::new(); set.insert(suf); set }); self.suf_map.entry(suf) .and_modify(|x: &mut HashSet<i32>| { x.insert(pre); }) .or_insert_with(|| { let mut set = HashSet::new(); set.insert(pre); set }); } } fn _rm_pre(&mut self, pre: &i32) { if !self.prefix.contains(pre) { return; } self.prefix.remove(pre); let suf_set = self.pre_map.remove(pre).unwrap(); for suf in suf_set { let pre_set = self.suf_map.get_mut(&suf).unwrap(); pre_set.remove(pre); if pre_set.len() == 0 { self.suf_map.remove(&suf); self.suffix.remove(&suf); } } } fn _rm_suf(&mut self, suf: &i32) { if !self.suffix.contains(suf) { return; } self.suffix.remove(suf); let pre_set = self.suf_map.remove(suf).unwrap(); for pre in pre_set { let suf_set = self.pre_map.get_mut(&pre).unwrap(); suf_set.remove(suf); if suf_set.len() == 0 { self.pre_map.remove(&pre); self.prefix.remove(&pre); } } } fn _cal_diff(set_all: &HashSet<i32>, set_part: &HashSet<i32>) -> Vec<i32> { let mut res = vec![]; for v in set_all { if set_part.contains(v) { continue; } res.push(*v); } res } } fn cal(size: i32, n: i32) -> i32 { match size { 3 => n * (n + 1) / 2, 4 => n * n, 5 => n * (3 * n - 1) / 2, 6 => n * (2 * n - 1), 7 => n * (5 * n - 3) / 2, 8 => n * (3 * n - 2), _ => n } }
pub mod convert; pub mod validate;
extern crate midir; use std::error::Error; use std::io::{stdin, stdout, Write}; use std::thread::sleep; use std::time::Duration; use midir::{MidiOutput, MidiOutputPort}; fn main() { match run() { Ok(_) => (), Err(err) => println!("Error: {}", err), } } fn run() -> Result<(), Box<dyn Error>> { let midi_out = MidiOutput::new("My Test Output")?; // Get an output port (read from console if multiple are available) let out_ports = midi_out.ports(); let out_port: &MidiOutputPort = match out_ports.len() { 0 => return Err("no output port found".into()), 1 => { println!( "Choosing the only available output port: {}", midi_out.port_name(&out_ports[0]).unwrap() ); &out_ports[0] } _ => { println!("\nAvailable output ports:"); for (i, p) in out_ports.iter().enumerate() { println!("{}: {}", i, midi_out.port_name(p).unwrap()); } print!("Please select output port: "); stdout().flush()?; let mut input = String::new(); stdin().read_line(&mut input)?; out_ports .get(input.trim().parse::<usize>()?) .ok_or("invalid output port selected")? } }; println!("\nOpening connection"); let mut conn_out = midi_out.connect(out_port, "midir-test")?; println!("Connection open. Listen!"); { // Define a new scope in which the closure `play_note` borrows conn_out, so it can be called easily let mut play_note = |note: u8, duration: u64| { const NOTE_ON_MSG: u8 = 0x90; const NOTE_OFF_MSG: u8 = 0x80; const VELOCITY: u8 = 0x64; // We're ignoring errors in here let _ = conn_out.send(&[NOTE_ON_MSG, note, VELOCITY]); sleep(Duration::from_millis(duration * 150)); let _ = conn_out.send(&[NOTE_OFF_MSG, note, VELOCITY]); }; sleep(Duration::from_millis(4 * 150)); play_note(66, 4); play_note(65, 3); play_note(63, 1); play_note(61, 6); play_note(59, 2); play_note(58, 4); play_note(56, 4); play_note(54, 4); } sleep(Duration::from_millis(150)); println!("\nClosing connection"); // This is optional, the connection would automatically be closed as soon as it goes out of scope conn_out.close(); println!("Connection closed"); Ok(()) }
pub mod pull_requests;
use testutil::*; use seven_client::analytics::{AnalyticsParams, Analytics}; mod testutil; fn init_client() -> Analytics { Analytics::new(get_client()) } fn default_params() -> AnalyticsParams { AnalyticsParams { end: None, label: None, start: None, subaccounts: None, } } #[test] fn grouped_by_country() { let res = init_client().group_by_country(default_params()); assert!(res.is_ok()); } #[test] fn grouped_by_date() { let res = init_client().group_by_date(default_params()); assert!(res.is_ok()) } #[test] fn grouped_by_label() { let res = init_client().group_by_label(default_params()); assert!(res.is_ok()) } #[test] fn grouped_by_subaccount() { let res = init_client().group_by_subaccount(default_params()); assert!(res.is_ok()) }
use crate::renderer::managers::*; use crate::ui::get_text_character_rect; use crate::ui::text_character::CharacterSizeManager; use rider_config::{ConfigAccess, ConfigHolder}; use sdl2::rect::Rect; use sdl2::render::Texture; use sdl2::render::TextureCreator; use sdl2::ttf::Font; use sdl2::ttf::Sdl2TtfContext; use std::collections::HashMap; use std::rc::Rc; pub trait Renderer { fn load_font(&mut self, details: FontDetails) -> Rc<Font>; fn load_text_tex( &mut self, details: &mut TextDetails, font_details: FontDetails, ) -> Result<Rc<Texture>, String>; fn load_image(&mut self, path: String) -> Result<Rc<Texture>, String>; } #[cfg_attr(tarpaulin, skip)] pub struct CanvasRenderer<'l> { config: ConfigAccess, font_manager: FontManager<'l>, texture_manager: TextureManager<'l, sdl2::video::WindowContext>, character_sizes: HashMap<TextCharacterDetails, Rect>, } #[cfg_attr(tarpaulin, skip)] impl<'l> CanvasRenderer<'l> { pub fn new( config: ConfigAccess, font_context: &'l Sdl2TtfContext, texture_creator: &'l TextureCreator<sdl2::video::WindowContext>, ) -> Self { let texture_manager = TextureManager::new(&texture_creator); let font_manager = FontManager::new(&font_context); Self { config, font_manager, texture_manager, character_sizes: HashMap::new(), } } pub fn character_sizes_mut(&mut self) -> &mut HashMap<TextCharacterDetails, Rect> { &mut self.character_sizes } } #[cfg_attr(tarpaulin, skip)] impl<'l> CharacterSizeManager for CanvasRenderer<'l> { fn load_character_size(&mut self, c: char) -> Rect { let (font_path, font_size) = { let config = self.config().read().unwrap(); ( config.editor_config().font_path().to_string(), config.editor_config().character_size().clone(), ) }; let details = TextCharacterDetails { c: c.clone(), font_path: font_path.to_string(), font_size, }; self.character_sizes .get(&details) .cloned() .or_else(|| { let size = get_text_character_rect(c, self).unwrap(); self.character_sizes.insert(details.clone(), size.clone()); Some(size) }) .unwrap() .clone() } } #[cfg_attr(tarpaulin, skip)] impl<'l> ConfigHolder for CanvasRenderer<'l> { fn config(&self) -> &ConfigAccess { &self.config } } #[cfg_attr(tarpaulin, skip)] impl<'l> Renderer for CanvasRenderer<'l> { fn load_font(&mut self, details: FontDetails) -> Rc<Font> { self.font_manager .load(&details) .unwrap_or_else(|_| panic!("Font not found {:?}", details)) } fn load_text_tex( &mut self, details: &mut TextDetails, font_details: FontDetails, ) -> Result<Rc<Texture>, String> { use crate::renderer::managers::*; let font = self .font_manager .load(&font_details) .unwrap_or_else(|_| panic!("Font not found {:?}", details)); self.texture_manager.load_text(details, font) } fn load_image(&mut self, path: String) -> Result<Rc<Texture>, String> { self.texture_manager.load(path.as_str()) } }
use super::{u256mod, ModulusTrait}; // Comparison - equality and ordering // Equality impl<M: ModulusTrait> std::cmp::PartialEq for u256mod<M> { fn eq(&self, other: &u256mod<M>) -> bool { return self.value == other.value; } } impl<M: ModulusTrait> std::cmp::Eq for u256mod<M> {} // Ordering impl<M: ModulusTrait> Ord for u256mod<M> { fn cmp(&self, other: &Self) -> std::cmp::Ordering { return self.value.cmp(&other.value); } } impl<M: ModulusTrait> std::cmp::PartialOrd for u256mod<M> { fn partial_cmp(&self, other: &u256mod<M>) -> Option<std::cmp::Ordering> { return Some(self.cmp(other)); } } #[cfg(test)] mod tests { }
pub trait Real { fn zero() -> Self; } impl Real for f32 { #[inline] fn zero() -> f32 { 0.0f32 } } impl Real for f64 { #[inline] fn zero() -> f64 { 0.0f64 } }
fn naive(x: &[u8]) -> u64 { x.iter().fold(0, |a, b| a + b.count_ones() as u64) } /// Computes the [Hamming /// weight](https://en.wikipedia.org/wiki/Hamming_weight) of `x`, that /// is, the population count, or number of 1. /// /// This is a highly optimised version of the following naive version: /// /// ```rust /// fn naive(x: &[u8]) -> u64 { /// x.iter().fold(0, |a, b| a + b.count_ones() as u64) /// } /// ``` /// /// This uses Lauradoux Cédric's [tree-merging /// approach](http://web.archive.org/web/20120411185540/http://perso.citi.insa-lyon.fr/claurado/hamming.html) /// (as implemented by Kim Walisch in /// [primesieve](http://primesieve.org/)) and achieves on the order of /// 1-2 cycles per byte. /// /// # Performance Comparison /// /// | length | `naive` (ns) | `weight` (ns) | `naive`/`weight` | /// |--:|--:|--:|--:| /// | 1 | 5 | 16 | 0.31 | /// | 10 | 29 | 51 | 0.56 | /// | 100 | 284 | 392 | 0.72 | /// | 1,000 | 2,780 | 340 | 8.2 | /// | 10,000 | 27,700 | 2,300 | 12 | /// | 100,000 | 276,000 | 17,900 | 15 | /// | 1,000,000 | 2,770,000 | 172,000 | 16 | /// /// # Example /// /// ```rust /// assert_eq!(hamming::weight(&[1, 0xFF, 1, 0xFF]), 1 + 8 + 1 + 8); /// ``` pub fn weight(x: &[u8]) -> u64 { const M1: u64 = 0x5555555555555555; const M2: u64 = 0x3333333333333333; const M4: u64 = 0x0F0F0F0F0F0F0F0F; const M8: u64 = 0x00FF00FF00FF00FF; type T30 = [u64; 30]; let (head, thirty, tail) = unsafe { ::util::align_to::<_, T30>(x) }; let mut count = naive(head) + naive(tail); for array in thirty { let mut acc = 0; for j_ in 0..10 { let j = j_ * 3; let mut count1 = array[j]; let mut count2 = array[j + 1]; let mut half1 = array[j + 2]; let mut half2 = half1; half1 &= M1; half2 = (half2 >> 1) & M1; count1 -= (count1 >> 1) & M1; count2 -= (count2 >> 1) & M1; count1 += half1; count2 += half2; count1 = (count1 & M2) + ((count1 >> 2) & M2); count1 += (count2 & M2) + ((count2 >> 2) & M2); acc += (count1 & M4) + ((count1 >> 4) & M4); } acc = (acc & M8) + ((acc >> 8) & M8); acc = acc + (acc >> 16); acc = acc + (acc >> 32); count += acc & 0xFFFF; } count } #[cfg(test)] mod tests { use quickcheck as qc; use rand; #[test] fn naive_smoke() { let tests = [(&[0u8] as &[u8], 0), (&[1], 1), (&[0xFF], 8), (&[0xFF; 10], 8 * 10), (&[1; 1000], 1000)]; for &(v, expected) in &tests { assert_eq!(super::naive(v), expected); } } #[test] fn weight_qc() { fn prop(v: Vec<u8>, misalign: u8) -> qc::TestResult { let misalign = misalign as usize % 16; if misalign > v.len() { return qc::TestResult::discard(); } let data = &v[misalign..]; qc::TestResult::from_bool(super::weight(data) == super::naive(data)) } qc::QuickCheck::new() .gen(qc::StdGen::new(rand::thread_rng(), 10_000)) .quickcheck(prop as fn(Vec<u8>,u8) -> qc::TestResult) } #[test] fn weight_huge() { let v = vec![0b1001_1101; 10234567]; assert_eq!(super::weight(&v), v[0].count_ones() as u64 * v.len() as u64); } }
#[doc = "Register `OTG_HCINTMSK10` reader"] pub type R = crate::R<OTG_HCINTMSK10_SPEC>; #[doc = "Register `OTG_HCINTMSK10` writer"] pub type W = crate::W<OTG_HCINTMSK10_SPEC>; #[doc = "Field `XFRCM` reader - XFRCM"] pub type XFRCM_R = crate::BitReader; #[doc = "Field `XFRCM` writer - XFRCM"] pub type XFRCM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `CHHM` reader - CHHM"] pub type CHHM_R = crate::BitReader; #[doc = "Field `CHHM` writer - CHHM"] pub type CHHM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `AHBERRM` reader - AHBERRM"] pub type AHBERRM_R = crate::BitReader; #[doc = "Field `AHBERRM` writer - AHBERRM"] pub type AHBERRM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `STALLM` reader - STALLM"] pub type STALLM_R = crate::BitReader; #[doc = "Field `STALLM` writer - STALLM"] pub type STALLM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `NAKM` reader - NAKM"] pub type NAKM_R = crate::BitReader; #[doc = "Field `NAKM` writer - NAKM"] pub type NAKM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ACKM` reader - ACKM"] pub type ACKM_R = crate::BitReader; #[doc = "Field `ACKM` writer - ACKM"] pub type ACKM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `NYET` reader - NYET"] pub type NYET_R = crate::BitReader; #[doc = "Field `NYET` writer - NYET"] pub type NYET_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TXERRM` reader - TXERRM"] pub type TXERRM_R = crate::BitReader; #[doc = "Field `TXERRM` writer - TXERRM"] pub type TXERRM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BBERRM` reader - BBERRM"] pub type BBERRM_R = crate::BitReader; #[doc = "Field `BBERRM` writer - BBERRM"] pub type BBERRM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `FRMORM` reader - FRMORM"] pub type FRMORM_R = crate::BitReader; #[doc = "Field `FRMORM` writer - FRMORM"] pub type FRMORM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DTERRM` reader - DTERRM"] pub type DTERRM_R = crate::BitReader; #[doc = "Field `DTERRM` writer - DTERRM"] pub type DTERRM_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `BNAMSK` reader - BNAMSK"] pub type BNAMSK_R = crate::BitReader; #[doc = "Field `BNAMSK` writer - BNAMSK"] pub type BNAMSK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `DESCLSTROLLMSK` reader - DESCLSTROLLMSK"] pub type DESCLSTROLLMSK_R = crate::BitReader; #[doc = "Field `DESCLSTROLLMSK` writer - DESCLSTROLLMSK"] pub type DESCLSTROLLMSK_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - XFRCM"] #[inline(always)] pub fn xfrcm(&self) -> XFRCM_R { XFRCM_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - CHHM"] #[inline(always)] pub fn chhm(&self) -> CHHM_R { CHHM_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - AHBERRM"] #[inline(always)] pub fn ahberrm(&self) -> AHBERRM_R { AHBERRM_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - STALLM"] #[inline(always)] pub fn stallm(&self) -> STALLM_R { STALLM_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - NAKM"] #[inline(always)] pub fn nakm(&self) -> NAKM_R { NAKM_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - ACKM"] #[inline(always)] pub fn ackm(&self) -> ACKM_R { ACKM_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - NYET"] #[inline(always)] pub fn nyet(&self) -> NYET_R { NYET_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - TXERRM"] #[inline(always)] pub fn txerrm(&self) -> TXERRM_R { TXERRM_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - BBERRM"] #[inline(always)] pub fn bberrm(&self) -> BBERRM_R { BBERRM_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - FRMORM"] #[inline(always)] pub fn frmorm(&self) -> FRMORM_R { FRMORM_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - DTERRM"] #[inline(always)] pub fn dterrm(&self) -> DTERRM_R { DTERRM_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - BNAMSK"] #[inline(always)] pub fn bnamsk(&self) -> BNAMSK_R { BNAMSK_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 13 - DESCLSTROLLMSK"] #[inline(always)] pub fn desclstrollmsk(&self) -> DESCLSTROLLMSK_R { DESCLSTROLLMSK_R::new(((self.bits >> 13) & 1) != 0) } } impl W { #[doc = "Bit 0 - XFRCM"] #[inline(always)] #[must_use] pub fn xfrcm(&mut self) -> XFRCM_W<OTG_HCINTMSK10_SPEC, 0> { XFRCM_W::new(self) } #[doc = "Bit 1 - CHHM"] #[inline(always)] #[must_use] pub fn chhm(&mut self) -> CHHM_W<OTG_HCINTMSK10_SPEC, 1> { CHHM_W::new(self) } #[doc = "Bit 2 - AHBERRM"] #[inline(always)] #[must_use] pub fn ahberrm(&mut self) -> AHBERRM_W<OTG_HCINTMSK10_SPEC, 2> { AHBERRM_W::new(self) } #[doc = "Bit 3 - STALLM"] #[inline(always)] #[must_use] pub fn stallm(&mut self) -> STALLM_W<OTG_HCINTMSK10_SPEC, 3> { STALLM_W::new(self) } #[doc = "Bit 4 - NAKM"] #[inline(always)] #[must_use] pub fn nakm(&mut self) -> NAKM_W<OTG_HCINTMSK10_SPEC, 4> { NAKM_W::new(self) } #[doc = "Bit 5 - ACKM"] #[inline(always)] #[must_use] pub fn ackm(&mut self) -> ACKM_W<OTG_HCINTMSK10_SPEC, 5> { ACKM_W::new(self) } #[doc = "Bit 6 - NYET"] #[inline(always)] #[must_use] pub fn nyet(&mut self) -> NYET_W<OTG_HCINTMSK10_SPEC, 6> { NYET_W::new(self) } #[doc = "Bit 7 - TXERRM"] #[inline(always)] #[must_use] pub fn txerrm(&mut self) -> TXERRM_W<OTG_HCINTMSK10_SPEC, 7> { TXERRM_W::new(self) } #[doc = "Bit 8 - BBERRM"] #[inline(always)] #[must_use] pub fn bberrm(&mut self) -> BBERRM_W<OTG_HCINTMSK10_SPEC, 8> { BBERRM_W::new(self) } #[doc = "Bit 9 - FRMORM"] #[inline(always)] #[must_use] pub fn frmorm(&mut self) -> FRMORM_W<OTG_HCINTMSK10_SPEC, 9> { FRMORM_W::new(self) } #[doc = "Bit 10 - DTERRM"] #[inline(always)] #[must_use] pub fn dterrm(&mut self) -> DTERRM_W<OTG_HCINTMSK10_SPEC, 10> { DTERRM_W::new(self) } #[doc = "Bit 11 - BNAMSK"] #[inline(always)] #[must_use] pub fn bnamsk(&mut self) -> BNAMSK_W<OTG_HCINTMSK10_SPEC, 11> { BNAMSK_W::new(self) } #[doc = "Bit 13 - DESCLSTROLLMSK"] #[inline(always)] #[must_use] pub fn desclstrollmsk(&mut self) -> DESCLSTROLLMSK_W<OTG_HCINTMSK10_SPEC, 13> { DESCLSTROLLMSK_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "This register reflects the mask for each channel status described in the previous section.\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`otg_hcintmsk10::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`otg_hcintmsk10::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct OTG_HCINTMSK10_SPEC; impl crate::RegisterSpec for OTG_HCINTMSK10_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`otg_hcintmsk10::R`](R) reader structure"] impl crate::Readable for OTG_HCINTMSK10_SPEC {} #[doc = "`write(|w| ..)` method takes [`otg_hcintmsk10::W`](W) writer structure"] impl crate::Writable for OTG_HCINTMSK10_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets OTG_HCINTMSK10 to value 0"] impl crate::Resettable for OTG_HCINTMSK10_SPEC { const RESET_VALUE: Self::Ux = 0; }
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. //! A list of error types which are produced during an execution of the protocol use thiserror::Error; /// Represents an error in the manipulation of internal cryptographic data #[derive(Debug, Error)] pub enum InternalPakeError { #[error("Invalid length for {name}: expected {len}, but is actually {actual_len}.")] SizeError { name: &'static str, len: usize, actual_len: usize, }, #[error("Could not decompress point.")] PointError, #[error("Key belongs to a small subgroup!")] SubGroupError, #[error("hashing to a key failed")] HashingFailure, #[error("Computing HKDF failed while deriving subkeys")] HkdfError, #[error("Computing HMAC failed while supplying a secret key")] HmacError, } /// Represents an error in password checking #[derive(Debug, Error)] pub enum PakeError { /// This error results from an internal error during PRF construction /// #[error("Internal error during PRF verification: {0}")] CryptoError(InternalPakeError), /// This error occurs when the symmetric encryption fails #[error("Symmetric encryption failed.")] EncryptionError, /// This error occurs when the symmetric decryption fails #[error("Symmetric decryption failed.")] DecryptionError, /// This error occurs when the symmetric decryption's hmac check fails #[error("HMAC check in symmetric decryption failed.")] DecryptionHmacError, /// This error occurs when the server object that is being called finish() on is malformed #[error("Incomplete set of keys passed into finish() function")] IncompleteKeysError, #[error("The provided server public key doesn't match the encrypted one")] IncompatibleServerStaticPublicKeyError, #[error("Error in key exchange protocol when attempting to validate MACs")] KeyExchangeMacValidationError, #[error("Error in validating credentials")] InvalidLoginError, } // This is meant to express future(ly) non-trivial ways of converting the // internal error into a PakeError impl From<InternalPakeError> for PakeError { fn from(e: InternalPakeError) -> PakeError { PakeError::CryptoError(e) } } /// Represents an error in protocol handling #[derive(Debug, Error)] pub enum ProtocolError { /// This error results from an error during password verification /// #[error("Internal error during password verification: {0}")] VerificationError(PakeError), /// This error occurs when the server answer cannot be handled #[error("Server response cannot be handled.")] ServerError, /// This error occurs when the client request cannot be handled #[error("Client request cannot be handled.")] ClientError, } // This is meant to express future(ly) non-trivial ways of converting the // Pake error into a ProtocolError impl From<PakeError> for ProtocolError { fn from(e: PakeError) -> ProtocolError { ProtocolError::VerificationError(e) } } // This is meant to express future(ly) non-trivial ways of converting the // internal error into a ProtocolError impl From<InternalPakeError> for ProtocolError { fn from(e: InternalPakeError) -> ProtocolError { ProtocolError::VerificationError(e.into()) } } // See https://github.com/rust-lang/rust/issues/64715 and remove this when // merged, and https://github.com/dtolnay/thiserror/issues/62 for why this // comes up in our doc tests. impl From<::std::convert::Infallible> for ProtocolError { fn from(_: ::std::convert::Infallible) -> Self { unreachable!() } } pub(crate) mod utils { use super::*; pub fn check_slice_size<'a>( slice: &'a [u8], expected_len: usize, arg_name: &'static str, ) -> Result<&'a [u8], InternalPakeError> { if slice.len() != expected_len { return Err(InternalPakeError::SizeError { name: arg_name, len: expected_len, actual_len: slice.len(), }); } Ok(slice) } }
use crate::proto::kvraftpb::*; use futures::Future; use std::fmt; use std::sync::atomic::AtomicU64; use std::sync::atomic::AtomicUsize; use std::sync::atomic::Ordering; use std::time::Duration; const ERR_RETRY_DUR: Duration = Duration::from_millis(200); enum Op { Put(String, String), Append(String, String), } pub struct Clerk { pub name: String, pub servers: Vec<KvClient>, // You will have to modify this struct. leader_id: AtomicUsize, req_id: AtomicU64, } impl fmt::Debug for Clerk { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("Clerk").field("name", &self.name).finish() } } impl Clerk { pub fn new(name: String, servers: Vec<KvClient>) -> Clerk { Clerk { name, servers, leader_id: AtomicUsize::new(0), req_id: AtomicU64::new(0), } } /// Increase the request id, and return the new value fn incr_req_id(&self) -> u64 { let prev = self.req_id.fetch_add(1, Ordering::SeqCst); prev + 1 } /// fetch the current value for a key. /// returns "" if the key does not exist. /// keeps trying forever in the face of all other errors. pub fn get(&self, key: String) -> String { let req_id = self.incr_req_id(); let req = GetRequest { key, client: self.name.clone(), req_id, }; let server_cnt = self.servers.len(); loop { let leader = self.leader_id.load(Ordering::Acquire); let fut = self.servers[leader].get(&req); if let Ok(v) = fut.wait() { if !v.wrong_leader && v.err.is_empty() { return v.value; } } std::thread::sleep(ERR_RETRY_DUR); let leader = (leader + 1) % server_cnt; self.leader_id.store(leader, Ordering::Release); } } /// shared by Put and Append. fn put_append(&self, op: Op) { let n_servers = self.servers.len(); let req_id = self.incr_req_id(); let req = match op { Op::Put(k, v) => PutAppendRequest { key: k, value: v, op: 1, client: self.name.clone(), req_id, }, Op::Append(k, v) => PutAppendRequest { key: k, value: v, op: 2, client: self.name.clone(), req_id, }, }; loop { let leader = self.leader_id.load(Ordering::Acquire); let fut = self.servers[leader].put_append(&req); if let Ok(v) = fut.wait() { if !v.wrong_leader && v.err.is_empty() { return; } } std::thread::sleep(ERR_RETRY_DUR); let leader = (leader + 1) % n_servers; self.leader_id.store(leader, Ordering::Release); } } pub fn put(&self, key: String, value: String) { self.put_append(Op::Put(key, value)) } pub fn append(&self, key: String, value: String) { self.put_append(Op::Append(key, value)) } }
#[doc = "Register `ECR` reader"] pub type R = crate::R<ECR_SPEC>; #[doc = "Field `TEC` reader - TEC"] pub type TEC_R = crate::FieldReader; #[doc = "Field `REC` reader - TREC"] pub type REC_R = crate::FieldReader; #[doc = "Field `RP` reader - RP"] pub type RP_R = crate::BitReader; #[doc = "Field `CEL` reader - CEL"] pub type CEL_R = crate::FieldReader; impl R { #[doc = "Bits 0:7 - TEC"] #[inline(always)] pub fn tec(&self) -> TEC_R { TEC_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:14 - TREC"] #[inline(always)] pub fn rec(&self) -> REC_R { REC_R::new(((self.bits >> 8) & 0x7f) as u8) } #[doc = "Bit 15 - RP"] #[inline(always)] pub fn rp(&self) -> RP_R { RP_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bits 16:23 - CEL"] #[inline(always)] pub fn cel(&self) -> CEL_R { CEL_R::new(((self.bits >> 16) & 0xff) as u8) } } #[doc = "FDCAN Error Counter Register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ecr::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ECR_SPEC; impl crate::RegisterSpec for ECR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ecr::R`](R) reader structure"] impl crate::Readable for ECR_SPEC {} #[doc = "`reset()` method sets ECR to value 0"] impl crate::Resettable for ECR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use std::error::Error; use std::fmt; use std::fmt::{Display, Formatter}; pub type BoxResult<T> = Result<T, Box<dyn Error>>; #[derive(Debug, Clone)] pub struct NoneError; impl Display for NoneError { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "NoneError") } } impl Error for NoneError { fn source(&self) -> Option<&(dyn Error + 'static)> { None } }
#[doc = "Register `IER` reader"] pub type R = crate::R<IER_SPEC>; #[doc = "Register `IER` writer"] pub type W = crate::W<IER_SPEC>; #[doc = "Field `TAMP1IE` reader - Tamper 1 interrupt enable"] pub type TAMP1IE_R = crate::BitReader; #[doc = "Field `TAMP1IE` writer - Tamper 1 interrupt enable"] pub type TAMP1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP2IE` reader - Tamper 2 interrupt enable"] pub type TAMP2IE_R = crate::BitReader; #[doc = "Field `TAMP2IE` writer - Tamper 2 interrupt enable"] pub type TAMP2IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP3IE` reader - Tamper 3 interrupt enable"] pub type TAMP3IE_R = crate::BitReader; #[doc = "Field `TAMP3IE` writer - Tamper 3 interrupt enable"] pub type TAMP3IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP4IE` reader - Tamper 4 interrupt enable"] pub type TAMP4IE_R = crate::BitReader; #[doc = "Field `TAMP4IE` writer - Tamper 4 interrupt enable"] pub type TAMP4IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP5IE` reader - Tamper 5 interrupt enable"] pub type TAMP5IE_R = crate::BitReader; #[doc = "Field `TAMP5IE` writer - Tamper 5 interrupt enable"] pub type TAMP5IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP6IE` reader - Tamper 6 interrupt enable"] pub type TAMP6IE_R = crate::BitReader; #[doc = "Field `TAMP6IE` writer - Tamper 6 interrupt enable"] pub type TAMP6IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP7IE` reader - Tamper 7interrupt enable"] pub type TAMP7IE_R = crate::BitReader; #[doc = "Field `TAMP7IE` writer - Tamper 7interrupt enable"] pub type TAMP7IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP8IE` reader - Tamper 8 interrupt enable"] pub type TAMP8IE_R = crate::BitReader; #[doc = "Field `TAMP8IE` writer - Tamper 8 interrupt enable"] pub type TAMP8IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP1IE` reader - Internal tamper 1 interrupt enable"] pub type ITAMP1IE_R = crate::BitReader; #[doc = "Field `ITAMP1IE` writer - Internal tamper 1 interrupt enable"] pub type ITAMP1IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP2IE` reader - Internal tamper 2 interrupt enable"] pub type ITAMP2IE_R = crate::BitReader; #[doc = "Field `ITAMP2IE` writer - Internal tamper 2 interrupt enable"] pub type ITAMP2IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP3IE` reader - Internal tamper 3 interrupt enable"] pub type ITAMP3IE_R = crate::BitReader; #[doc = "Field `ITAMP3IE` writer - Internal tamper 3 interrupt enable"] pub type ITAMP3IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP4IE` reader - Internal tamper 4 interrupt enable"] pub type ITAMP4IE_R = crate::BitReader; #[doc = "Field `ITAMP4IE` writer - Internal tamper 4 interrupt enable"] pub type ITAMP4IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP5IE` reader - Internal tamper 5 interrupt enable"] pub type ITAMP5IE_R = crate::BitReader; #[doc = "Field `ITAMP5IE` writer - Internal tamper 5 interrupt enable"] pub type ITAMP5IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP6IE` reader - Internal tamper 6 interrupt enable"] pub type ITAMP6IE_R = crate::BitReader; #[doc = "Field `ITAMP6IE` writer - Internal tamper 6 interrupt enable"] pub type ITAMP6IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP7IE` reader - Internal tamper 7 interrupt enable"] pub type ITAMP7IE_R = crate::BitReader; #[doc = "Field `ITAMP7IE` writer - Internal tamper 7 interrupt enable"] pub type ITAMP7IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP8IE` reader - Internal tamper 8 interrupt enable"] pub type ITAMP8IE_R = crate::BitReader; #[doc = "Field `ITAMP8IE` writer - Internal tamper 8 interrupt enable"] pub type ITAMP8IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP9IE` reader - Internal tamper 9 interrupt enable"] pub type ITAMP9IE_R = crate::BitReader; #[doc = "Field `ITAMP9IE` writer - Internal tamper 9 interrupt enable"] pub type ITAMP9IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP11IE` reader - Internal tamper 11 interrupt enable"] pub type ITAMP11IE_R = crate::BitReader; #[doc = "Field `ITAMP11IE` writer - Internal tamper 11 interrupt enable"] pub type ITAMP11IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP12IE` reader - Internal tamper 12 interrupt enable"] pub type ITAMP12IE_R = crate::BitReader; #[doc = "Field `ITAMP12IE` writer - Internal tamper 12 interrupt enable"] pub type ITAMP12IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP13IE` reader - Internal tamper 13 interrupt enable"] pub type ITAMP13IE_R = crate::BitReader; #[doc = "Field `ITAMP13IE` writer - Internal tamper 13 interrupt enable"] pub type ITAMP13IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ITAMP15IE` reader - Internal tamper 15 interrupt enable"] pub type ITAMP15IE_R = crate::BitReader; #[doc = "Field `ITAMP15IE` writer - Internal tamper 15 interrupt enable"] pub type ITAMP15IE_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; impl R { #[doc = "Bit 0 - Tamper 1 interrupt enable"] #[inline(always)] pub fn tamp1ie(&self) -> TAMP1IE_R { TAMP1IE_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Tamper 2 interrupt enable"] #[inline(always)] pub fn tamp2ie(&self) -> TAMP2IE_R { TAMP2IE_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Tamper 3 interrupt enable"] #[inline(always)] pub fn tamp3ie(&self) -> TAMP3IE_R { TAMP3IE_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Tamper 4 interrupt enable"] #[inline(always)] pub fn tamp4ie(&self) -> TAMP4IE_R { TAMP4IE_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Tamper 5 interrupt enable"] #[inline(always)] pub fn tamp5ie(&self) -> TAMP5IE_R { TAMP5IE_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Tamper 6 interrupt enable"] #[inline(always)] pub fn tamp6ie(&self) -> TAMP6IE_R { TAMP6IE_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Tamper 7interrupt enable"] #[inline(always)] pub fn tamp7ie(&self) -> TAMP7IE_R { TAMP7IE_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Tamper 8 interrupt enable"] #[inline(always)] pub fn tamp8ie(&self) -> TAMP8IE_R { TAMP8IE_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 16 - Internal tamper 1 interrupt enable"] #[inline(always)] pub fn itamp1ie(&self) -> ITAMP1IE_R { ITAMP1IE_R::new(((self.bits >> 16) & 1) != 0) } #[doc = "Bit 17 - Internal tamper 2 interrupt enable"] #[inline(always)] pub fn itamp2ie(&self) -> ITAMP2IE_R { ITAMP2IE_R::new(((self.bits >> 17) & 1) != 0) } #[doc = "Bit 18 - Internal tamper 3 interrupt enable"] #[inline(always)] pub fn itamp3ie(&self) -> ITAMP3IE_R { ITAMP3IE_R::new(((self.bits >> 18) & 1) != 0) } #[doc = "Bit 19 - Internal tamper 4 interrupt enable"] #[inline(always)] pub fn itamp4ie(&self) -> ITAMP4IE_R { ITAMP4IE_R::new(((self.bits >> 19) & 1) != 0) } #[doc = "Bit 20 - Internal tamper 5 interrupt enable"] #[inline(always)] pub fn itamp5ie(&self) -> ITAMP5IE_R { ITAMP5IE_R::new(((self.bits >> 20) & 1) != 0) } #[doc = "Bit 21 - Internal tamper 6 interrupt enable"] #[inline(always)] pub fn itamp6ie(&self) -> ITAMP6IE_R { ITAMP6IE_R::new(((self.bits >> 21) & 1) != 0) } #[doc = "Bit 22 - Internal tamper 7 interrupt enable"] #[inline(always)] pub fn itamp7ie(&self) -> ITAMP7IE_R { ITAMP7IE_R::new(((self.bits >> 22) & 1) != 0) } #[doc = "Bit 23 - Internal tamper 8 interrupt enable"] #[inline(always)] pub fn itamp8ie(&self) -> ITAMP8IE_R { ITAMP8IE_R::new(((self.bits >> 23) & 1) != 0) } #[doc = "Bit 24 - Internal tamper 9 interrupt enable"] #[inline(always)] pub fn itamp9ie(&self) -> ITAMP9IE_R { ITAMP9IE_R::new(((self.bits >> 24) & 1) != 0) } #[doc = "Bit 26 - Internal tamper 11 interrupt enable"] #[inline(always)] pub fn itamp11ie(&self) -> ITAMP11IE_R { ITAMP11IE_R::new(((self.bits >> 26) & 1) != 0) } #[doc = "Bit 27 - Internal tamper 12 interrupt enable"] #[inline(always)] pub fn itamp12ie(&self) -> ITAMP12IE_R { ITAMP12IE_R::new(((self.bits >> 27) & 1) != 0) } #[doc = "Bit 28 - Internal tamper 13 interrupt enable"] #[inline(always)] pub fn itamp13ie(&self) -> ITAMP13IE_R { ITAMP13IE_R::new(((self.bits >> 28) & 1) != 0) } #[doc = "Bit 30 - Internal tamper 15 interrupt enable"] #[inline(always)] pub fn itamp15ie(&self) -> ITAMP15IE_R { ITAMP15IE_R::new(((self.bits >> 30) & 1) != 0) } } impl W { #[doc = "Bit 0 - Tamper 1 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp1ie(&mut self) -> TAMP1IE_W<IER_SPEC, 0> { TAMP1IE_W::new(self) } #[doc = "Bit 1 - Tamper 2 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp2ie(&mut self) -> TAMP2IE_W<IER_SPEC, 1> { TAMP2IE_W::new(self) } #[doc = "Bit 2 - Tamper 3 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp3ie(&mut self) -> TAMP3IE_W<IER_SPEC, 2> { TAMP3IE_W::new(self) } #[doc = "Bit 3 - Tamper 4 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp4ie(&mut self) -> TAMP4IE_W<IER_SPEC, 3> { TAMP4IE_W::new(self) } #[doc = "Bit 4 - Tamper 5 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp5ie(&mut self) -> TAMP5IE_W<IER_SPEC, 4> { TAMP5IE_W::new(self) } #[doc = "Bit 5 - Tamper 6 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp6ie(&mut self) -> TAMP6IE_W<IER_SPEC, 5> { TAMP6IE_W::new(self) } #[doc = "Bit 6 - Tamper 7interrupt enable"] #[inline(always)] #[must_use] pub fn tamp7ie(&mut self) -> TAMP7IE_W<IER_SPEC, 6> { TAMP7IE_W::new(self) } #[doc = "Bit 7 - Tamper 8 interrupt enable"] #[inline(always)] #[must_use] pub fn tamp8ie(&mut self) -> TAMP8IE_W<IER_SPEC, 7> { TAMP8IE_W::new(self) } #[doc = "Bit 16 - Internal tamper 1 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp1ie(&mut self) -> ITAMP1IE_W<IER_SPEC, 16> { ITAMP1IE_W::new(self) } #[doc = "Bit 17 - Internal tamper 2 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp2ie(&mut self) -> ITAMP2IE_W<IER_SPEC, 17> { ITAMP2IE_W::new(self) } #[doc = "Bit 18 - Internal tamper 3 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp3ie(&mut self) -> ITAMP3IE_W<IER_SPEC, 18> { ITAMP3IE_W::new(self) } #[doc = "Bit 19 - Internal tamper 4 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp4ie(&mut self) -> ITAMP4IE_W<IER_SPEC, 19> { ITAMP4IE_W::new(self) } #[doc = "Bit 20 - Internal tamper 5 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp5ie(&mut self) -> ITAMP5IE_W<IER_SPEC, 20> { ITAMP5IE_W::new(self) } #[doc = "Bit 21 - Internal tamper 6 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp6ie(&mut self) -> ITAMP6IE_W<IER_SPEC, 21> { ITAMP6IE_W::new(self) } #[doc = "Bit 22 - Internal tamper 7 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp7ie(&mut self) -> ITAMP7IE_W<IER_SPEC, 22> { ITAMP7IE_W::new(self) } #[doc = "Bit 23 - Internal tamper 8 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp8ie(&mut self) -> ITAMP8IE_W<IER_SPEC, 23> { ITAMP8IE_W::new(self) } #[doc = "Bit 24 - Internal tamper 9 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp9ie(&mut self) -> ITAMP9IE_W<IER_SPEC, 24> { ITAMP9IE_W::new(self) } #[doc = "Bit 26 - Internal tamper 11 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp11ie(&mut self) -> ITAMP11IE_W<IER_SPEC, 26> { ITAMP11IE_W::new(self) } #[doc = "Bit 27 - Internal tamper 12 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp12ie(&mut self) -> ITAMP12IE_W<IER_SPEC, 27> { ITAMP12IE_W::new(self) } #[doc = "Bit 28 - Internal tamper 13 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp13ie(&mut self) -> ITAMP13IE_W<IER_SPEC, 28> { ITAMP13IE_W::new(self) } #[doc = "Bit 30 - Internal tamper 15 interrupt enable"] #[inline(always)] #[must_use] pub fn itamp15ie(&mut self) -> ITAMP15IE_W<IER_SPEC, 30> { ITAMP15IE_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "TAMP interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ier::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ier::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct IER_SPEC; impl crate::RegisterSpec for IER_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`ier::R`](R) reader structure"] impl crate::Readable for IER_SPEC {} #[doc = "`write(|w| ..)` method takes [`ier::W`](W) writer structure"] impl crate::Writable for IER_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets IER to value 0"] impl crate::Resettable for IER_SPEC { const RESET_VALUE: Self::Ux = 0; }
/** * トレイト境界 * 「あるトレイトを実装する型」をジェネリクスで受け取ることもできる。これをトレイト境界という。 * 型の集合を定義するもの * 関数をまとめた関数みたいなもの **/ trait DuckLike { // トレイトを実装する型が実装するべきメソッドを定義 fn quack(&self); // デフォルトメソッドを定義することもできる fn walk(&self) { println!("walking"); } } // トレイトを実装するためだけのデータ型なら、Unit構造体が便利 struct Duck; // `impl トレイト名 for 型名 {..}`で定義可能 impl DuckLike for Duck { // トレイトで実装されていないメソッドを実装側で定義する fn quack(&self) { println!("quick"); } } // struct Tsuchinoko; // // 別の型にも実装できます。 // impl DuckLike for Tsuchinoko { // fn quack(&self) { // // どうやらこのツチノコの正体はネコだったようです // println!("mew"); // } // // デフォルトメソッドで上書きすることもできる // fn walk(&self) { // println!("wringgling"); // } // } // 既存の型にトレイトを実装することもできる // モンキーパッチをしているような気分 <=? impl DuckLike for i64 { fn quack(&self) { for _ in 0..*self { println!("quack"); } } } /** * ここまでtrait.rsと一緒 */ // ジェネリクスの型パラメータに`型パラメータ名: トレイト名`で境界をつけることができる fn duck_go<D: DuckLike>(duck: D) { // 境界をつけることで関数本体でトレイトのメソッドが使える duck.quack(); duck.walk(); } fn main() { let duck = Duck; duck_go(duck); // let f = 0.0; // duck_go(f); // Ducklikeとれいとはfloatを実装していないため、コンパイルエラー }
#![feature(test)] extern crate test; use decimal::d128; use roc_dec::RocDec; use std::convert::TryInto; use test::{black_box, Bencher}; #[bench] fn dec_mul1(bench: &mut Bencher) { let dec1: RocDec = "1.2".try_into().unwrap(); let dec2: RocDec = "3.4".try_into().unwrap(); bench.iter(|| { black_box(dec1 * dec2); }); } #[bench] fn dec_mul7(bench: &mut Bencher) { let dec1: RocDec = "1.2".try_into().unwrap(); let dec2: RocDec = "3.4".try_into().unwrap(); bench.iter(|| { black_box({ let a = black_box(dec1 * dec2); let a = black_box(a * dec1); let a = black_box(a * dec2); let a = black_box(a * dec1); let a = black_box(a * dec2); let a = black_box(a * dec1); let a = black_box(a * dec2); let a = black_box(a * dec1); let a = black_box(a * dec2); let a = black_box(a * dec1); let a = black_box(a * dec2); let a = black_box(a * dec1); let a = black_box(a * dec2); let a = black_box(a * dec1); let a = black_box(a * dec2); let a = black_box(a * dec1); let a = black_box(a * dec2); black_box(a) }) }); } #[bench] fn d128_mul1(bench: &mut Bencher) { let d1: d128 = d128!(1.2); let d2: d128 = d128!(3.4); bench.iter(|| { black_box(mul_d128_or_panic(d1, d2)); }); } #[bench] fn i128_mul1(bench: &mut Bencher) { let i1: i128 = 12; let i2: i128 = 34; bench.iter(|| { black_box(mul_i128_or_panic(i1, i2)); }); } #[bench] fn f64_mul1(bench: &mut Bencher) { let f1: f64 = 1.2; let f2: f64 = 3.4; bench.iter(|| { black_box(mul_or_panic(f1, f2)); }); } #[bench] fn f64_mul7(bench: &mut Bencher) { let f1: f64 = 1.2; let f2: f64 = 3.4; bench.iter(|| { black_box({ let a = black_box(mul_or_panic(f1, f2)); let a = black_box(mul_or_panic(a, f1)); let a = black_box(mul_or_panic(a, f2)); let a = black_box(mul_or_panic(a, f1)); let a = black_box(mul_or_panic(a, f2)); let a = black_box(mul_or_panic(a, f1)); let a = black_box(mul_or_panic(a, f2)); let a = black_box(mul_or_panic(a, f1)); let a = black_box(mul_or_panic(a, f2)); let a = black_box(mul_or_panic(a, f1)); let a = black_box(mul_or_panic(a, f2)); let a = black_box(mul_or_panic(a, f1)); let a = black_box(mul_or_panic(a, f2)); let a = black_box(mul_or_panic(a, f1)); let a = black_box(mul_or_panic(a, f2)); let a = black_box(mul_or_panic(a, f1)); let a = black_box(mul_or_panic(a, f2)); black_box(a) }) }); } #[bench] fn i128_mul7(bench: &mut Bencher) { let i1: i128 = 12; let i2: i128 = 34; bench.iter(|| { black_box({ let a = black_box(mul_i128_or_panic(i1, i2)); let a = black_box(mul_i128_or_panic(a, i1)); let a = black_box(mul_i128_or_panic(a, i2)); let a = black_box(mul_i128_or_panic(a, i1)); let a = black_box(mul_i128_or_panic(a, i2)); let a = black_box(mul_i128_or_panic(a, i1)); let a = black_box(mul_i128_or_panic(a, i2)); let a = black_box(mul_i128_or_panic(a, i1)); let a = black_box(mul_i128_or_panic(a, i2)); let a = black_box(mul_i128_or_panic(a, i1)); let a = black_box(mul_i128_or_panic(a, i2)); let a = black_box(mul_i128_or_panic(a, i1)); let a = black_box(mul_i128_or_panic(a, i2)); let a = black_box(mul_i128_or_panic(a, i1)); let a = black_box(mul_i128_or_panic(a, i2)); let a = black_box(mul_i128_or_panic(a, i1)); let a = black_box(mul_i128_or_panic(a, i2)); black_box(a) }) }); } #[bench] fn d128_mul7(bench: &mut Bencher) { let d1: d128 = d128!(1.2); let d2: d128 = d128!(3.4); bench.iter(|| { black_box({ let a = black_box(mul_d128_or_panic(d1, d2)); let a = black_box(mul_d128_or_panic(a, d1)); let a = black_box(mul_d128_or_panic(a, d2)); let a = black_box(mul_d128_or_panic(a, d1)); let a = black_box(mul_d128_or_panic(a, d2)); let a = black_box(mul_d128_or_panic(a, d1)); let a = black_box(mul_d128_or_panic(a, d2)); let a = black_box(mul_d128_or_panic(a, d1)); let a = black_box(mul_d128_or_panic(a, d2)); let a = black_box(mul_d128_or_panic(a, d1)); let a = black_box(mul_d128_or_panic(a, d2)); let a = black_box(mul_d128_or_panic(a, d1)); let a = black_box(mul_d128_or_panic(a, d2)); let a = black_box(mul_d128_or_panic(a, d1)); let a = black_box(mul_d128_or_panic(a, d2)); let a = black_box(mul_d128_or_panic(a, d1)); let a = black_box(mul_d128_or_panic(a, d2)); black_box(a) }) }); } fn mul_i128_or_panic(a: i128, b: i128) -> i128 { let (answer, overflowed) = a.overflowing_mul(b); if !overflowed { answer } else { todo!("throw an exception"); } } fn mul_d128_or_panic(a: d128, b: d128) -> d128 { let answer = a * b; if answer.is_finite() { answer } else { todo!("throw an exception"); } } fn mul_or_panic(a: f64, b: f64) -> f64 { let answer = a * b; if answer.is_finite() { answer } else { todo!("throw an exception"); } }
use chore::*; #[test] fn general() -> Result<()> { for (args, expect_stdout, expect_confirm, expect_tasks) in &[ ( vec!["modify", "+done"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD x (M) 2001-02-03 @home +chore add tests\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD x add task due:2002-03-04T05:06:07\n", ), true, concat!( "x (M) 2001-02-03 @home +chore add tests\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x add task due:2002-03-04T05:06:07\n" ), ), ( vec!["modify", "-+done"], concat!( "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD (H) 2001-01-02 @work issue:123\n", ), false, concat!( "(H) 2001-01-02 @work issue:123\n", "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", ), ), ( vec!["modify", "+chore"], concat!( "DEL add task due:2002-03-04T05:06:07\n", "ADD add task due:2002-03-04T05:06:07 +chore\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) 2001-01-02 @work issue:123 +chore\n", ), true, concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07 +chore\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123 +chore\n", ), ), ( vec!["modify", "-+chore"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) 2001-02-03 @home add tests\n", ), false, concat!( "(M) 2001-02-03 @home add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), ), ( vec!["modify", "@work"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) 2001-02-03 @home +chore add tests @work\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD add task due:2002-03-04T05:06:07 @work\n", ), true, concat!( "(M) 2001-02-03 @home +chore add tests @work\n", "add task due:2002-03-04T05:06:07 @work\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), ), ( vec!["modify", "-@work"], concat!( "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) 2001-01-02 issue:123\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 issue:123\n", ), ), ( vec!["modify", "issue:999"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) 2001-02-03 @home +chore add tests issue:999\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD add task due:2002-03-04T05:06:07 issue:999\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) 2001-01-02 @work issue:999\n", ), true, concat!( "(M) 2001-02-03 @home +chore add tests issue:999\n", "add task due:2002-03-04T05:06:07 issue:999\n", "x 2001-02-03 (H) 2001-01-02 @work issue:999\n", ), ), ( vec!["modify", "end:2009-09-09"], concat!( "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2009-09-09 (H) 2001-01-02 @work issue:123\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2009-09-09 (H) 2001-01-02 @work issue:123\n", ), ), ( vec!["modify", "pri:Z"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (Z) 2001-02-03 @home +chore add tests\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD (Z) add task due:2002-03-04T05:06:07\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (Z) 2001-01-02 @work issue:123\n", ), true, concat!( "(Z) 2001-02-03 @home +chore add tests\n", "(Z) add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (Z) 2001-01-02 @work issue:123\n", ), ), ( vec!["modify", "entry:2009-09-09"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) 2009-09-09 @home +chore add tests\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD 2009-09-09 add task due:2002-03-04T05:06:07\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) 2009-09-09 @work issue:123\n", ), true, concat!( "(M) 2009-09-09 @home +chore add tests\n", "2009-09-09 add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2009-09-09 @work issue:123\n", ), ), ( vec!["modify", "due:2009-09-09"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) 2001-02-03 @home +chore add tests due:2009-09-09\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD add task due:2009-09-09\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) 2001-01-02 @work issue:123 due:2009-09-09\n", ), true, concat!( "(M) 2001-02-03 @home +chore add tests due:2009-09-09\n", "add task due:2009-09-09\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123 due:2009-09-09\n", ), ), ( vec!["modify", "end:"], concat!( "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x (H) 2001-01-02 @work issue:123\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x (H) 2001-01-02 @work issue:123\n", ), ), ( vec!["modify", "pri:"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD 2001-02-03 @home +chore add tests\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 2001-01-02 @work issue:123\n", ), true, concat!( "2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 2001-01-02 @work issue:123\n", ), ), ( vec!["modify", "entry:"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) @home +chore add tests\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) @work issue:123\n", ), true, concat!( "(M) @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) @work issue:123\n", ), ), ( vec!["modify", "due:"], concat!("DEL add task due:2002-03-04T05:06:07\n", "ADD add task\n",), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), ), ( vec!["modify", "issue:"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) 2001-02-03 @home +chore add tests issue:\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD add task due:2002-03-04T05:06:07 issue:\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) 2001-01-02 @work issue:\n", ), true, concat!( "(M) 2001-02-03 @home +chore add tests issue:\n", "add task due:2002-03-04T05:06:07 issue:\n", "x 2001-02-03 (H) 2001-01-02 @work issue:\n", ), ), ( vec!["modify", "-end:"], concat!( "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x (H) 2001-01-02 @work issue:123\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x (H) 2001-01-02 @work issue:123\n", ), ), ( vec!["modify", "-pri:"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD 2001-02-03 @home +chore add tests\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 2001-01-02 @work issue:123\n", ), true, concat!( "2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 2001-01-02 @work issue:123\n", ), ), ( vec!["modify", "-entry:"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) @home +chore add tests\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) @work issue:123\n", ), true, concat!( "(M) @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) @work issue:123\n", ), ), ( vec!["modify", "-issue:"], concat!( "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) 2001-01-02 @work\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work\n", ), ), ( vec!["modify", ">>Z"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) 2001-02-03 @home +chore add tests Z\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD add task due:2002-03-04T05:06:07 Z\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) 2001-01-02 @work issue:123 Z\n", ), true, concat!( "(M) 2001-02-03 @home +chore add tests Z\n", "add task due:2002-03-04T05:06:07 Z\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123 Z\n", ), ), ( vec!["modify", ">>A", "B", "C", "pri:Z"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (Z) 2001-02-03 @home +chore add tests A B C\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD (Z) add task due:2002-03-04T05:06:07 A B C\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (Z) 2001-01-02 @work issue:123 A B C\n", ), true, concat!( "(Z) 2001-02-03 @home +chore add tests A B C\n", "(Z) add task due:2002-03-04T05:06:07 A B C\n", "x 2001-02-03 (Z) 2001-01-02 @work issue:123 A B C\n", ), ), ( vec!["modify", "Z"], concat!( "DEL (M) 2001-02-03 @home +chore add tests\n", "ADD (M) 2001-02-03 Z\n", "DEL add task due:2002-03-04T05:06:07\n", "ADD Z\n", "DEL x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "ADD x 2001-02-03 (H) 2001-01-02 Z\n", ), true, concat!( "(M) 2001-02-03 Z\n", "Z\n", "x 2001-02-03 (H) 2001-01-02 Z\n", ), ), ( vec!["add", "pri:Z", "@home", "entry:2009-09-09", "+chore", "example"], concat!( "ADD (Z) 2009-09-09 @home +chore example\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "(Z) 2009-09-09 @home +chore example\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), ), ] { let config = Config { now: chrono::NaiveDate::from_ymd(2001, 2, 3).and_hms(4, 5, 6), args: args.iter().map(|s| s.to_string()).collect(), tasks: Some( concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ) .to_owned(), ), date_keys: Some("due:\nscheduled:\nwait:\nuntil:\n".to_owned()), ..Default::default() }; let mut expect_undo = String::from("---\n"); expect_undo.push_str(expect_stdout); match chore::run(config)? { Output::WriteFiles { stdout, confirm, tasks, undo, } => { assert_eq!(&stdout, expect_stdout); assert_eq!(&confirm, expect_confirm); assert_eq!(&tasks, expect_tasks); assert_eq!(undo, expect_undo); } _ => panic!("expected WriteFiles"), } } Ok(()) } #[test] fn special_tags() -> Result<()> { for (tasks, args, expect_stdout, expect_confirm, expect_tasks) in &[ // recur: ( concat!( "(M) 2001-02-03 @home +chore recur:1w add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), vec!["recur.any:", "modify", "+done", "end:today"], concat!( "DEL (M) 2001-02-03 @home +chore recur:1w add tests\n", "ADD (M) 2001-02-10 @home +chore recur:1w add tests\n", "ADD x 2001-02-03 (M) 2001-02-03 @home +chore recur:1w add tests\n", ), false, concat!( "(M) 2001-02-10 @home +chore recur:1w add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x 2001-02-03 (M) 2001-02-03 @home +chore recur:1w add tests\n", ), ), ( concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07 recur:1w\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), vec!["recur.any:", "modify", "+done", "end:today"], concat!( "DEL add task due:2002-03-04T05:06:07 recur:1w\n", "ADD add task due:2002-03-11T05:06:07 recur:1w\n", "ADD x 2001-02-03 add task due:2002-03-04T05:06:07 recur:1w\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-11T05:06:07 recur:1w\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x 2001-02-03 add task due:2002-03-04T05:06:07 recur:1w\n", ), ), // +update ( concat!( "(M) 2001-02-03 @home +chore add tests +update\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), vec!["+update", "modify", "+done", "end:today"], concat!( "DEL (M) 2001-02-03 @home +chore add tests +update\n", "ADD x 2001-02-03 (M) 2001-02-03 @home +chore add tests +update\n", ), false, concat!( "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x 2001-02-03 (M) 2001-02-03 @home +chore add tests +update\n", ), ), ( concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07 +update\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), vec!["+update", "modify", "+done", "end:today"], concat!( "DEL add task due:2002-03-04T05:06:07 +update\n", "ADD x 2001-02-03 add task due:2002-03-04T05:06:07 +update\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x 2001-02-03 add task due:2002-03-04T05:06:07 +update\n", ), ), ( concat!( "(M) 2001-02-03 @home +chore add tests +update\n", "add task due:2002-03-04T05:06:07\n", "x 2001-01-01 (M) 2001-01-01 @home +chore add tests +update\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), vec!["-+done", "+update", "modify", "+done", "end:today"], concat!( "DEL (M) 2001-02-03 @home +chore add tests +update\n", "DEL x 2001-01-01 (M) 2001-01-01 @home +chore add tests +update\n", "ADD x 2001-02-03 (M) 2001-02-03 @home +chore add tests +update\n", ), false, concat!( "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x 2001-02-03 (M) 2001-02-03 @home +chore add tests +update\n", ), ), ( concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07 +update\n", "x 2001-01-01 add task due:2002-03-04T05:06:07 +update\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), vec!["-+done", "+update", "modify", "+done", "end:today"], concat!( "DEL add task due:2002-03-04T05:06:07 +update\n", "DEL x 2001-01-01 add task due:2002-03-04T05:06:07 +update\n", "ADD x 2001-02-03 add task due:2002-03-04T05:06:07 +update\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x 2001-02-03 add task due:2002-03-04T05:06:07 +update\n", ), ), ( concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07 +update\n", "x 2001-01-01 add task due:2003 +update\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), vec!["-+done", "+update", "modify", "+done", "end:today"], concat!( "DEL add task due:2002-03-04T05:06:07 +update\n", "DEL x 2001-01-01 add task due:2003 +update\n", "ADD x 2001-02-03 add task due:2002-03-04T05:06:07 +update\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x 2001-02-03 add task due:2002-03-04T05:06:07 +update\n", ), ), ( concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-01-01 (H) 2001-01-02 @work issue:123 +update\n", ), vec!["+update", "modify", "+done", "end:today"], concat!( "DEL x 2001-01-01 (H) 2001-01-02 @work issue:123 +update\n", "ADD x 2001-02-03 (H) 2001-01-02 @work issue:123 +update\n", ), false, concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123 +update\n", ), ), // recur: and +update ( concat!( "(M) 2001-02-03 @home +chore recur:1w +update add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), vec!["recur.any:", "modify", "+done", "end:today"], concat!( "DEL (M) 2001-02-03 @home +chore recur:1w +update add tests\n", "ADD (M) 2001-02-10 @home +chore recur:1w +update add tests\n", "ADD x 2001-02-03 (M) 2001-02-03 @home +chore recur:1w +update add tests\n", ), false, concat!( "(M) 2001-02-10 @home +chore recur:1w +update add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x 2001-02-03 (M) 2001-02-03 @home +chore recur:1w +update add tests\n", ), ), ( concat!( "(M) 2001-02-03 @home +chore recur:1w +update add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-01-01 (M) 2001-02-01 @home +chore recur:1w +update add tests\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ), vec!["-+done", "recur.any:", "modify", "+done", "end:today"], concat!( "DEL (M) 2001-02-03 @home +chore recur:1w +update add tests\n", "ADD (M) 2001-02-10 @home +chore recur:1w +update add tests\n", "DEL x 2001-01-01 (M) 2001-02-01 @home +chore recur:1w +update add tests\n", "ADD x 2001-02-03 (M) 2001-02-03 @home +chore recur:1w +update add tests\n", ), false, concat!( "(M) 2001-02-10 @home +chore recur:1w +update add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", "x 2001-02-03 (M) 2001-02-03 @home +chore recur:1w +update add tests\n", ), ), ] { let config = Config { now: chrono::NaiveDate::from_ymd(2001, 2, 3).and_hms(4, 5, 6), args: args.iter().map(|s| s.to_string()).collect(), tasks: Some(tasks.to_string()), date_keys: Some("due:\nscheduled:\nwait:\nuntil:\n".to_owned()), ..Default::default() }; let mut expect_undo = String::from("---\n"); expect_undo.push_str(expect_stdout); match chore::run(config)? { Output::WriteFiles { stdout, confirm, tasks, undo, } => { assert_eq!(&stdout, expect_stdout); assert_eq!(&confirm, expect_confirm); assert_eq!(&tasks, expect_tasks); assert_eq!(undo, expect_undo); } _ => panic!("expected WriteFiles"), } } Ok(()) } #[test] fn invalid() -> Result<()> { for (args, expect) in &[ ( vec!["modify", "end:2001-02-03T04:05:06"], InvalidEnd("end:2001-02-03T04:05:06".to_owned()), ), ( vec!["modify", "end:x"], KeyExpectsDateValue("end:x".to_owned()), ), (vec!["modify", "pri:x"], InvalidPriority("pri:x".to_owned())), ( vec!["modify", "entry:2001-02-03T04:05:06"], InvalidEntry("entry:2001-02-03T04:05:06".to_owned()), ), ( vec!["modify", "entry:x"], KeyExpectsDateValue("entry:x".to_owned()), ), ( vec!["modify", "due:x"], KeyExpectsDateValue("due:x".to_owned()), ), ] { let config = Config { now: chrono::NaiveDate::from_ymd(2001, 2, 3).and_hms(4, 5, 6), args: args.iter().map(|s| s.to_string()).collect(), tasks: Some( concat!( "(M) 2001-02-03 @home +chore add tests\n", "add task due:2002-03-04T05:06:07\n", "x 2001-02-03 (H) 2001-01-02 @work issue:123\n", ) .to_owned(), ), date_keys: Some("due:\nscheduled:\nwait:\nuntil:\n".to_owned()), ..Default::default() }; let actual = match chore::run(config) { Ok(_) => panic!("expected error"), Err(e) => e, }; assert_eq!(format!("{:?}", actual), format!("{:?}", expect)); } Ok(()) }
use escargot::CargoBuild; use std::io::{Read, Result, Write}; use std::net::{Shutdown, TcpStream}; use std::process::{Child, Stdio}; pub struct ServerWrapper { stream: TcpStream, child: Child, } impl ServerWrapper { fn setup_server() -> Result<Child> { CargoBuild::new() .bin("server") .current_release() .current_target() .manifest_path("../src/server/Cargo.toml") .run() .unwrap() .command() // .stderr(Stdio::null()) // .stdout(Stdio::null()) .spawn() } fn try_connect() -> Result<TcpStream> { let bind_addr = "127.0.0.1:3333".to_string(); let stream = TcpStream::connect(bind_addr)?; stream.set_nodelay(true).unwrap(); Ok(stream) } pub fn new() -> std::result::Result<ServerWrapper, String> { // Configure log environment let child = ServerWrapper::setup_server().unwrap(); std::thread::sleep(std::time::Duration::from_millis(100)); match ServerWrapper::try_connect() { Ok(stream) => Ok(ServerWrapper { stream, child }), _ => Err("Failed to connect to server".to_owned()), } } pub fn close_client(&mut self) { println!("Sending close..."); self.run_command_without_out("\\close"); println!("Done..."); self.stream .shutdown(Shutdown::Both) .expect("Shutdown occurred unsuccessfully"); std::thread::sleep(std::time::Duration::from_millis(100)); println!("About to kill client/server"); self.child.kill().unwrap(); } pub fn cleanup(&mut self) -> &mut Self { self.run_command("\\d") } pub fn run_command_without_out(&mut self, command: &str) { // Send command self.stream .write_all(format!("{}\n", command).as_bytes()) .expect("Failed to write"); } pub fn run_command_with_out(&mut self, command: &str) -> String { // Send command self.stream .write_all(format!("{}\n", command).as_bytes()) .expect("Failed to write"); // Read server response let mut data = [0 as u8; 256]; while match self.stream.read(&mut data) { Ok(_size) => { //TODO: Remove echo and change to from_utf8 // let s = String::from_utf8_lossy(&data); //TODO this is dirty. Should likely be response type sent to client. // //quit command received from server // if s.starts_with("\\") { // if s.starts_with("\\quit") { // info!("Received Quit Command"); // cont = false; // } else { // info!("command received {}", s); // panic!("No action specified for command {}", s); // } // } // info!("{}", s); false } Err(_) => false, } {} String::from_utf8(data.to_vec()).unwrap() // FIXME: this is a better way of reading the answer // println!("Command sent, waiting for response..."); // let mut out = [0 as u8; 256]; // self.stream.read_exact(&mut out).unwrap(); // println!("response received!"); // String::from_utf8(out.to_vec()).unwrap() } pub fn run_command(&mut self, command: &str) -> &mut Self { self.run_command_with_out(command); self } }
use crate::i2c::{Error, Instance, SclPin, SdaPin}; use crate::time::Hertz; use core::marker::PhantomData; use embassy::util::Unborrow; use embassy_extras::unborrow; use embedded_hal::blocking::i2c::Read; use embedded_hal::blocking::i2c::Write; use embedded_hal::blocking::i2c::WriteRead; use crate::pac::i2c; use crate::pac::gpio::vals::{Afr, Moder, Ot}; use crate::pac::gpio::Gpio; pub struct I2c<'d, T: Instance> { phantom: PhantomData<&'d mut T>, } impl<'d, T: Instance> I2c<'d, T> { pub fn new<F>( pclk: Hertz, _peri: impl Unborrow<Target = T> + 'd, scl: impl Unborrow<Target = impl SclPin<T>>, sda: impl Unborrow<Target = impl SdaPin<T>>, freq: F, ) -> Self where F: Into<Hertz>, { unborrow!(scl, sda); unsafe { Self::configure_pin(scl.block(), scl.pin() as _, scl.af_num()); Self::configure_pin(sda.block(), sda.pin() as _, sda.af_num()); } unsafe { T::regs().cr1().modify(|reg| { reg.set_pe(false); //reg.set_anfoff(false); }); } let timings = Timings::new(pclk, freq.into()); unsafe { T::regs().cr2().modify(|reg| { reg.set_freq(timings.freq); }); T::regs().ccr().modify(|reg| { reg.set_f_s(timings.mode.f_s()); reg.set_duty(timings.duty.duty()); reg.set_ccr(timings.ccr); }); T::regs().trise().modify(|reg| { reg.set_trise(timings.trise); }); } unsafe { T::regs().cr1().modify(|reg| { reg.set_pe(true); }); } Self { phantom: PhantomData, } } unsafe fn configure_pin(block: Gpio, pin: usize, af_num: u8) { let (afr, n_af) = if pin < 8 { (0, pin) } else { (1, pin - 8) }; block.moder().modify(|w| w.set_moder(pin, Moder::ALTERNATE)); block.afr(afr).modify(|w| w.set_afr(n_af, Afr(af_num))); block.otyper().modify(|w| w.set_ot(pin, Ot::OPENDRAIN)); } unsafe fn check_and_clear_error_flags(&self) -> Result<i2c::regs::Sr1, Error> { // Note that flags should only be cleared once they have been registered. If flags are // cleared otherwise, there may be an inherent race condition and flags may be missed. let sr1 = T::regs().sr1().read(); if sr1.timeout() { T::regs().sr1().modify(|reg| reg.set_timeout(false)); return Err(Error::Timeout); } if sr1.pecerr() { T::regs().sr1().modify(|reg| reg.set_pecerr(false)); return Err(Error::Crc); } if sr1.ovr() { T::regs().sr1().modify(|reg| reg.set_ovr(false)); return Err(Error::Overrun); } if sr1.af() { T::regs().sr1().modify(|reg| reg.set_af(false)); return Err(Error::Nack); } if sr1.arlo() { T::regs().sr1().modify(|reg| reg.set_arlo(false)); return Err(Error::Arbitration); } // The errata indicates that BERR may be incorrectly detected. It recommends ignoring and // clearing the BERR bit instead. if sr1.berr() { T::regs().sr1().modify(|reg| reg.set_berr(false)); } Ok(sr1) } unsafe fn write_bytes(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Error> { // Send a START condition T::regs().cr1().modify(|reg| { reg.set_start(i2c::vals::Start::START); }); // Wait until START condition was generated while self.check_and_clear_error_flags()?.sb() == i2c::vals::Sb::NOSTART {} // Also wait until signalled we're master and everything is waiting for us while { self.check_and_clear_error_flags()?; let sr2 = T::regs().sr2().read(); !sr2.msl() && !sr2.busy() } {} // Set up current address, we're trying to talk to T::regs().dr().write(|reg| reg.set_dr(addr << 1)); // Wait until address was sent while { // Check for any I2C errors. If a NACK occurs, the ADDR bit will never be set. let sr1 = self.check_and_clear_error_flags()?; // Wait for the address to be acknowledged !sr1.addr() } {} // Clear condition by reading SR2 let _ = T::regs().sr2().read(); // Send bytes for c in bytes { self.send_byte(*c)?; } // Fallthrough is success Ok(()) } unsafe fn send_byte(&self, byte: u8) -> Result<(), Error> { // Wait until we're ready for sending while { // Check for any I2C errors. If a NACK occurs, the ADDR bit will never be set. !self.check_and_clear_error_flags()?.tx_e() } {} // Push out a byte of data T::regs().dr().write(|reg| reg.set_dr(byte)); // Wait until byte is transferred while { // Check for any potential error conditions. !self.check_and_clear_error_flags()?.btf() } {} Ok(()) } unsafe fn recv_byte(&self) -> Result<u8, Error> { while { // Check for any potential error conditions. self.check_and_clear_error_flags()?; !T::regs().sr1().read().rx_ne() } {} let value = T::regs().dr().read().dr(); Ok(value) } } impl<'d, T: Instance> Read for I2c<'d, T> { type Error = Error; fn read(&mut self, addr: u8, buffer: &mut [u8]) -> Result<(), Self::Error> { if let Some((last, buffer)) = buffer.split_last_mut() { // Send a START condition and set ACK bit unsafe { T::regs().cr1().modify(|reg| { reg.set_start(i2c::vals::Start::START); reg.set_ack(true); }); } // Wait until START condition was generated while unsafe { T::regs().sr1().read().sb() } == i2c::vals::Sb::NOSTART {} // Also wait until signalled we're master and everything is waiting for us while { let sr2 = unsafe { T::regs().sr2().read() }; !sr2.msl() && !sr2.busy() } {} // Set up current address, we're trying to talk to unsafe { T::regs().dr().write(|reg| reg.set_dr((addr << 1) + 1)); } // Wait until address was sent while { unsafe { let sr1 = self.check_and_clear_error_flags()?; // Wait for the address to be acknowledged !sr1.addr() } } {} // Clear condition by reading SR2 unsafe { let _ = T::regs().sr2().read(); } // Receive bytes into buffer for c in buffer { *c = unsafe { self.recv_byte()? }; } // Prepare to send NACK then STOP after next byte unsafe { T::regs().cr1().modify(|reg| { reg.set_ack(false); reg.set_stop(i2c::vals::Stop::STOP); }); } // Receive last byte *last = unsafe { self.recv_byte()? }; // Wait for the STOP to be sent. while unsafe { T::regs().cr1().read().stop() == i2c::vals::Stop::STOP } {} // Fallthrough is success Ok(()) } else { Err(Error::Overrun) } } } impl<'d, T: Instance> Write for I2c<'d, T> { type Error = Error; fn write(&mut self, addr: u8, bytes: &[u8]) -> Result<(), Self::Error> { unsafe { self.write_bytes(addr, bytes)?; // Send a STOP condition T::regs() .cr1() .modify(|reg| reg.set_stop(i2c::vals::Stop::STOP)); // Wait for STOP condition to transmit. while T::regs().cr1().read().stop() == i2c::vals::Stop::STOP {} }; // Fallthrough is success Ok(()) } } impl<'d, T: Instance> WriteRead for I2c<'d, T> { type Error = Error; fn write_read(&mut self, addr: u8, bytes: &[u8], buffer: &mut [u8]) -> Result<(), Self::Error> { unsafe { self.write_bytes(addr, bytes)? }; self.read(addr, buffer)?; Ok(()) } } enum Mode { Fast, Standard, } impl Mode { fn f_s(&self) -> i2c::vals::FS { match self { Mode::Fast => i2c::vals::FS::FAST, Mode::Standard => i2c::vals::FS::STANDARD, } } } enum Duty { Duty2_1, Duty16_9, } impl Duty { fn duty(&self) -> i2c::vals::Duty { match self { Duty::Duty2_1 => i2c::vals::Duty::DUTY2_1, Duty::Duty16_9 => i2c::vals::Duty::DUTY16_9, } } } struct Timings { freq: u8, mode: Mode, trise: u8, ccr: u16, duty: Duty, } impl Timings { fn new(i2cclk: Hertz, speed: Hertz) -> Self { // Calculate settings for I2C speed modes let speed = speed.0; let clock = i2cclk.0; let freq = clock / 1_000_000; assert!(freq >= 2 && freq <= 50); // Configure bus frequency into I2C peripheral //self.i2c.cr2.write(|w| unsafe { w.freq().bits(freq as u8) }); let trise = if speed <= 100_000 { freq + 1 } else { (freq * 300) / 1000 + 1 }; let mut ccr; let duty; let mode; // I2C clock control calculation if speed <= 100_000 { duty = Duty::Duty2_1; mode = Mode::Standard; ccr = { let ccr = clock / (speed * 2); if ccr < 4 { 4 } else { ccr } }; } else { const DUTYCYCLE: u8 = 0; mode = Mode::Fast; if DUTYCYCLE == 0 { duty = Duty::Duty2_1; ccr = clock / (speed * 3); ccr = if ccr < 1 { 1 } else { ccr }; // Set clock to fast mode with appropriate parameters for selected speed (2:1 duty cycle) } else { duty = Duty::Duty16_9; ccr = clock / (speed * 25); ccr = if ccr < 1 { 1 } else { ccr }; // Set clock to fast mode with appropriate parameters for selected speed (16:9 duty cycle) } } Self { freq: freq as u8, trise: trise as u8, ccr: ccr as u16, duty, mode, //prescale: presc_reg, //scll, //sclh, //sdadel, //scldel, } } }
#[doc = r" Value read from the register"] pub struct R { bits: u32, } #[doc = r" Value to write to the register"] pub struct W { bits: u32, } impl super::BODCTRL { #[doc = r" Modifies the contents of the register"] #[inline] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.set(w.bits); } #[doc = r" Reads the contents of the register"] #[inline] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r" Writes to the register"] #[inline] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { let mut w = W::reset_value(); f(&mut w); self.register.set(w.bits); } #[doc = r" Writes the reset value to the register"] #[inline] pub fn reset(&self) { self.write(|w| w) } } #[doc = r" Value of the field"] pub struct BODHVREFSELR { bits: bool, } impl BODHVREFSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct BODLVREFSELR { bits: bool, } impl BODLVREFSELR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct BODFPWDR { bits: bool, } impl BODFPWDR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct BODCPWDR { bits: bool, } impl BODCPWDR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct BODHPWDR { bits: bool, } impl BODHPWDR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Value of the field"] pub struct BODLPWDR { bits: bool, } impl BODLPWDR { #[doc = r" Value of the field as raw bits"] #[inline] pub fn bit(&self) -> bool { self.bits } #[doc = r" Returns `true` if the bit is clear (0)"] #[inline] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r" Returns `true` if the bit is set (1)"] #[inline] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r" Proxy"] pub struct _BODHVREFSELW<'a> { w: &'a mut W, } impl<'a> _BODHVREFSELW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 5; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BODLVREFSELW<'a> { w: &'a mut W, } impl<'a> _BODLVREFSELW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 4; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BODFPWDW<'a> { w: &'a mut W, } impl<'a> _BODFPWDW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 3; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BODCPWDW<'a> { w: &'a mut W, } impl<'a> _BODCPWDW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 2; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BODHPWDW<'a> { w: &'a mut W, } impl<'a> _BODHPWDW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 1; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } #[doc = r" Proxy"] pub struct _BODLPWDW<'a> { w: &'a mut W, } impl<'a> _BODLPWDW<'a> { #[doc = r" Sets the field bit"] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r" Clears the field bit"] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r" Writes raw bits to the field"] #[inline] pub fn bit(self, value: bool) -> &'a mut W { const MASK: bool = true; const OFFSET: u8 = 0; self.w.bits &= !((MASK as u32) << OFFSET); self.w.bits |= ((value & MASK) as u32) << OFFSET; self.w } } impl R { #[doc = r" Value of the register as raw bits"] #[inline] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 5 - BODH External Reference Select. Note: the SWE mux select in PWRSEQ2SWE must be set for this to take effect."] #[inline] pub fn bodhvrefsel(&self) -> BODHVREFSELR { let bits = { const MASK: bool = true; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BODHVREFSELR { bits } } #[doc = "Bit 4 - BODL External Reference Select. Note: the SWE mux select in PWRSEQ2SWE must be set for this to take effect."] #[inline] pub fn bodlvrefsel(&self) -> BODLVREFSELR { let bits = { const MASK: bool = true; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BODLVREFSELR { bits } } #[doc = "Bit 3 - BODF Power Down."] #[inline] pub fn bodfpwd(&self) -> BODFPWDR { let bits = { const MASK: bool = true; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BODFPWDR { bits } } #[doc = "Bit 2 - BODC Power Down."] #[inline] pub fn bodcpwd(&self) -> BODCPWDR { let bits = { const MASK: bool = true; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BODCPWDR { bits } } #[doc = "Bit 1 - BODH Power Down."] #[inline] pub fn bodhpwd(&self) -> BODHPWDR { let bits = { const MASK: bool = true; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BODHPWDR { bits } } #[doc = "Bit 0 - BODL Power Down."] #[inline] pub fn bodlpwd(&self) -> BODLPWDR { let bits = { const MASK: bool = true; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) != 0 }; BODLPWDR { bits } } } impl W { #[doc = r" Reset value of the register"] #[inline] pub fn reset_value() -> W { W { bits: 0 } } #[doc = r" Writes raw bits to the register"] #[inline] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 5 - BODH External Reference Select. Note: the SWE mux select in PWRSEQ2SWE must be set for this to take effect."] #[inline] pub fn bodhvrefsel(&mut self) -> _BODHVREFSELW { _BODHVREFSELW { w: self } } #[doc = "Bit 4 - BODL External Reference Select. Note: the SWE mux select in PWRSEQ2SWE must be set for this to take effect."] #[inline] pub fn bodlvrefsel(&mut self) -> _BODLVREFSELW { _BODLVREFSELW { w: self } } #[doc = "Bit 3 - BODF Power Down."] #[inline] pub fn bodfpwd(&mut self) -> _BODFPWDW { _BODFPWDW { w: self } } #[doc = "Bit 2 - BODC Power Down."] #[inline] pub fn bodcpwd(&mut self) -> _BODCPWDW { _BODCPWDW { w: self } } #[doc = "Bit 1 - BODH Power Down."] #[inline] pub fn bodhpwd(&mut self) -> _BODHPWDW { _BODHPWDW { w: self } } #[doc = "Bit 0 - BODL Power Down."] #[inline] pub fn bodlpwd(&mut self) -> _BODLPWDW { _BODLPWDW { w: self } } }
extern crate image; // DMDBG: Not sure if this should really be speaking 'image' directly use std::boxed::Box; use std::collections::HashMap; use crate::shape; use crate::geometry; use geometry::{Ray, RayHit}; pub struct Scene { pub lights: HashMap<String, shape::PointLight>, pub shapes: HashMap<String, Box<dyn shape::Shape>>, } impl Scene { pub fn new() -> Self { return Scene { lights: HashMap::new(), shapes: HashMap::new(), }; } pub fn add_light(&mut self, name: &str, light: shape::PointLight) { self.lights.insert(name.to_string(), light); } pub fn get_light(&self, name: &str) -> Option<&shape::PointLight> { self.lights.get(name) } pub fn add_shape(&mut self, name: &str, shape: Box<dyn shape::Shape>) { self.shapes.insert(name.to_string(), shape); } pub fn get_shape(&self, name: &str) -> Option<&Box<dyn shape::Shape>> { self.shapes.get(name) } pub fn ray_cast(&self, ray: &Ray) -> Option<RayHit> { self.shapes .iter() .map(|item| item.1.ray_cast(&ray)) .filter(|hit| hit.is_some()) .map(|hit| hit.unwrap()) .max_by(|lhs, rhs| { let lhs_norm = lhs.near.coords.norm(); let rhs_norm = rhs.near.coords.norm(); //lhs_norm.partial_cmp(&rhs_norm).unwrap().reverse() if lhs_norm > rhs_norm { std::cmp::Ordering::Less } else if lhs_norm < rhs_norm { std::cmp::Ordering::Greater } else { std::cmp::Ordering::Equal } }) } pub fn paint(&self, hit: &RayHit) -> image::Rgb<u8> { let l_scene = self.get_light("light").unwrap().pose.translation; let n = hit.normal; let l = (l_scene * (-hit.near)).coords.normalize(); let light_ray = geometry::Ray { origin: hit.near, direction: l, }; match self.ray_cast(&light_ray) { Some(hit) => { return image::Rgb([0, 0, 0]); }, None => { let n_dot_l = n.dot(&l); let val = num::clamp(n_dot_l * 255.0, 0.0, 255.0) as u8; return image::Rgb([val, val, val]); } }; } }
#[doc = "Register `SQR1` reader"] pub type R = crate::R<SQR1_SPEC>; #[doc = "Register `SQR1` writer"] pub type W = crate::W<SQR1_SPEC>; #[doc = "Field `SQ13` reader - 13th conversion in regular sequence"] pub type SQ13_R = crate::FieldReader; #[doc = "Field `SQ13` writer - 13th conversion in regular sequence"] pub type SQ13_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `SQ14` reader - 14th conversion in regular sequence"] pub type SQ14_R = crate::FieldReader; #[doc = "Field `SQ14` writer - 14th conversion in regular sequence"] pub type SQ14_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `SQ15` reader - 15th conversion in regular sequence"] pub type SQ15_R = crate::FieldReader; #[doc = "Field `SQ15` writer - 15th conversion in regular sequence"] pub type SQ15_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `SQ16` reader - 16th conversion in regular sequence"] pub type SQ16_R = crate::FieldReader; #[doc = "Field `SQ16` writer - 16th conversion in regular sequence"] pub type SQ16_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 5, O>; #[doc = "Field `L` reader - Regular channel sequence length"] pub type L_R = crate::FieldReader; #[doc = "Field `L` writer - Regular channel sequence length"] pub type L_W<'a, REG, const O: u8> = crate::FieldWriterSafe<'a, REG, 4, O>; impl R { #[doc = "Bits 0:4 - 13th conversion in regular sequence"] #[inline(always)] pub fn sq13(&self) -> SQ13_R { SQ13_R::new((self.bits & 0x1f) as u8) } #[doc = "Bits 5:9 - 14th conversion in regular sequence"] #[inline(always)] pub fn sq14(&self) -> SQ14_R { SQ14_R::new(((self.bits >> 5) & 0x1f) as u8) } #[doc = "Bits 10:14 - 15th conversion in regular sequence"] #[inline(always)] pub fn sq15(&self) -> SQ15_R { SQ15_R::new(((self.bits >> 10) & 0x1f) as u8) } #[doc = "Bits 15:19 - 16th conversion in regular sequence"] #[inline(always)] pub fn sq16(&self) -> SQ16_R { SQ16_R::new(((self.bits >> 15) & 0x1f) as u8) } #[doc = "Bits 20:23 - Regular channel sequence length"] #[inline(always)] pub fn l(&self) -> L_R { L_R::new(((self.bits >> 20) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:4 - 13th conversion in regular sequence"] #[inline(always)] #[must_use] pub fn sq13(&mut self) -> SQ13_W<SQR1_SPEC, 0> { SQ13_W::new(self) } #[doc = "Bits 5:9 - 14th conversion in regular sequence"] #[inline(always)] #[must_use] pub fn sq14(&mut self) -> SQ14_W<SQR1_SPEC, 5> { SQ14_W::new(self) } #[doc = "Bits 10:14 - 15th conversion in regular sequence"] #[inline(always)] #[must_use] pub fn sq15(&mut self) -> SQ15_W<SQR1_SPEC, 10> { SQ15_W::new(self) } #[doc = "Bits 15:19 - 16th conversion in regular sequence"] #[inline(always)] #[must_use] pub fn sq16(&mut self) -> SQ16_W<SQR1_SPEC, 15> { SQ16_W::new(self) } #[doc = "Bits 20:23 - Regular channel sequence length"] #[inline(always)] #[must_use] pub fn l(&mut self) -> L_W<SQR1_SPEC, 20> { L_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "regular sequence register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sqr1::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`sqr1::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct SQR1_SPEC; impl crate::RegisterSpec for SQR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`sqr1::R`](R) reader structure"] impl crate::Readable for SQR1_SPEC {} #[doc = "`write(|w| ..)` method takes [`sqr1::W`](W) writer structure"] impl crate::Writable for SQR1_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets SQR1 to value 0"] impl crate::Resettable for SQR1_SPEC { const RESET_VALUE: Self::Ux = 0; }
//! Analog to a Python boolean type. //! //! It supports & and | operators, and comparison to Rust bool types. //! To return to Python use the ```into_raw``` method and return a raw pointer. //! //! # Safety //! You can convert a raw pointer to a bool type with ```from_ptr_into_bool``` method, //! or to a ```&PyBool``` with ```from_ptr``` method. Those operations are unsafe as they require //! dereferencing a raw pointer. //! //! # Examples //! //! ``` //! use rustypy::PyBool; //! let pybool = PyBool::from(true); //! assert_eq!(pybool, true); //! //! // prepare to return to Python: //! let ptr = pybool.into_raw(); //! // convert from raw pointer to a bool //! let rust_bool = unsafe { PyBool::from_ptr_into_bool(ptr) }; //! ``` use libc::c_char; use std::convert::From; use std::ops::{BitAnd, BitOr, Not}; /// Analog to a Python boolean type. /// /// Read the [module docs](index.html) for more information. #[derive(Clone, Debug, PartialEq, Eq, Hash, Copy)] pub struct PyBool { val: i8, } impl PyBool { /// Get a PyBool from a previously boxed raw pointer. pub unsafe fn from_ptr(ptr: *mut PyBool) -> PyBool { *(Box::from_raw(ptr)) } /// Creates a bool from a raw pointer to a PyBool. pub unsafe fn from_ptr_into_bool(ptr: *mut PyBool) -> bool { let ptr: &PyBool = &*ptr; match ptr.val { 0 => false, _ => true, } } /// Conversion from PyBool to bool. pub fn to_bool(self) -> bool { match self.val { 0 => false, _ => true, } } /// Returns PyBool as a raw pointer. Use this whenever you want to return /// a PyBool to Python. pub fn into_raw(self) -> *mut PyBool { Box::into_raw(Box::new(self)) } /// Sets value of the underlying bool pub fn load(&mut self, v: bool) { if v { self.val = 1 } else { self.val = 0 } } } #[doc(hidden)] #[no_mangle] pub unsafe extern "C" fn pybool_free(ptr: *mut PyBool) { if ptr.is_null() { return; } Box::from_raw(ptr); } #[doc(hidden)] #[no_mangle] pub extern "C" fn pybool_new(val: c_char) -> *mut PyBool { let val = match val { 0 => 0, _ => 1, }; let pystr = PyBool { val }; pystr.into_raw() } #[doc(hidden)] #[no_mangle] pub unsafe extern "C" fn pybool_get_val(ptr: *mut PyBool) -> i8 { let pybool = &*ptr; pybool.val } impl From<PyBool> for bool { fn from(b: PyBool) -> bool { b.to_bool() } } impl From<bool> for PyBool { fn from(b: bool) -> PyBool { let val = if b { 1 } else { 0 }; PyBool { val } } } impl<'a> From<&'a bool> for PyBool { fn from(b: &'a bool) -> PyBool { let val = if *b { 1 } else { 0 }; PyBool { val } } } impl From<i8> for PyBool { fn from(b: i8) -> PyBool { let val = match b { 0 => 0, _ => 1, }; PyBool { val } } } impl PartialEq<bool> for PyBool { fn eq(&self, other: &bool) -> bool { (self.val == 0 && !(*other)) || (self.val == 1 && *other) } } impl<'a> PartialEq<bool> for &'a PyBool { fn eq(&self, other: &bool) -> bool { (self.val == 0 && !(*other)) || (self.val == 1 && *other) } } impl Not for PyBool { type Output = bool; fn not(self) -> bool { match self.val { 0 => false, _ => true, } } } impl BitAnd<bool> for PyBool { type Output = bool; fn bitand(self, rhs: bool) -> bool { let val = match self.val { 0 => false, _ => true, }; val & rhs } } impl<'a> BitAnd<bool> for &'a PyBool { type Output = bool; fn bitand(self, rhs: bool) -> bool { let val = match self.val { 0 => false, _ => true, }; val & rhs } } impl<'a> BitAnd<&'a bool> for PyBool { type Output = bool; fn bitand(self, rhs: &'a bool) -> bool { let val = match self.val { 0 => false, _ => true, }; val & rhs } } impl<'a, 'b> BitAnd<&'a bool> for &'b PyBool { type Output = bool; fn bitand(self, rhs: &'a bool) -> bool { let val = match self.val { 0 => false, _ => true, }; val & rhs } } impl BitOr<bool> for PyBool { type Output = bool; fn bitor(self, rhs: bool) -> bool { let val = match self.val { 0 => false, _ => true, }; val | rhs } } impl<'a> BitOr<bool> for &'a PyBool { type Output = bool; fn bitor(self, rhs: bool) -> bool { let val = match self.val { 0 => false, _ => true, }; val | rhs } } impl<'a> BitOr<&'a bool> for PyBool { type Output = bool; fn bitor(self, rhs: &'a bool) -> bool { let val = match self.val { 0 => false, _ => true, }; val | rhs } } impl<'a, 'b> BitOr<&'a bool> for &'b PyBool { type Output = bool; fn bitor(self, rhs: &'a bool) -> bool { let val = match self.val { 0 => false, _ => true, }; val | rhs } }
/* Узнав на уроке информатики про шифрование данных при помощи открытых ключей, Вика и Катя решили создать собственный шифр. У Кати есть открытый ключ — набор из N чисел a1, a2, ..., aN. Вика передаёт ей N текстовых строк. Расшифровка будет являться словом, составленным из букв переданных строк. Первая буква должна встречаться в первой строке a1 раз, вторая — во второй a2 раз, и так далее. Помогите Кате расшифровать слово. */ use std::collections::{HashMap, VecDeque}; #[derive(Debug)] pub enum ReadError { FailedToRead, FailedToParse, } pub fn parse_read<T>() -> Result<T, ReadError> where T: std::str::FromStr, { let mut buffer = String::new(); std::io::stdin() .read_line(&mut buffer) .map_err(|_| ReadError::FailedToParse)?; Ok(buffer .trim() .parse::<T>() .map_err(|_| ReadError::FailedToParse)?) } pub fn main() { let count_of_strings: usize = parse_read().expect("Please, enter valid number"); let mut buffer = String::new(); std::io::stdin() .read_line(&mut buffer) .expect("Failed to read a line"); let mut keys = VecDeque::new(); for key in buffer.trim().split(" ") { keys.push_back(key.parse::<usize>().expect("Please, enter valid number")) } let mut strings: Vec<String> = Vec::new(); for _ in 0..count_of_strings { let mut text = String::new(); std::io::stdin() .read_line(&mut text) .expect("Failed to read a line"); strings.push(text); } let mut result = String::new(); for string in &strings { let mut count: HashMap<char, usize> = HashMap::new(); for char in string.trim().chars() { count .entry(char) .and_modify(|x| { *x += 1; }) .or_insert(1); } let required_count = keys.pop_front().unwrap(); for (element, count) in count { if count == required_count { result.push(element); } } } println!("{}", result); }
//! Virtualization implementation for normal, 'unstaged' Rust use quote::Tokens; use std::cmp::{PartialEq}; use std::mem; use std::ops::{Add, Sub, Not}; use codegen::{__Codegen, Tokenize}; use expr::{Pat, __ExprBlock, __ExprTuple, __Ref, __RefMut}; use ops::{__Not, __PartialEq, __Add, __Sub}; impl<CG, T> __Not<T> for CG where CG: __Codegen, T: Not, { type Output = <T as Not>::Output; fn __not(&mut self, expr: T) -> Self::Output { Not::not(expr) } } impl<CG, LHS, RHS> __PartialEq<LHS, RHS> for CG where CG: __Codegen, LHS: PartialEq<RHS>, { type Output = bool; fn __eq(&mut self, lhs: &LHS, rhs: &RHS) -> bool { PartialEq::eq(lhs, rhs) } fn __ne(&mut self, lhs: &LHS, rhs: &RHS) -> bool { PartialEq::ne(lhs, rhs) } } impl<CG, LHS, RHS> __Add<LHS, RHS> for CG where CG: __Codegen, LHS: Add<RHS>, { type Output = <LHS as Add<RHS>>::Output; fn __add(&mut self, lhs: LHS, rhs: RHS) -> Self::Output { Add::add(lhs, rhs) } } impl<CG, LHS, RHS> __Sub<LHS, RHS> for CG where CG: __Codegen, LHS: Sub<RHS>, { type Output = <LHS as Sub<RHS>>::Output; fn __sub(&mut self, lhs: LHS, rhs: RHS) -> Self::Output { Sub::sub(lhs, rhs) } } impl<CG, T> __ExprBlock<T> for CG where CG: __Codegen, { default fn __expr(&mut self, expr: T) -> T { expr } default fn __stmnt_local(&mut self, _: Pat, expr: T) -> T { expr } } default impl<CG, T> __ExprTuple<T> for CG where CG: __Codegen, { default type Output = T; default fn __expr(&mut self, tup: T) -> Self::Output { // !DANGER! // This works ****only**** when we always specialize both, // Output and __expr. unsafe { mem::transmute_copy(&tup) } } } default impl<T> Tokenize for T { fn tokens(self) -> Tokens { Tokens::new() } }
use std::slice; use ggez::graphics; pub use resources::Sounds; pub const CARD_WIDTH: f32 = 123.0; pub const CARD_HEIGHT: f32 = 233.0; pub const BUTTON_RADIUS: f32 = 30.0; pub const BUTTON_RADIUS_SQUARED: f32 = BUTTON_RADIUS * BUTTON_RADIUS; pub type Point2 = ggez::nalgebra::Point2<f32>; pub type Vector2 = ggez::nalgebra::Vector2<f32>; #[derive(Debug, Copy, Clone, Hash, Eq, PartialEq)] pub struct Entity(usize); impl Entity { pub fn new(id: usize) -> Entity { Entity(id) } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum Color { Red, Green, White, } impl Color { pub fn to_font_color(&self) -> graphics::Color { match *self { Color::Red => graphics::Color::new(0.7, 0.2, 0.1, 1.0), Color::Green => graphics::Color::new(0.1, 0.4, 0.3, 1.0), Color::White => graphics::Color::new(0.1, 0.1, 0.1, 1.0), } } pub fn to_icon_color(&self) -> graphics::Color { match *self { Color::Red => graphics::Color::new(1.0, 1.0, 1.0, 1.0), Color::Green => graphics::Color::new(0.1, 0.4, 0.3, 1.0), Color::White => graphics::Color::new(1.0, 1.0, 1.0, 1.0), } } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum ButtonState { Active, Up, Down, } #[derive(Debug)] pub struct Button { pub color: Color, pub state: ButtonState, pub stacks: Option<(Entity, [Entity; 4])>, } impl Button { pub fn new(color: Color) -> Button { Button { color, state: ButtonState::Up, stacks: None, } } } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum Suite { FaceDown, Flower, Dragon(Color), Number(u8, Color), } #[derive(Copy, Clone, Debug, Eq, PartialEq, Hash)] pub enum StackRole { Dragon, Flower, Target, Sorting, Generic, Animation, } #[derive(Clone, Hash, Eq, PartialEq, Debug)] pub struct Stack { pub cards: Vec<Suite>, pub role: StackRole, } impl Stack { pub fn new(role: StackRole) -> Stack { Stack { cards: Vec::new(), role, } } pub fn len(&self) -> usize { self.cards.len() } pub fn iter(&self) -> slice::Iter<Suite> { self.cards.iter() } pub fn top(&self) -> Option<Suite> { self.cards.last().map(|s| *s) } pub fn push_card(&mut self, card: Suite) { self.cards.push(card); } pub fn pop_card(&mut self) -> Option<Suite> { self.cards.pop() } pub fn extend(&mut self, other: Stack) { self.cards.extend(other.cards); } pub fn peek(&self, idx: usize) -> Suite { self.cards[idx] } pub fn get_stackshift(&self) -> Vector2 { match self.role { StackRole::Dragon => Vector2::new(0.1, -0.25), //StackRole::DragonLocked => Vector2::new(0.1, -0.25), StackRole::Flower => Vector2::new(0.1, -0.25), StackRole::Target => Vector2::new(0.1, -0.25), StackRole::Sorting => Vector2::new(0.0, 32.0), StackRole::Generic => Vector2::new(0.0, 32.0), StackRole::Animation => Vector2::new(0.0, 0.0), } } pub fn split(&mut self, at: usize) -> Stack { Stack { cards: self.cards.split_off(at), role: StackRole::Generic, } } } pub struct Animation { pub start_delay: f32, pub time_left: f32, pub target_pos: Point2, pub target_stack: Option<Entity>, pub sound_start: Sounds, pub sound_stop: Sounds, }
table! { anime (id) { id -> Integer, name -> Varchar, episodes -> Nullable<Integer>, slot1 -> Bool, slot2 -> Bool, slot3 -> Bool, } } table! { decisions (tournament, left_anime, right_anime) { tournament -> Integer, left_anime -> Integer, right_anime -> Integer, pick -> Nullable<Bool>, } } table! { tournaments (id) { id -> Integer, } } table! { tournament_anime (tournament, anime) { tournament -> Integer, anime -> Integer, } } allow_tables_to_appear_in_same_query!( anime, decisions, tournaments, tournament_anime, );
pub use self::{clip::*, comp::*, converter::*, prim::*, shape::*, transform::*, value::*}; use crate::{Model, SystemMessage}; pub mod builder; pub mod clip; pub mod comp; pub mod converter; pub mod prim; pub mod shape; pub mod transform; pub mod value; pub enum Node<M: Model> { Prim(Prim<M>), Comp(Comp), } impl<M: Model> Node<M> { pub fn get_id(&self) -> Option<&str> { match self { Node::Prim(prim) => prim.id(), Node::Comp(comp) => comp.id(), } } pub fn set_id(&mut self, id: impl Into<String>) { match self { Node::Prim(prim) => prim.shape.set_id(id), Node::Comp(comp) => comp.set_id(id), } } pub fn as_prim(&self) -> Option<&Prim<M>> { match self { Node::Prim(prim) => Some(prim), _ => None, } } pub fn as_prim_mut(&mut self) -> Option<&mut Prim<M>> { match self { Node::Prim(prim) => Some(prim), _ => None, } } pub fn into_prim(self) -> Option<Prim<M>> { match self { Node::Prim(prim) => Some(prim), _ => None, } } pub fn as_comp(&self) -> Option<&Comp> { match self { Node::Comp(comp) => Some(comp), _ => None, } } pub fn as_comp_mut(&mut self) -> Option<&mut Comp> { match self { Node::Comp(comp) => Some(comp), _ => None, } } pub fn into_comp(self) -> Option<Comp> { match self { Node::Comp(comp) => Some(comp), _ => None, } } pub fn get(&self, id: impl AsRef<str>) -> Option<&Node<M>> { let id = id.as_ref(); match self { Node::Prim(prim) if prim.id() == Some(id) => Some(self), Node::Prim(prim) => { for child in &prim.children { if let Some(node) = child.get(id) { return Some(node); } } None } Node::Comp(comp) if comp.id() == Some(id) => Some(self), _ => None, } } pub fn get_mut(&mut self, id: impl AsRef<str>) -> Option<&mut Node<M>> { let id = id.as_ref(); match self { Node::Prim(prim) if prim.id() == Some(id) => Some(self), Node::Prim(prim) => { for child in &mut prim.children { if let Some(node) = child.get_mut(id) { return Some(node); } } None } Node::Comp(comp) if comp.id() == Some(id) => Some(self), _ => None, } } pub fn get_prim(&self, id: impl AsRef<str>) -> Option<&Prim<M>> { let id = id.as_ref(); match self { Node::Prim(prim) => { if prim.id() == Some(id) { Some(prim) } else { for child in &prim.children { if let Some(prim) = child.get_prim(id) { return Some(prim); } } None } } _ => None, } } pub fn get_prim_mut(&mut self, id: impl AsRef<str>) -> Option<&mut Prim<M>> { let id = id.as_ref(); match self { Node::Prim(prim) => { if prim.id() == Some(id) { Some(prim) } else { for child in &mut prim.children { if let Some(prim) = child.get_prim_mut(id) { return Some(prim); } } None } } _ => None, } } pub fn get_comp_mut(&mut self, id: impl AsRef<str>) -> Option<&mut Comp> { let id = id.as_ref(); match self { Node::Comp(comp) if comp.id() == Some(id) => Some(comp), Node::Prim(prim) => { for child in &mut prim.children { if let Some(comp) = child.get_comp_mut(id) { return Some(comp); } } None } _ => None, } } pub fn transform_mut(&mut self) -> &mut Transform { match self { Node::Prim(prim) => prim.transform_mut(), Node::Comp(comp) => comp.transform_mut(), } } pub fn send_system_msg(&mut self, msg: SystemMessage, outputs: &mut Vec<M::Message>) { match self { Node::Prim(prim) => prim.send_system_msg(msg, outputs), Node::Comp(comp) => comp.send_system_msg(msg), } } pub fn update_view(&mut self) -> UpdateView { match self { Node::Prim(prim) => prim.update_view(), Node::Comp(comp) => comp.update_view(), } } } impl<M: Model> CompositeShape for Node<M> { fn shape(&self) -> Option<&Shape> { match self { Node::Prim(prim) => prim.shape(), Node::Comp(comp) => comp.shape(), } } fn shape_mut(&mut self) -> Option<&mut Shape> { match self { Node::Prim(prim) => prim.shape_mut(), Node::Comp(comp) => comp.shape_mut(), } } fn children(&self) -> Option<CompositeShapeIter> { match self { Node::Prim(prim) => CompositeShape::children(prim), Node::Comp(comp) => CompositeShape::children(comp), } } fn children_mut(&mut self) -> Option<CompositeShapeIterMut> { match self { Node::Prim(prim) => CompositeShape::children_mut(prim), Node::Comp(comp) => CompositeShape::children_mut(comp), } } fn need_recalc(&self) -> Option<bool> { match self { Node::Prim(prim) => CompositeShape::need_recalc(prim), Node::Comp(comp) => CompositeShape::need_recalc(comp), } } fn need_redraw(&self) -> Option<bool> { match self { Node::Prim(prim) => CompositeShape::need_redraw(prim), Node::Comp(comp) => CompositeShape::need_redraw(comp), } } }
use std::{collections::HashMap, path::PathBuf}; use structopt::StructOpt; use serde::Deserialize; type R<T> = Result<T, Box<dyn std::error::Error>>; #[derive(StructOpt)] struct Args { #[structopt(short, long)] /// The path to a json file containing an array of strings representing /// the target zip codes. If not provided all zipcodes will be considered zips_path: Option<PathBuf>, #[structopt(short, long)] /// the 2 digit state code to use to get current appointments state: String, #[structopt(short, long)] /// The email address to send alerts from from_email: Option<String>, #[structopt(short, long)] /// The email address to send alerts to to_email: Option<String>, } #[tokio::main] async fn main() -> R<()> { let args = Args::from_args(); let mut current_info: HashMap<u64, Vec<Appointment>> = HashMap::new(); let zips = fetch_considered_zips(&args.zips_path); loop { if let Ok(res) = reqwest::get(&format!( "https://www.vaccinespotter.org/api/v0/states/{}.json", args.state.to_uppercase() )) .await { let res: Response = res.json().await?; report_locations( &res.features, &current_info, &zips, &args.from_email, &args.to_email, ); current_info = res .features .into_iter() .map(|f| { ( f.properties.id, f.properties.appointments.unwrap_or_default(), ) }) .collect(); } tokio::time::sleep(std::time::Duration::from_secs(60)).await; } } fn report_locations( locations: &[Feature], current_info: &HashMap<u64, Vec<Appointment>>, zips: &[String], from_email: &Option<String>, to_email: &Option<String>, ) { if let (Some(from_email), Some(to_email)) = (from_email, to_email) { if let Err(e) = email_locations(locations, current_info, zips, from_email, to_email) { eprintln!( "Failed to send email from {} to {}: {}", from_email, to_email, e ); } } else { print_locations(locations, current_info, zips) } } #[cfg(not(feature = "email-notifications"))] fn email_locations( locations: &[Feature], current_info: &HashMap<u64, Vec<Appointment>>, zips: &[String], _from_email: &str, _to_email: &str, ) -> R<()> { print_locations(locations, current_info, zips); Ok(()) } fn print_locations( locations: &[Feature], current_info: &HashMap<u64, Vec<Appointment>>, zips: &[String], ) { let mut printed_preamble = false; for entry in locations { if let Some(appointments) = &entry.properties.appointments { if let Some(info) = current_info.get(&entry.properties.id) { if appointments != info && !appointments.is_empty() { if let Some(zip) = &entry.properties.postal_code { if zips.is_empty() || zips.contains(zip) { if !printed_preamble { println!("{}", "=".repeat(10)); println!("Report as of {}", chrono::Local::now()); println!("{}", "=".repeat(10)); printed_preamble = true } print_location(&entry.properties); } } } } else if !appointments.is_empty() { if let Some(zip) = &entry.properties.postal_code { if zips.is_empty() || zips.contains(zip) { if !printed_preamble { println!("{}", "=".repeat(10)); println!("Report as of {}", chrono::Local::now()); println!("{}", "=".repeat(10)); printed_preamble = true } print_location(&entry.properties); } } } } } } fn print_location(props: &Properties) { println!("{}", "+".repeat(10)); println!("{}", props); println!("{}", "+".repeat(10)); } #[cfg(feature = "email-notifications")] fn email_locations( locations: &[Feature], current_info: &HashMap<u64, Vec<Appointment>>, zips: &[String], from_email: &str, to_email: &str, ) -> R<()> { use lettre::{Message, SmtpTransport, Transport}; let mut body = format!( "{}\nReport as of {}\n{}\n\n", "=".repeat(10), chrono::Local::now(), "=".repeat(10), ); let mut send = false; for entry in locations { if let Some(appointments) = &entry.properties.appointments { if let Some(info) = current_info.get(&entry.properties.id) { if appointments != info { if let Some(zip) = &entry.properties.postal_code { if zips.is_empty() || zips.contains(zip) { send = true; body.push_str(&format!( "{}\n{}\n{}\n", "+".repeat(10), &entry.properties, "+".repeat(10) )) } } } } else if !appointments.is_empty() { if let Some(zip) = &entry.properties.postal_code { if zips.is_empty() || zips.contains(zip) { send = true; body.push_str(&format!( "{}\n{}\n{}\n", "+".repeat(10), &entry.properties, "+".repeat(10) )) } } } } } if !send { return Ok(()); } let email = Message::builder() .to(from_email.parse()?) .to(to_email.parse()?) .subject("New Vaccine Appointments") .body(body)?; // Open a local connection on port 25 let mailer = SmtpTransport::unencrypted_localhost(); // Send the email mailer.send(&email)?; Ok(()) } fn fetch_considered_zips(path: &Option<PathBuf>) -> Vec<String> { if let Some(path) = path { let s = match std::fs::read_to_string(path) { Ok(s) => s, Err(e) => { eprintln!("failed to read zips.json to string: {}", e); return Vec::new(); } }; serde_json::from_str(&s).unwrap_or_default() } else { Vec::new() } } #[derive(Clone, Debug, Deserialize)] struct Response { features: Vec<Feature>, } #[derive(Clone, Debug, Deserialize)] struct Feature { properties: Properties, } #[derive(Clone, Debug, Deserialize)] struct Properties { id: u64, url: Option<String>, city: Option<String>, state: Option<String>, address: Option<String>, name: Option<String>, provider: Option<String>, postal_code: Option<String>, carries_vaccine: Option<bool>, appointments_available: Option<bool>, appointments_available_all_doses: Option<bool>, appointments_available_2nd_dose_only: Option<bool>, appointments: Option<Vec<Appointment>>, } impl std::fmt::Display for Properties { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { writeln!( f, "{}-{}", string_or_question(&self.provider), string_or_question(&self.name) )?; writeln!(f, "{}", string_or_question(&self.url))?; writeln!(f, "{}", string_or_question(&self.address))?; writeln!( f, "{}, {} {}", string_or_question(&self.city), string_or_question(&self.state), string_or_question(&self.postal_code) )?; if let Some(apts) = &self.appointments { for (i, apt) in apts.iter().enumerate() { if i > 0 { write!(f, ", ")?; } write!(f, "{}", apt.time)?; } } writeln!(f, "") } } fn string_or_question(o: &Option<String>) -> &str { if let Some(o) = o { o } else { "??" } } #[derive(Clone, Debug, Deserialize, PartialEq)] struct Appointment { time: String, } impl PartialEq<str> for Appointment { fn eq(&self, other: &str) -> bool { self.time == other } }
//! Module for the message struct. use serde::{Deserialize, Serialize}; /// The struct representing a message. #[derive(Clone, Debug, Serialize, Deserialize)] pub struct Message {}
extern crate wasm_bindgen; use wasm_bindgen::prelude::*; use shortscale::shortscale; #[wasm_bindgen] pub fn numwords(num: u64) -> String { return shortscale(num); }
pub mod addstream; pub mod removestream; pub mod tracked; use std::{borrow::Cow, sync::Arc}; use twilight_model::application::interaction::{ application_command::CommandOptionValue, ApplicationCommand, }; use crate::{ util::{constants::common_literals::NAME, CowUtils}, Args, BotResult, Context, Error, }; pub use self::{addstream::*, removestream::*, tracked::*}; use super::{MyCommand, MyCommandOption}; enum StreamCommandKind { Add(String), Remove(String), List, } struct StreamArgs; impl StreamArgs { fn args<'n>(args: &mut Args<'n>) -> Result<Cow<'n, str>, &'static str> { match args.next() { Some(arg) => Ok(arg.cow_to_ascii_lowercase()), None => Err("The first argument must be the name of the stream"), } } fn slash(command: &mut ApplicationCommand) -> BotResult<StreamCommandKind> { command .data .options .pop() .and_then(|option| match option.value { CommandOptionValue::SubCommand(mut options) => match option.name.as_str() { "add" => options .pop() .filter(|option| option.name == NAME) .and_then(|option| match option.value { CommandOptionValue::String(value) => Some(value), _ => None, }) .map(StreamCommandKind::Add), "list" => Some(StreamCommandKind::List), "remove" => options .pop() .filter(|option| option.name == NAME) .and_then(|option| match option.value { CommandOptionValue::String(value) => Some(value), _ => None, }) .map(StreamCommandKind::Remove), _ => None, }, _ => None, }) .ok_or(Error::InvalidCommandOptions) } } pub async fn slash_trackstream( ctx: Arc<Context>, mut command: ApplicationCommand, ) -> BotResult<()> { match StreamArgs::slash(&mut command)? { StreamCommandKind::Add(name) => _addstream(ctx, command.into(), name.as_str()).await, StreamCommandKind::Remove(name) => _removestream(ctx, command.into(), name.as_str()).await, StreamCommandKind::List => tracked(ctx, command.into()).await, } } fn option_name() -> MyCommandOption { MyCommandOption::builder(NAME, "Name of the twitch channel").string(Vec::new(), true) } fn subcommand_add() -> MyCommandOption { let help = "Track a twitch stream in this channel.\n\ When the stream goes online, a notification will be send to this channel within a few minutes."; MyCommandOption::builder("add", "Track a twitch stream in this channel") .help(help) .subcommand(vec![option_name()]) } fn subcommand_remove() -> MyCommandOption { MyCommandOption::builder("remove", "Untrack a twitch stream in this channel") .subcommand(vec![option_name()]) } fn subcommand_list() -> MyCommandOption { MyCommandOption::builder("list", "List all tracked twitch stream in this channel") .subcommand(Vec::new()) } pub fn define_trackstream() -> MyCommand { let options = vec![subcommand_add(), subcommand_remove(), subcommand_list()]; let description = "(Un)track a twitch stream or list all tracked streams in this channel"; MyCommand::new("trackstream", description) .options(options) .authority() }
use async_std::task; pub struct Script { }
use std::io; use rotor::mio; use rotor::{Scope, Time, PollOpt, EventSet}; use rotor::{_scope, _Timeo, _Notify, _LoopApi}; /// Operation that was done with Scope #[derive(Debug, PartialEq, Eq)] pub enum Operation { Register(EventSet, PollOpt), Reregister(EventSet, PollOpt), Deregister, Shutdown, } struct Handler { operations: Vec<Operation>, } /// A mock loop implementation /// /// It's not actually fully working loop, just a thing which you can get /// a `Scope` object from. pub struct MockLoop<C> { event_loop: mio::EventLoop<Handler>, handler: Handler, context: C, channel: mio::Sender<_Notify>, } impl<C> MockLoop<C> { /// Create a mock loop /// /// The `ctx` is a context, and it's type must be compatible /// to your state machine. pub fn new(ctx: C) -> MockLoop<C> { let eloop = mio::EventLoop::new() .expect("event loop is crated"); MockLoop { handler: Handler { operations: Vec::new(), }, channel: eloop.channel(), event_loop: eloop, context: ctx, } } /// Get a scope object for specified token /// /// This is useful to call state machine actions directly pub fn scope(&mut self, x: usize) -> Scope<C> { _scope(Time::zero(), mio::Token(x), &mut self.context, &mut self.channel, &mut self.handler) } pub fn ctx(&mut self) -> &mut C { &mut self.context } } impl mio::Handler for Handler { type Timeout = _Timeo; type Message = _Notify; } impl _LoopApi for Handler { fn register(&mut self, _io: &mio::Evented, _token: mio::Token, interest: EventSet, opt: PollOpt) -> io::Result<()> { self.operations.push(Operation::Register(interest, opt)); Ok(()) } fn reregister(&mut self, _io: &mio::Evented, _token: mio::Token, interest: EventSet, opt: PollOpt) -> io::Result<()> { self.operations.push(Operation::Reregister(interest, opt)); Ok(()) } fn deregister(&mut self, _io: &mio::Evented) -> io::Result<()> { self.operations.push(Operation::Deregister); Ok(()) } fn timeout_ms(&mut self, _token: mio::Token, _delay: u64) -> Result<mio::Timeout, mio::TimerError> { panic!("Deprecated API"); } fn clear_timeout(&mut self, _token: mio::Timeout) -> bool { panic!("Deprecated API"); } fn shutdown(&mut self) { self.operations.push(Operation::Shutdown); } } #[cfg(test)] mod self_test { use rotor::{Machine, EventSet, Scope, Response}; use rotor::void::{unreachable, Void}; use super::MockLoop; #[derive(PartialEq, Eq, Debug)] struct M(u32); impl Machine for M { type Context = (); type Seed = Void; fn create(seed: Self::Seed, _scope: &mut Scope<()>) -> Response<Self, Void> { unreachable(seed) } fn ready(self, _events: EventSet, _scope: &mut Scope<()>) -> Response<Self, Self::Seed> { unimplemented!(); } fn spawned(self, _scope: &mut Scope<()>) -> Response<Self, Self::Seed> { unimplemented!(); } fn timeout(self, _scope: &mut Scope<()>) -> Response<Self, Self::Seed> { unimplemented!(); } fn wakeup(self, _scope: &mut Scope<()>) -> Response<Self, Self::Seed> { Response::ok(M(self.0 + 1)) } } #[test] fn test_machine() { let mut factory = MockLoop::new(()); let m = M(10); let mut value = None; Machine::wakeup(m, &mut factory.scope(1)).wrap(|x| value = Some(x)); assert_eq!(value, Some(M(11))); } }
#[doc = "Reader of register RX_MATCH"] pub type R = crate::R<u32, super::RX_MATCH>; #[doc = "Writer for register RX_MATCH"] pub type W = crate::W<u32, super::RX_MATCH>; #[doc = "Register RX_MATCH `reset()`'s with value 0"] impl crate::ResetValue for super::RX_MATCH { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0 } } #[doc = "Reader of field `ADDR`"] pub type ADDR_R = crate::R<u8, u8>; #[doc = "Write proxy for field `ADDR`"] pub struct ADDR_W<'a> { w: &'a mut W, } impl<'a> ADDR_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !0xff) | ((value as u32) & 0xff); self.w } } #[doc = "Reader of field `MASK`"] pub type MASK_R = crate::R<u8, u8>; #[doc = "Write proxy for field `MASK`"] pub struct MASK_W<'a> { w: &'a mut W, } impl<'a> MASK_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0xff << 16)) | (((value as u32) & 0xff) << 16); self.w } } impl R { #[doc = "Bits 0:7 - N/A"] #[inline(always)] pub fn addr(&self) -> ADDR_R { ADDR_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 16:23 - Slave device address mask. This field is a mask that specifies which of the slave address bits take part in the matching. MATCH = ((ADDR & MASK) == ('slave address' & MASK))."] #[inline(always)] pub fn mask(&self) -> MASK_R { MASK_R::new(((self.bits >> 16) & 0xff) as u8) } } impl W { #[doc = "Bits 0:7 - N/A"] #[inline(always)] pub fn addr(&mut self) -> ADDR_W { ADDR_W { w: self } } #[doc = "Bits 16:23 - Slave device address mask. This field is a mask that specifies which of the slave address bits take part in the matching. MATCH = ((ADDR & MASK) == ('slave address' & MASK))."] #[inline(always)] pub fn mask(&mut self) -> MASK_W { MASK_W { w: self } } }
use super::types::{DiffOptions, Only}; use crate::data::{Entry, Item}; use crate::index::Indexer; use crate::path_str; use anyhow::Result; use std::path::PathBuf; pub struct DiffHandler { indexer: Indexer, items: Vec<Item>, options: DiffOptions, } impl DiffHandler { pub fn new( home: PathBuf, repository: PathBuf, items: Vec<Item>, options: DiffOptions, only: Option<Only>, ) -> Self { let indexer = Indexer::new(home, repository, only); Self { indexer, items, options, } } pub fn diff(&self) -> Result<()> { let entries = self.indexer.index(&self.items)?; let entries: Vec<&Entry> = entries .iter() .flat_map(|(_name, es)| es) .filter(|e| e.is_diff()) .collect(); if entries.is_empty() { println!("All up to date."); return Ok(()); } for entry in entries { if let Entry::Ok { home_path, repo_path, .. } = entry { let a = path_str!(home_path); let b = path_str!(repo_path); let mut cmd = self.options.to_cmd(&a, &b)?; cmd.status()?; } } Ok(()) } }
use super::FPS_INTERVAL; /// Tracks frames per second. pub struct FpsCounter { fps: f64, time_acc: f64, frames_acc: f64, } impl FpsCounter { pub fn new() -> FpsCounter { FpsCounter { fps: 0.0, time_acc: 0.0, frames_acc: 0.0, } } pub fn fps(&self) -> f64 { self.fps } pub fn update(&mut self, dt: f64) { self.time_acc += dt; self.frames_acc += 1.0; if self.time_acc > FPS_INTERVAL { self.fps = self.frames_acc / self.time_acc; self.time_acc = 0.0; self.frames_acc = 0.0; } } }
use seed::{prelude::*, *}; use std::borrow::Cow; pub const TITLE: &str = "Example D"; pub const DESCRIPTION: &str = "Click button 'Send request` to send request to endpoint with configurable delay. Click again to disable timeout - otherwise the request will time out."; const TIMEOUT: u32 = 2000; fn get_request_url() -> impl Into<Cow<'static, str>> { let response_delay_ms: u32 = 2500; format!("/api/delayed-response/{}", response_delay_ms) } // ------ ------ // Model // ------ ------ #[derive(Default)] pub struct Model { pub fetch_result: Option<fetch::Result<String>>, pub request_controller: Option<fetch::RequestController>, pub status: Status, } pub enum TimeoutStatus { Enabled, Disabled, } pub enum Status { ReadyToSendRequest, WaitingForResponse(TimeoutStatus), } impl Default for Status { fn default() -> Self { Self::ReadyToSendRequest } } // ------ ------ // Update // ------ ------ pub enum Msg { SendRequest, DisableTimeout, Fetched(fetch::Result<String>), } pub fn update(msg: Msg, model: &mut Model, orders: &mut impl Orders<Msg>) { match msg { Msg::SendRequest => { let (request, controller) = Request::new(get_request_url()) .timeout(TIMEOUT) .controller(); model.status = Status::WaitingForResponse(TimeoutStatus::Enabled); model.fetch_result = None; model.request_controller = Some(controller); orders.perform_cmd(async { Msg::Fetched(async { fetch(request).await?.text().await }.await) }); } Msg::DisableTimeout => { if let Some(controller) = &model.request_controller { controller.disable_timeout().expect("disable timeout"); } model.status = Status::WaitingForResponse(TimeoutStatus::Disabled) } Msg::Fetched(fetch_result) => { model.status = Status::ReadyToSendRequest; model.fetch_result = Some(fetch_result); } } } // ------ ------ // View // ------ ------ pub fn view(model: &Model, intro: impl FnOnce(&str, &str) -> Vec<Node<Msg>>) -> Vec<Node<Msg>> { nodes![ intro(TITLE, DESCRIPTION), match &model.fetch_result { None => IF!(matches!(model.status, Status::WaitingForResponse(_)) => div!["Waiting for response..."]), Some(Ok(result)) => Some(div![format!("Server returned: {:#?}", result)]), Some(Err(fetch_error)) => Some(div![format!("{:#?}", fetch_error)]), }, view_button(&model.status), ] } pub fn view_button(status: &Status) -> Node<Msg> { match status { Status::WaitingForResponse(TimeoutStatus::Enabled) => { button![ev(Ev::Click, |_| Msg::DisableTimeout), "Disable timeout"] } Status::WaitingForResponse(TimeoutStatus::Disabled) => { button![attrs! {"disabled" => true}, "Timeout disabled"] } _ => button![ev(Ev::Click, |_| Msg::SendRequest), "Send request"], } }
use anyhow::Result; fn main() { let input = load("input/day4").unwrap(); println!("{}", validate_part1(&input)); println!("{}", validate_part2(&input)); } fn load(input: &str) -> Result<String> { Ok(std::fs::read_to_string(input)?) } #[test] fn test_load() { assert_eq!(load("input/day4tdd").unwrap().lines().count(), 13); } fn validate_part1(input: &str) -> usize { let input = input.replace('\n', " ").replace(" ", "\n"); input .lines() .filter(|line| validate_passport_part1(line)) .count() } fn validate_passport_part1(line: &str) -> bool { let fields = vec![ "byr", "iyr", "eyr", "hgt", "hcl", "ecl", "pid", /*"cid"*/ ]; fields.iter().filter(|field| line.contains(*field)).count() == fields.len() } #[test] fn test_part1() { let input = load("input/day4tdd").unwrap(); assert_eq!(validate_part1(&input), 2); } /// Stolen from https://old.reddit.com/r/rust/comments/k6fgrs/advent_of_code_2020_day_4/gelwfuz/ /// as I find it readable and efficient! fn validate_part2(line: &str) -> usize { line.split_terminator("\n\n") .map(|a| { a.split_whitespace() .map(|p| p.split(':')) .filter_map(|mut pair| { let in_range = |v: &str, a, b| Some((a..=b).contains(&v.parse::<u32>().ok()?)); let (key, val) = (pair.next()?, pair.next()?); Some(match (key, val.len()) { ("byr", 4) if in_range(val, 1920, 2002)? => 0, ("iyr", 4) if in_range(val, 2010, 2020)? => 1, ("eyr", 4) if in_range(val, 2020, 2030)? => 2, ("hgt", _) if val .strip_suffix("cm") .and_then(|h| in_range(h, 150, 193)) .or_else(|| { val.strip_suffix("in").and_then(|h| in_range(h, 59, 76)) })? => { 3 } ("hcl", 7) if val .strip_prefix('#')? .chars() .all(|c| matches!(c,'0'..='9'|'a'..='f')) => { 4 } ("pid", 9) if val.chars().all(|c| c.is_ascii_digit()) => 5, ("ecl", 3) if matches!( val, "amb" | "blu" | "brn" | "gry" | "grn" | "hzl" | "oth" ) => { 6 } _ => return None, }) }) .fold(0, |acc, index| acc | (1 << index)) }) .filter(|&bitset| bitset == 0b111_1111) .count() }
extern crate dmbc; extern crate exonum; extern crate exonum_testkit; extern crate hyper; extern crate iron; extern crate iron_test; extern crate mount; extern crate serde_json; pub mod dmbc_testkit; use std::collections::HashMap; use dmbc_testkit::{DmbcTestApiBuilder, DmbcTestKitApi}; use exonum::crypto; use hyper::status::StatusCode; use dmbc::currency::api::fees::FeesResponseBody; use dmbc::currency::configuration::{Configuration, TransactionFees, TransactionPermissions}; use dmbc::currency::error::Error; use dmbc::currency::transactions::builders::transaction; use dmbc::currency::transactions::components::FeeStrategy; #[test] fn fees_for_exchange_intermediary_recipient() { let transaction_fee = 1000; let fixed = 10; let units = 2; let meta_data0 = "asset0"; let meta_data1 = "asset1"; let meta_data2 = "asset2"; let meta_data3 = "asset3"; let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0); let permissions = TransactionPermissions::default(); let (creator_pub_key, _) = crypto::gen_keypair(); let (sender_public_key, sender_secret_key) = crypto::gen_keypair(); let (recipient_public_key, recipient_secret_key) = crypto::gen_keypair(); let (intermediary_public_key, intermediary_secret_key) = crypto::gen_keypair(); let (asset0, info0) = dmbc_testkit::create_asset( meta_data0, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset1, info1) = dmbc_testkit::create_asset( meta_data1, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset2, info2) = dmbc_testkit::create_asset( meta_data2, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset3, info3) = dmbc_testkit::create_asset( meta_data3, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_asset_to_wallet(&sender_public_key, (asset0.clone(), info0)) .add_asset_to_wallet(&sender_public_key, (asset1.clone(), info1)) .add_asset_to_wallet(&sender_public_key, (asset2.clone(), info2)) .add_asset_to_wallet(&recipient_public_key, (asset3.clone(), info3)) .create(); let api = testkit.api(); let tx_exchange_assets = transaction::Builder::new() .keypair(recipient_public_key, recipient_secret_key) .tx_exchange_with_intermediary() .sender_key_pair(sender_public_key, sender_secret_key) .intermediary_key_pair(intermediary_public_key, intermediary_secret_key) .fee_strategy(FeeStrategy::Recipient) .sender_add_asset_value(asset0) .sender_add_asset_value(asset1) .sender_add_asset_value(asset2) .recipient_add_asset_value(asset3) .build(); let (status, response) = api.post_fee(&tx_exchange_assets); let mut expected = HashMap::new(); let expected_fee = transaction_fee + fixed * units * 4; expected.insert(recipient_public_key, expected_fee); assert_eq!(status, StatusCode::Ok); assert_eq!(response, Ok(Ok(FeesResponseBody { fees: expected }))); } #[test] fn fees_for_exchange_intermediary_sender() { let transaction_fee = 1000; let fixed = 10; let units = 2; let meta_data0 = "asset0"; let meta_data1 = "asset1"; let meta_data2 = "asset2"; let meta_data3 = "asset3"; let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0); let permissions = TransactionPermissions::default(); let (creator_pub_key, _) = crypto::gen_keypair(); let (sender_public_key, sender_secret_key) = crypto::gen_keypair(); let (recipient_public_key, recipient_secret_key) = crypto::gen_keypair(); let (intermediary_public_key, intermediary_secret_key) = crypto::gen_keypair(); let (asset0, info0) = dmbc_testkit::create_asset( meta_data0, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset1, info1) = dmbc_testkit::create_asset( meta_data1, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset2, info2) = dmbc_testkit::create_asset( meta_data2, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset3, info3) = dmbc_testkit::create_asset( meta_data3, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_asset_to_wallet(&sender_public_key, (asset0.clone(), info0)) .add_asset_to_wallet(&sender_public_key, (asset1.clone(), info1)) .add_asset_to_wallet(&sender_public_key, (asset2.clone(), info2)) .add_asset_to_wallet(&recipient_public_key, (asset3.clone(), info3)) .create(); let api = testkit.api(); let tx_exchange_assets = transaction::Builder::new() .keypair(recipient_public_key, recipient_secret_key) .tx_exchange_with_intermediary() .sender_key_pair(sender_public_key, sender_secret_key) .intermediary_key_pair(intermediary_public_key, intermediary_secret_key) .fee_strategy(FeeStrategy::Sender) .sender_add_asset_value(asset0) .sender_add_asset_value(asset1) .sender_add_asset_value(asset2) .recipient_add_asset_value(asset3) .build(); let (status, response) = api.post_fee(&tx_exchange_assets); let mut expected = HashMap::new(); let expected_fee = transaction_fee + fixed * units * 4; expected.insert(sender_public_key, expected_fee); assert_eq!(status, StatusCode::Ok); assert_eq!(response, Ok(Ok(FeesResponseBody { fees: expected }))); } #[test] fn fees_for_exchange_intermediary_recipient_and_sender() { let transaction_fee = 1000; let fixed = 10; let units = 2; let meta_data0 = "asset0"; let meta_data1 = "asset1"; let meta_data2 = "asset2"; let meta_data3 = "asset3"; let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0); let permissions = TransactionPermissions::default(); let (creator_pub_key, _) = crypto::gen_keypair(); let (sender_public_key, sender_secret_key) = crypto::gen_keypair(); let (recipient_public_key, recipient_secret_key) = crypto::gen_keypair(); let (intermediary_public_key, intermediary_secret_key) = crypto::gen_keypair(); let (asset0, info0) = dmbc_testkit::create_asset( meta_data0, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset1, info1) = dmbc_testkit::create_asset( meta_data1, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset2, info2) = dmbc_testkit::create_asset( meta_data2, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset3, info3) = dmbc_testkit::create_asset( meta_data3, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_asset_to_wallet(&sender_public_key, (asset0.clone(), info0)) .add_asset_to_wallet(&sender_public_key, (asset1.clone(), info1)) .add_asset_to_wallet(&sender_public_key, (asset2.clone(), info2)) .add_asset_to_wallet(&recipient_public_key, (asset3.clone(), info3)) .create(); let api = testkit.api(); let tx_exchange_assets = transaction::Builder::new() .keypair(recipient_public_key, recipient_secret_key) .tx_exchange_with_intermediary() .sender_key_pair(sender_public_key, sender_secret_key) .intermediary_key_pair(intermediary_public_key, intermediary_secret_key) .fee_strategy(FeeStrategy::RecipientAndSender) .sender_add_asset_value(asset0) .sender_add_asset_value(asset1) .sender_add_asset_value(asset2) .recipient_add_asset_value(asset3) .build(); let (status, response) = api.post_fee(&tx_exchange_assets); let mut expected = HashMap::new(); let expected_fee = transaction_fee / 2 + fixed * units * 2; expected.insert(sender_public_key, expected_fee); expected.insert(recipient_public_key, expected_fee); assert_eq!(status, StatusCode::Ok); assert_eq!(response, Ok(Ok(FeesResponseBody { fees: expected }))); } #[test] fn fees_for_exchange_intermediary_intermediary() { let transaction_fee = 1000; let fixed = 10; let units = 2; let meta_data0 = "asset0"; let meta_data1 = "asset1"; let meta_data2 = "asset2"; let meta_data3 = "asset3"; let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0); let permissions = TransactionPermissions::default(); let (creator_pub_key, _) = crypto::gen_keypair(); let (sender_public_key, sender_secret_key) = crypto::gen_keypair(); let (recipient_public_key, recipient_secret_key) = crypto::gen_keypair(); let (intermediary_public_key, intermediary_secret_key) = crypto::gen_keypair(); let (asset0, info0) = dmbc_testkit::create_asset( meta_data0, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset1, info1) = dmbc_testkit::create_asset( meta_data1, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset2, info2) = dmbc_testkit::create_asset( meta_data2, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset3, info3) = dmbc_testkit::create_asset( meta_data3, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_asset_to_wallet(&sender_public_key, (asset0.clone(), info0)) .add_asset_to_wallet(&sender_public_key, (asset1.clone(), info1)) .add_asset_to_wallet(&sender_public_key, (asset2.clone(), info2)) .add_asset_to_wallet(&recipient_public_key, (asset3.clone(), info3)) .create(); let api = testkit.api(); let tx_exchange_assets = transaction::Builder::new() .keypair(recipient_public_key, recipient_secret_key) .tx_exchange_with_intermediary() .sender_key_pair(sender_public_key, sender_secret_key) .intermediary_key_pair(intermediary_public_key, intermediary_secret_key) .fee_strategy(FeeStrategy::Intermediary) .sender_add_asset_value(asset0) .sender_add_asset_value(asset1) .sender_add_asset_value(asset2) .recipient_add_asset_value(asset3) .build(); let (status, response) = api.post_fee(&tx_exchange_assets); let mut expected = HashMap::new(); let expected_fee = transaction_fee + fixed * units * 4; expected.insert(intermediary_public_key, expected_fee); assert_eq!(status, StatusCode::Ok); assert_eq!(response, Ok(Ok(FeesResponseBody { fees: expected }))); } #[test] fn fees_for_exchange_intermediary_recipient_and_sender_creator() { let transaction_fee = 1000; let fixed = 10; let units = 2; let meta_data0 = "asset0"; let meta_data1 = "asset1"; let meta_data2 = "asset2"; let meta_data3 = "asset3"; let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0); let permissions = TransactionPermissions::default(); let (sender_public_key, sender_secret_key) = crypto::gen_keypair(); let (recipient_public_key, recipient_secret_key) = crypto::gen_keypair(); let (intermediary_public_key, intermediary_secret_key) = crypto::gen_keypair(); let (asset0, info0) = dmbc_testkit::create_asset( meta_data0, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &sender_public_key, ); let (asset1, info1) = dmbc_testkit::create_asset( meta_data1, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &sender_public_key, ); let (asset2, info2) = dmbc_testkit::create_asset( meta_data2, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &sender_public_key, ); let (asset3, info3) = dmbc_testkit::create_asset( meta_data3, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &sender_public_key, ); let testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .add_asset_to_wallet(&sender_public_key, (asset0.clone(), info0)) .add_asset_to_wallet(&sender_public_key, (asset1.clone(), info1)) .add_asset_to_wallet(&sender_public_key, (asset2.clone(), info2)) .add_asset_to_wallet(&recipient_public_key, (asset3.clone(), info3)) .create(); let api = testkit.api(); let tx_exchange_assets = transaction::Builder::new() .keypair(recipient_public_key, recipient_secret_key) .tx_exchange_with_intermediary() .sender_key_pair(sender_public_key, sender_secret_key) .intermediary_key_pair(intermediary_public_key, intermediary_secret_key) .fee_strategy(FeeStrategy::RecipientAndSender) .sender_add_asset_value(asset0) .sender_add_asset_value(asset1) .sender_add_asset_value(asset2) .recipient_add_asset_value(asset3) .build(); let (status, response) = api.post_fee(&tx_exchange_assets); let mut expected = HashMap::new(); let expected_sender_fee = transaction_fee / 2; let expected_recipient_fee = transaction_fee / 2 + fixed * units * 2; expected.insert(sender_public_key, expected_sender_fee); expected.insert(recipient_public_key, expected_recipient_fee); assert_eq!(status, StatusCode::Ok); assert_eq!(response, Ok(Ok(FeesResponseBody { fees: expected }))); } #[test] fn fees_for_exchange_intermediary_asset_not_found() { let transaction_fee = 1000; let fixed = 10; let units = 2; let meta_data0 = "asset0"; let meta_data1 = "asset1"; let meta_data2 = "asset2"; let meta_data3 = "asset3"; let config_fees = TransactionFees::with_default_key(0, 0, 0, transaction_fee, 0, 0); let permissions = TransactionPermissions::default(); let (creator_pub_key, _) = crypto::gen_keypair(); let (sender_public_key, sender_secret_key) = crypto::gen_keypair(); let (recipient_public_key, recipient_secret_key) = crypto::gen_keypair(); let (intermediary_public_key, intermediary_secret_key) = crypto::gen_keypair(); let (asset0, _) = dmbc_testkit::create_asset( meta_data0, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset1, _) = dmbc_testkit::create_asset( meta_data1, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset2, _) = dmbc_testkit::create_asset( meta_data2, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let (asset3, _) = dmbc_testkit::create_asset( meta_data3, units, dmbc_testkit::asset_fees(fixed, "0.0".parse().unwrap()), &creator_pub_key, ); let testkit = DmbcTestApiBuilder::new() .with_configuration(Configuration::new(config_fees, permissions)) .create(); let api = testkit.api(); let tx_exchange_assets = transaction::Builder::new() .keypair(recipient_public_key, recipient_secret_key) .tx_exchange_with_intermediary() .sender_key_pair(sender_public_key, sender_secret_key) .intermediary_key_pair(intermediary_public_key, intermediary_secret_key) .fee_strategy(FeeStrategy::Recipient) .sender_add_asset_value(asset0) .sender_add_asset_value(asset1) .sender_add_asset_value(asset2) .recipient_add_asset_value(asset3) .build(); let (status, response) = api.post_fee(&tx_exchange_assets); assert_eq!(status, StatusCode::BadRequest); assert_eq!(response, Ok(Err(Error::AssetNotFound))); }
//! Parenchyma extension package for backend-agnostic deep neural network (NN) operations. #![allow(unused_variables)] #![feature(non_modrs_mods)] extern crate ocl; extern crate parenchyma; pub use self::extension_package::{Extension, Package}; pub mod frameworks; mod extension_package;
use std::io::{stdin, stdout, Write}; use std::str::FromStr; #[doc(hidden)] pub fn get__<F: FromStr>() -> Result<F, <F as FromStr>::Err> { let mut s = String::new(); let _ = stdout().flush(); stdin() .read_line(&mut s) .expect("user did not enter correct string"); if let Some('\n') = s.chars().next_back() { s.pop(); } if let Some('\r') = s.chars().next_back() { s.pop(); } s.parse::<F>() } #[doc(hidden)] pub fn set__<F: FromStr>(value: &mut F) { if let Ok(i) = get__::<F>() { *value = i; } } #[macro_export] macro_rules! get_input { ($generic: ty) => { $crate::get__::<$generic>() }; ($generic: ty, $($arg:tt)*) => {{ print!("{}",format_args!($($arg)*)); $crate::get__::<$generic>() }}; } #[macro_export] macro_rules! set_from_input { ($value: expr) => { $crate::set__($value) }; ($value: expr, $($arg:tt)*) => {{ print!("{}",format_args!($($arg)*)); $crate::set__($value) }}; }
use super::super::HasTable; use super::{Component, FromWorldMut, UnsafeView, World}; use crate::tables::unique_table::UniqueTable; use crate::tables::TableId; use std::ops::{Deref, DerefMut}; use std::ptr::NonNull; pub struct UnwrapViewMut<Id: TableId, C: Component<Id>>(NonNull<UniqueTable<Id, C>>); impl<'a, Id: TableId, C: Component<Id>> Clone for UnwrapViewMut<Id, C> { fn clone(&self) -> Self { UnwrapViewMut(self.0) } } impl<'a, Id: TableId, C: Component<Id>> Copy for UnwrapViewMut<Id, C> {} unsafe impl<'a, Id: TableId, C: Component<Id>> Send for UnwrapViewMut<Id, C> {} unsafe impl<'a, Id: TableId, C: Component<Id>> Sync for UnwrapViewMut<Id, C> {} impl<'a, Id: TableId, C: Component<Id>> UnwrapViewMut<Id, C> { pub fn from_table(t: &mut UniqueTable<Id, C>) -> Self { let ptr = unsafe { NonNull::new_unchecked(t) }; Self(ptr) } } impl<'a, Id: TableId, C: Component<Id>> Deref for UnwrapViewMut<Id, C> { type Target = C; fn deref(&self) -> &Self::Target { unsafe { self.0.as_ref() } .value .as_ref() .expect("UnwrapViewMut dereferenced with an empty table") } } impl<'a, Id: TableId, C: Component<Id>> DerefMut for UnwrapViewMut<Id, C> { fn deref_mut(&mut self) -> &mut Self::Target { unsafe { self.0.as_mut() } .value .as_mut() .expect("UnwrapViewMut dereferenced with an empty table") } } impl<'a, Id: TableId, C: Default + Component<Id, Table = UniqueTable<Id, C>>> FromWorldMut for UnwrapViewMut<Id, C> where crate::world::World: HasTable<Id, C>, { fn from_world_mut(w: &mut World) -> Self { let table = UnsafeView::from_world_mut(w).as_ptr(); UnwrapViewMut(NonNull::new(table).unwrap()) } }
#![doc = "generated by AutoRust 0.1.0"] #![allow(unused_mut)] #![allow(unused_variables)] #![allow(unused_imports)] use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub mod container_host_mappings { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn get_container_host_mapping( operation_config: &crate::OperationConfig, container_host_mapping: &ContainerHostMapping, subscription_id: &str, resource_group_name: &str, location: &str, ) -> std::result::Result<get_container_host_mapping::Response, get_container_host_mapping::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DevSpaces/locations/{}/checkContainerHostMapping", &operation_config.base_path, subscription_id, resource_group_name, location ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get_container_host_mapping::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(container_host_mapping); let req = req_builder.build().context(get_container_host_mapping::BuildRequestError)?; let rsp = client.execute(req).await.context(get_container_host_mapping::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get_container_host_mapping::ResponseBytesError)?; let rsp_value: ContainerHostMapping = serde_json::from_slice(&body).context(get_container_host_mapping::DeserializeError { body })?; Ok(get_container_host_mapping::Response::Ok200(rsp_value)) } StatusCode::NO_CONTENT => Ok(get_container_host_mapping::Response::NoContent204), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get_container_host_mapping::ResponseBytesError)?; let rsp_value: DevSpacesErrorResponse = serde_json::from_slice(&body).context(get_container_host_mapping::DeserializeError { body })?; get_container_host_mapping::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get_container_host_mapping { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(ContainerHostMapping), NoContent204, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::DevSpacesErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } } pub mod operations { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn list(operation_config: &crate::OperationConfig) -> std::result::Result<ResourceProviderOperationList, list::Error> { let client = &operation_config.client; let uri_str = &format!("{}/providers/Microsoft.DevSpaces/operations", &operation_config.base_path,); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ResourceProviderOperationList = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; list::UnexpectedResponse { status_code, body: body }.fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { UnexpectedResponse { status_code: StatusCode, body: bytes::Bytes }, BuildRequestError { source: reqwest::Error }, ExecuteRequestError { source: reqwest::Error }, ResponseBytesError { source: reqwest::Error }, DeserializeError { source: serde_json::Error, body: bytes::Bytes }, GetTokenError { source: azure_core::errors::AzureError }, } } } pub mod controllers { use crate::models::*; use reqwest::StatusCode; use snafu::{ResultExt, Snafu}; pub async fn get( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, name: &str, ) -> std::result::Result<Controller, get::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DevSpaces/controllers/{}", &operation_config.base_path, subscription_id, resource_group_name, name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(get::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(get::BuildRequestError)?; let rsp = client.execute(req).await.context(get::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: Controller = serde_json::from_slice(&body).context(get::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(get::ResponseBytesError)?; let rsp_value: DevSpacesErrorResponse = serde_json::from_slice(&body).context(get::DeserializeError { body })?; get::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod get { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::DevSpacesErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn create( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, name: &str, controller: &Controller, ) -> std::result::Result<create::Response, create::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DevSpaces/controllers/{}", &operation_config.base_path, subscription_id, resource_group_name, name ); let mut req_builder = client.put(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(create::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(controller); let req = req_builder.build().context(create::BuildRequestError)?; let rsp = client.execute(req).await.context(create::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Controller = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Ok200(rsp_value)) } StatusCode::CREATED => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: Controller = serde_json::from_slice(&body).context(create::DeserializeError { body })?; Ok(create::Response::Created201(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(create::ResponseBytesError)?; let rsp_value: DevSpacesErrorResponse = serde_json::from_slice(&body).context(create::DeserializeError { body })?; create::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod create { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Controller), Created201(Controller), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::DevSpacesErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn update( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, name: &str, controller_update_parameters: &ControllerUpdateParameters, ) -> std::result::Result<update::Response, update::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DevSpaces/controllers/{}", &operation_config.base_path, subscription_id, resource_group_name, name ); let mut req_builder = client.patch(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(update::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(controller_update_parameters); let req = req_builder.build().context(update::BuildRequestError)?; let rsp = client.execute(req).await.context(update::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: Controller = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Ok200(rsp_value)) } StatusCode::CREATED => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: Controller = serde_json::from_slice(&body).context(update::DeserializeError { body })?; Ok(update::Response::Created201(rsp_value)) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(update::ResponseBytesError)?; let rsp_value: DevSpacesErrorResponse = serde_json::from_slice(&body).context(update::DeserializeError { body })?; update::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod update { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200(Controller), Created201(Controller), } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::DevSpacesErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn delete( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, name: &str, ) -> std::result::Result<delete::Response, delete::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DevSpaces/controllers/{}", &operation_config.base_path, subscription_id, resource_group_name, name ); let mut req_builder = client.delete(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(delete::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(delete::BuildRequestError)?; let rsp = client.execute(req).await.context(delete::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => Ok(delete::Response::Ok200), StatusCode::ACCEPTED => Ok(delete::Response::Accepted202), StatusCode::NO_CONTENT => Ok(delete::Response::NoContent204), status_code => { let body: bytes::Bytes = rsp.bytes().await.context(delete::ResponseBytesError)?; let rsp_value: DevSpacesErrorResponse = serde_json::from_slice(&body).context(delete::DeserializeError { body })?; delete::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod delete { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug)] pub enum Response { Ok200, Accepted202, NoContent204, } #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::DevSpacesErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_by_resource_group( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, ) -> std::result::Result<ControllerList, list_by_resource_group::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DevSpaces/controllers", &operation_config.base_path, subscription_id, resource_group_name ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_by_resource_group::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list_by_resource_group::BuildRequestError)?; let rsp = client.execute(req).await.context(list_by_resource_group::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?; let rsp_value: ControllerList = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_by_resource_group::ResponseBytesError)?; let rsp_value: DevSpacesErrorResponse = serde_json::from_slice(&body).context(list_by_resource_group::DeserializeError { body })?; list_by_resource_group::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_by_resource_group { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::DevSpacesErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list( operation_config: &crate::OperationConfig, subscription_id: &str, ) -> std::result::Result<ControllerList, list::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/providers/Microsoft.DevSpaces/controllers", &operation_config.base_path, subscription_id ); let mut req_builder = client.get(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); let req = req_builder.build().context(list::BuildRequestError)?; let rsp = client.execute(req).await.context(list::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: ControllerList = serde_json::from_slice(&body).context(list::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list::ResponseBytesError)?; let rsp_value: DevSpacesErrorResponse = serde_json::from_slice(&body).context(list::DeserializeError { body })?; list::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::DevSpacesErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } pub async fn list_connection_details( operation_config: &crate::OperationConfig, subscription_id: &str, resource_group_name: &str, name: &str, list_connection_details_parameters: &ListConnectionDetailsParameters, ) -> std::result::Result<ControllerConnectionDetailsList, list_connection_details::Error> { let client = &operation_config.client; let uri_str = &format!( "{}/subscriptions/{}/resourceGroups/{}/providers/Microsoft.DevSpaces/controllers/{}/listConnectionDetails", &operation_config.base_path, subscription_id, resource_group_name, name ); let mut req_builder = client.post(uri_str); if let Some(token_credential) = &operation_config.token_credential { let token_response = token_credential .get_token(&operation_config.token_credential_resource) .await .context(list_connection_details::GetTokenError)?; req_builder = req_builder.bearer_auth(token_response.token.secret()); } req_builder = req_builder.query(&[("api-version", &operation_config.api_version)]); req_builder = req_builder.json(list_connection_details_parameters); let req = req_builder.build().context(list_connection_details::BuildRequestError)?; let rsp = client.execute(req).await.context(list_connection_details::ExecuteRequestError)?; match rsp.status() { StatusCode::OK => { let body: bytes::Bytes = rsp.bytes().await.context(list_connection_details::ResponseBytesError)?; let rsp_value: ControllerConnectionDetailsList = serde_json::from_slice(&body).context(list_connection_details::DeserializeError { body })?; Ok(rsp_value) } status_code => { let body: bytes::Bytes = rsp.bytes().await.context(list_connection_details::ResponseBytesError)?; let rsp_value: DevSpacesErrorResponse = serde_json::from_slice(&body).context(list_connection_details::DeserializeError { body })?; list_connection_details::DefaultResponse { status_code, value: rsp_value, } .fail() } } } pub mod list_connection_details { use crate::{models, models::*}; use reqwest::StatusCode; use snafu::Snafu; #[derive(Debug, Snafu)] #[snafu(visibility(pub(crate)))] pub enum Error { DefaultResponse { status_code: StatusCode, value: models::DevSpacesErrorResponse, }, BuildRequestError { source: reqwest::Error, }, ExecuteRequestError { source: reqwest::Error, }, ResponseBytesError { source: reqwest::Error, }, DeserializeError { source: serde_json::Error, body: bytes::Bytes, }, GetTokenError { source: azure_core::errors::AzureError, }, } } }
use std::os::raw::c_char; use std::io::{Error, ErrorKind}; use libc::O_NOATIME; redhook::hook! { unsafe fn open64( path: *const c_char, flags: i32, mode: i32 ) -> i32 => fileopen64 { let ret = redhook::real!(open64)( path, flags | O_NOATIME, mode ); if ret < 0 && Error::last_os_error().kind() == ErrorKind::PermissionDenied { redhook::real!(open64)(path, flags, mode) } else { ret } } } redhook::hook! { unsafe fn open( path: *const c_char, flags: i32, mode: i32 ) -> i32 => fileopen { let ret = redhook::real!(open)( path, flags | O_NOATIME, mode ); if ret < 0 && Error::last_os_error().kind() == ErrorKind::PermissionDenied { redhook::real!(open)(path, flags, mode) } else { ret } } } redhook::hook! { unsafe fn __open64_2( path: *const c_char, flags: i32 ) -> i32 => fileopen64_2 { let ret = redhook::real!(__open64_2)( path, flags | O_NOATIME ); if ret < 0 && Error::last_os_error().kind() == ErrorKind::PermissionDenied { redhook::real!(__open64_2)(path, flags) } else { ret } } }
use std::ops::Add; #[derive(Debug)] struct Point { x: i32, y: i32, } impl Add for Point { type Output = Point; fn add (self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y } } } fn main() { let p1 = Point { x: 1, y:0 }; let p2 = Point { x: 1, y:3 }; let p3 = p1+p2; println!("{:?}", p3); }
#![doc(html_root_url = "https://docs.rs/thetvdb/0.1.0-beta.2")] #![deny(missing_docs, missing_debug_implementations, unsafe_code)] //! This crate provides an async [client] as well as helpful types to request //! and interact with data from **TheTVDB API v3**. //! //! You will need a valid API key to create a new client. //! To generate a key log in and go to the [API Keys page]. //! //! # Examples //! Search for a series by name: //! ```no_run //! # use thetvdb::error::Result; //! use thetvdb::{Client, params::SearchBy}; //! //! # #[tokio::main] //! # async fn main() -> Result<()> { //! let client = Client::new("YOUR_API_KEY").await?; //! //! let results = client.search(SearchBy::Name("Planet Earth")).await?; //! //! println!("{:#?}", results); //! # Ok(()) } //! ``` //! Get a series by ID: //! ```no_run //! # use thetvdb::error::Result; //! # use thetvdb::Client; //! # //! # #[tokio::main] //! # async fn main() -> Result<()> { //! # let client = Client::new("KEY").await?; //! let series = client.series(318408).await?; //! //! assert_eq!( //! series.series_name, //! Some("Planet Earth II".to_string()) //! ); //! # Ok(()) } //! ``` //! Use a custom struct to deserialize the API response: //! ```no_run //! # use thetvdb::error::Result; //! # use thetvdb::Client; //! use serde::Deserialize; //! # //! # #[tokio::main] //! # async fn main() -> Result<()> { //! # let client = Client::new("KEY").await?; //! //! #[derive(Deserialize)] //! struct MySeries { //! #[serde(rename = "seriesName")] //! name: String, //! overview: Option<String>, //! season: String, //! banner: Option<String>, //! genre: Vec<String>, //! } //! //! let series: MySeries = client.series_into(318408).await?; //! # Ok(()) } //! ``` //! //! For more examples check [`Client`][client]. //! //! [client]: ./client/struct.Client.html //! [API Keys page]: https://thetvdb.com/dashboard/account/apikeys mod serialization; mod urls; pub mod client; pub mod error; pub mod language; pub mod params; pub mod response; #[doc(inline)] pub use client::Client; #[doc(inline)] pub use error::{Error, Result}; #[cfg(test)] mod test_util { use chrono::{DateTime, TimeZone, Utc}; use crate::error::Error; pub fn now_round_seconds() -> DateTime<Utc> { Utc.timestamp(Utc::now().timestamp(), 0) } pub fn wrong_error_kind(expected: Error, got: Error) { panic!("Wrong error kind: expected {:?}, got {:?}", expected, got); } }
use std::cell::RefCell; use std::cmp::{max, Ordering}; use std::rc::Rc; use std::fmt::Display; pub struct Node<T> { key: T, left: Link<T>, right: Link<T>, height: i32, } pub type Link<T> = Option<Rc<RefCell<Node<T>>>>; pub struct AVLTree<T> { root: Link<T>, } impl<T> Node<T> { fn new(key: T) -> Link<T> { Some(Rc::new(RefCell::new(Node { key: key, left: None, right: None, height: 1, }))) } } impl<T: Ord> AVLTree<T> { pub fn new() -> Self { AVLTree { root: None } } fn add_inner(mut root: Link<T>, key: T) -> Link<T> { match root.take() { Some(node) => { { let mut x = node.borrow_mut(); match key.cmp(&x.key) { Ordering::Less => { x.left = Self::add_inner(x.left.take(), key) }, Ordering::Greater => x.right = Self::add_inner(x.right.take(), key), _ => return None } x.height = std::cmp::max(Self::tree_height(&x.left), Self::tree_height(&x.right)) + 1; } Self::balance(Some(node)) } None => { Node::new(key) } } } fn rotate_left(mut root: Link<T>) -> Link<T> { root.take().map(|x| { let rch = x.borrow_mut().right.take().unwrap(); let rchlch = rch.borrow_mut().left.take(); { let mut x = x.borrow_mut(); x.right = rchlch; x.height = max(Self::tree_height(&x.left), Self::tree_height(&x.right)) + 1; } { let mut y = rch.borrow_mut(); y.left = Some(x); y.height = max(Self::tree_height(&y.left), Self::tree_height(&y.right) + 1); } rch }) } fn rotate_right(mut root: Link<T>) -> Link<T> { root.take().map(|x| { let lch = { x.borrow_mut().left.take().unwrap() }; let lchrch = { lch.borrow_mut().right.take() }; { let mut x = x.borrow_mut(); x.left = lchrch; x.height = max(Self::tree_height(&x.left), Self::tree_height(&x.right)) + 1; } { let mut y = lch.borrow_mut(); y.right = Some(x); y.height = max(Self::tree_height(&y.left), Self::tree_height(&y.right) + 1); } lch }) } fn tree_height(node: &Link<T>) -> i32 { node.as_ref().map_or(0, |x| x.borrow().height) } fn balance_factor(node: &Link<T>) -> i32 { node.as_ref().map_or(0, |x| { let x = x.borrow(); Self::tree_height(&x.left) - Self::tree_height(&x.right) }) } fn balance(root: Link<T>) -> Link<T> { let bf = Self::balance_factor(&root); if bf >= -1 && bf <= 1 { return root; } if let Some(x) = root { match bf { -2 => { let sub_bf = Self::balance_factor(&x.borrow().right); if sub_bf > 0 { let mut x = x.borrow_mut(); x.right = Self::rotate_right(x.right.take()); } Self::rotate_left(Some(x)) } 2 => { let sub_bf = Self::balance_factor(&x.borrow().left); if sub_bf < 0 { let mut x = x.borrow_mut(); x.left = Self::rotate_left(x.left.take()); } Self::rotate_right(Some(x)) } _ => unreachable!(), } } else { None } } pub fn add(&mut self, key: T) { self.root = Self::add_inner(self.root.take(), key) } fn find(root: &Link<T>, key: T) -> Link<T> { root.as_ref().and_then(|node| { let x = node.borrow(); if key.lt(&x.key) { Self::find(&x.left, key) } else if x.key.lt(&key) { Self::find(&x.right, key) } else { Some(node.clone()) } }) } pub fn contains(&self, key: T) -> bool { Self::find(&self.root, key).is_some() } fn is_balanced(root: &Link<T>) -> bool { match root { Some(x) => { let x = x.borrow(); let lh = Self::tree_height(&x.left); let rh = Self::tree_height(&x.right); let lch_ok = Self::is_balanced(&x.left); let rch_ok = Self::is_balanced(&x.right); // println!("{} {} {} {} {}", lch_ok, rch_ok, x.height, lh, rh); lch_ok && rch_ok && x.height == max(lh, rh) + 1 && lh - rh <= 1 && lh - rh >= -1 } None => true } } } impl<T: Display> AVLTree<T> { pub fn traverse_inner(node: &Link<T>) { node.as_ref().map(|x| { Self::traverse_inner(&x.borrow().left); println!("=>{}", x.borrow().key); Self::traverse_inner(&x.borrow().right); }); } pub fn traverse(&self) { Self::traverse_inner(&self.root); } } #[cfg(test)] mod test { use crate::avltree::AVLTree; #[test] fn basics() { let mut t = AVLTree::new(); t.add(1); assert_eq!(AVLTree::is_balanced(&t.root), true); t.add(5); assert_eq!(AVLTree::is_balanced(&t.root), true); t.add(3); assert_eq!(AVLTree::is_balanced(&t.root), true); t.add(2); assert_eq!(AVLTree::is_balanced(&t.root), true); t.add(4); assert_eq!(AVLTree::is_balanced(&t.root), true); assert_eq!(t.contains(1), true); assert_eq!(t.contains(2), true); assert_eq!(t.contains(3), true); assert_eq!(t.contains(4), true); assert_eq!(t.contains(5), true); assert_eq!(t.contains(6), false); assert_eq!(t.contains(0), false); } }
fn main() -> Result<(), Box<dyn std::error::Error>> { let chap2_iface_files = &["api/v1/protos/product_info.proto"]; let dirs = &["."]; // Chapter 2: Unary gRPC Pattern tonic_build::configure() .compile(chap2_iface_files, dirs) .unwrap(); // Chapter 3: gRPC Communication Patterns let chap3_iface_files = &["api/v2/protos/order_mgmt.proto"]; tonic_build::configure() .compile(chap3_iface_files, dirs) .unwrap(); Ok(()) }
use ignore::Walk; use std::fs::metadata; use trigram::find_words_iter; use std::fs::File; use std::io::{prelude::*, BufReader}; fn main() { let args: Vec<String> = std::env::args().collect(); if args.len() != 1+1 { eprintln!("Usage: ff pattern This will search for pattern in files in the current directory tree not excluded by .gitignore. "); std::process::exit(1); } let pattern = &args[1]; for result in Walk::new("./") { match result { Ok(entry) => { let path: &str = entry.path().to_str().unwrap(); let md = metadata(path).unwrap(); if md.is_file() { search_file(&pattern, path) } } Err(err) => eprintln!("ERROR: {}", err), } } } fn search_file(pattern: &str, path: &str) { let file = File::open(path).unwrap(); let reader = BufReader::new(file); let mut line_num = 0; for line in reader.lines() { line_num += 1; match line { Ok(line) => { for w in find_words_iter(pattern, &line, 0.45) { println!("{}:{}: {}", path, line_num, w.as_str()); } }, Err(e) => { eprintln!("{}", e); } } } }
use exonum::crypto::{Hash, PublicKey}; use super::proto; /// Wallet information stored in the database. #[derive(Clone, Debug, ProtobufConvert)] #[exonum(pb = "proto::User", serde_pb_convert)] pub struct User { /// `PublicKey` of the user. pub key: PublicKey, /// Name of the user. pub name: String, } impl User { /// Create new user. pub fn new( &key: &PublicKey, name: &String, ) -> Self { Self { key, name: name.to_owned(), } } }
use std::io::Cursor; use rodio::{Decoder, Sink}; use audio::{DecoderError, Source}; use audio::output::Output; /// This structure provides a way to programmatically pick and play music. pub struct Dj { sink: Sink, pub(crate) picker: Option<Box<FnMut(&mut Dj) -> bool + Send + Sync>>, } impl Dj { /// Creates a new Dj using the given audio output. pub fn new(output: &Output) -> Dj { Dj { sink: Sink::new(&output.endpoint), picker: None, } } /// A Dj's picker will be called by the DjSystem whenever the Dj runs out of music to play. /// /// Only the Dj added to the world's resources with resource ID 0 will have their picker called. /// /// During callback the picker is separated from the Dj in order to avoid multiple aliasing. /// After the callback is complete, if the picker returned true it will be reattached. pub fn set_picker(&mut self, picker: Box<FnMut(&mut Dj) -> bool + Send + Sync>) { self.picker = Some(picker); } /// Clears the previously set picker. pub fn clear_picker(&mut self) { self.picker = None; } /// Adds a source to the Dj's queue of music to play. pub fn append(&self, source: &Source) -> Result<(), DecoderError> { self.sink.append(Decoder::new(Cursor::new(source.clone())) .map_err(|_| DecoderError)?); Ok(()) } /// Returns true if the Dj has no more music to play. pub fn empty(&self) -> bool { self.sink.empty() } /// Retrieves the volume of the Dj, between 0.0 and 1.0; pub fn volume(&self) -> f32 { self.sink.volume() } /// Sets the volume of the Dj. pub fn set_volume(&mut self, volume: f32) { self.sink.set_volume(volume); } /// Resumes playback of a paused Dj. Has no effect if this Dj was never paused. pub fn play(&self) { self.sink.play(); } /// Pauses playback, this can be resumed with `Dj::play` pub fn pause(&self) { self.sink.pause() } /// Returns true if the Dj is currently paused. pub fn is_paused(&self) -> bool { self.sink.is_paused() } /// Empties the Dj's queue of all music. pub fn stop(&self) { self.sink.stop(); } }
use std::collections::HashMap; // struct that holds info for the columns in the parsed file #[derive(Debug, Clone)] pub struct CsvRows { pub date: String, pub time: String, pub info: HashMap<String, String> }
fn if_let_pattern_test() { let tmp_str = String::from("red"); let fav_color: Option<&str> = Some(&tmp_str); // let fav_color: Option<&str> = None; let is_tuesday = true; let age: Result<u8, _> = "34".parse(); if let Some(color) = fav_color { println!("Using your favorite color, {}, as the background", color); } else if is_tuesday { println!("Tuesday is green day!"); } else if let Ok(age) = age { if age > 30 { println!("Using purple has the background color"); } else { println!("Using orange has the background color"); } } else { println!("Using blue has the background color"); } } fn while_let_pattern_test() { let mut stack = Vec::new(); stack.push(1); stack.push(2); stack.push(3); while let Some(top) = stack.pop() { println!("{}", top); } } fn for_loop_pattern_test() { let v = vec!['a', 'b', 'c']; for (index, val) in v.iter().enumerate() { println!("{} is at index {}", val, index); } } fn let_destruction_pattern_test() { let x = 5; println!("x is {}", x); let (a, b, c) = (1, 2, 3); println!("a,b,c = ({},{},{})", a, b, c); let point = (3, 5); print_coordinates(&point); } fn print_coordinates(&(x, y): &(i32, i32)) { println!("current pos is ({}, {})", x, y); } fn refutable_irrefutable_test() { // let Some(x) = some_option_value; if let x = 5 { println!("{}", x); } } fn pattern_syntax_test() { // match literials let x = 8; match x { 1 => println!("one"), 2 => println!("two"), 3 => println!("three"), 4 | 5 => println!("four or five"), 6..=10 => println!("six to ten"), _ => println!("anything"), } let w = 'c'; match w { 'a'..='j' => println!("early ASCII letter"), 'k'..='z' => println!("late ASCII letter"), _ => println!("something else"), } // match named varibles let y = Some(5); let z = 10; match y { Some(50) => println!("Got 50"), Some(z) => println!("Matched, z = {:?}", z), _ => println!("Default case, y = {:?}", y), } println!("at the end: y = {:?}, z = {:?}", y, z); // destructing to break apart values struct Point { x: i32, y: i32, } let p = Point { x: 0, y: 7 }; let Point { x: a, y: b } = p; let Point { x, y } = p; println!("breaking apart from Point and a = {}, b = {}", a, b); println!("breaking apart from Point and x = {}, y = {}", x, y); match p { Point { x, y: 0 } => println!("On the x axis at {}", x), Point { x: 0, y } => println!("On the y axis at {}", y), Point { x, y } => println!("On neither axis at ({}, {})", x, y), } enum_test(); // destructuring mix structs and tuples let ((feet, inches), Point { x, y }) = ((2, 10), Point { x: 3, y: 5 }); println!( "feet is {}, inches is {}, point is ({}, {})", feet, inches, x, y ); foo(3, 4); // let mut v_1 = Some(5); let mut v_1 = None; let v_2 = Some(10); match (v_1, v_2) { (Some(_), Some(_)) => { println!("can not override an existing customized value"); } _ => { v_1 = v_2; } } println!("v1 is {:?}", v_1); let numbers = (2, 4, 6, 8, 10); match numbers { (first, _, third, _, fifth) => { println!("Some numbers: {}, {}, {}", first, third, fifth); } } match numbers { (first, .., last) => { println!("Some numbers in first and last is : {}, {}", first, last); } } // difference bt '_' and '_variant' (bind or not bind) let ss = Some(String::from("hello")); let ss2 = Some(String::from("hello")); if let Some(_s) = ss { println!("found a string {}", _s); } if let Some(_) = ss2 { println!("found a string"); } // println!("ss = {:?}", ss); moved to _s and will compile failed println!("ss2 = {:?}", ss2); // _ not moved and binded to _ // ignore remaining parts of a value with .. struct MyPoint { x: i32, y: i32, z: i32, } let origin = MyPoint { x: 10, y: 0, z: 0 }; match origin { MyPoint { x, .. } => println!("my point matched x is {}", x), } // match guards // let num = Some(4); let num = Some(8); match num { Some(x) if x < 5 => println!("less than five {}", x), Some(x) => println!("{}", x), None => (), } match_guard_with_outer_var(); // binding test enum MyMessage { Hello { id: i32 }, } let my_msg = MyMessage::Hello { id: 5 }; match my_msg { MyMessage::Hello { id: id_var @ 3..=7 } => println!("Found an id in range: {}", id_var), MyMessage::Hello { id: 10..=12 } => println!("Found an id in another range"), MyMessage::Hello { id } => println!("Found some other id in range {}", id), } } fn match_guard_with_outer_var() { // let x = Some(5); let x = Some(10); let y = 10; match x { Some(50) => println!("Got 50"), Some(n) if n == y => println!("Matched, n = {}", n), // y is outer var not new in match scope _ => println!("Default case, x = {:?}", x), } let xx = 4; let yy = false; match xx { 4 | 5 | 6 if yy => { println!("matched yes"); } _ => { println!("matched no"); } } } fn foo(_: i32, y: i32) { println!("y parameter is {}, and x is arbitrary", y); } // destruction nested enums enum Color { Rgb(i32, i32, i32), Hsv(i32, i32, i32), } enum Message { Quit, Move { x: i32, y: i32 }, Write(String), ChangeColor(Color), } fn enum_test() { // let msg = Message::ChangeColor(0, 160, 255); let msg = Message::ChangeColor(Color::Rgb(0, 160, 255)); // let msg = Message::Quit; // let msg = Message::Move(10, 20); // let msg = Message::Write("hello rust"); match msg { Message::Quit => println!("The Quit variant has no data to destructure."), Message::Move { x, y } => println!("Move in the {} x direction and {} y direction", x, y), Message::Write(text) => println!("Text message {}", text), Message::ChangeColor(Color::Rgb(r, g, b)) => { println!("Change the rgb color to red {}, green {}, blue {}", r, g, b) } Message::ChangeColor(Color::Hsv(h, s, v)) => { println!("Change the hsv color to h {}, s {}, v {}", h, s, v) } } } fn main() { if_let_pattern_test(); while_let_pattern_test(); for_loop_pattern_test(); let_destruction_pattern_test(); pattern_syntax_test(); }
use cryptanalysis::english; use bitwise::bitwiseops; use bitwise::hex_rep::ToHexRep; use challengeinfo::challenge::{Challenge, ChallengeInfo}; use std::io::{BufRead, BufReader}; use std::fs::File; use num_rational::Ratio; pub const FILE: &'static str = "data/set1/ex4.txt"; pub const INFO4: ChallengeInfo<'static> = ChallengeInfo { set_number: 4, challenge_number: 4, title: "Detect single-character XOR", description: "", url: "http://cryptopals.com/sets/1/challenges/4", }; pub const CHALLENGE4: Challenge<'static> = Challenge { info: INFO4, func: execute, }; fn execute() -> String { let expected_plaintext = Vec::from("Now that the party is jumping\n"); let handle = File::open(FILE).unwrap(); let reader = BufReader::new(handle); let mut best_score = Ratio::from_integer(0); let mut best_ciphertext: Vec<u8> = Vec::new(); let mut best_char = 0x00; for line in reader.lines() { let line = line.unwrap(); let possible_ciphertext = line.to_hex().unwrap(); let possible_char = english::most_likely_byte(&possible_ciphertext); let possible_plaintext = bitwiseops::xor_with_char(possible_char, possible_ciphertext.as_ref()); let score = english::score(&possible_plaintext); if score >= best_score { best_score = score; best_ciphertext = possible_ciphertext; best_char = possible_char; } } let best_plaintext = bitwiseops::xor_with_char(best_char, best_ciphertext.as_ref()); assert_eq!(expected_plaintext.len(), best_plaintext.len()); assert_eq!(expected_plaintext, best_plaintext); String::from_utf8(best_plaintext).unwrap() }
extern crate diesel; use rocket::State; use rocket_contrib::json::Json; use crate::auth::crypto_auth; use crate::db::models::*; use crate::db::user; use crate::db::auth_info; pub fn create_signup(database_url: State<String>, create_info: Json<CreateInfo>) -> Result<CreateResult, &str> { let user_to_insert: User = User { email: create_info.email.clone(), dob: create_info.dob.clone(), kyc_level: 0 }; let user = user::fetch_user_by_email(&database_url, &user_to_insert.email); match user { None => { let user_entity = user::insert_user(&database_url, user_to_insert); let password_hash = crypto_auth::hash_password(&create_info.password); let auth_info: AuthInfo = AuthInfo { user_id: user_entity.id, password_hash: password_hash, mfa_enabled: false, }; let auth_info_entity = auth_info::insert_auth_info(&database_url, auth_info); Ok(CreateResult { uid: user_entity.id, auth_id: auth_info_entity.id }) }, Some(_user) => Err("User already exists") } }
pub mod textures;
use super::{ filters::{AudioFilter, VideoFilter}, graph, }; use crate::{source::Decoder, Result}; use stainless_ffmpeg::{ audio_decoder::AudioDecoder, format_context::FormatContext, video_decoder::VideoDecoder, }; use std::sync::{Arc, Mutex}; #[derive(Debug, PartialEq)] pub struct StreamDescriptor { pub index: usize, descriptor: Descriptor, } impl StreamDescriptor { pub fn new_audio(index: usize, filters: Vec<AudioFilter>) -> Self { StreamDescriptor { index, descriptor: filters.into(), } } pub fn new_video(index: usize, filters: Vec<VideoFilter>) -> Self { StreamDescriptor { index, descriptor: filters.into(), } } pub fn new_data(index: usize) -> Self { let descriptor = Descriptor::DataDescriptor; StreamDescriptor { index, descriptor } } pub fn build_decoder(&self, format_context: Arc<Mutex<FormatContext>>) -> Result<Decoder> { match &self.descriptor { Descriptor::AudioDescriptor(audio_descriptor) => { // AudioDecoder can decode any codec, not only video let audio_decoder = AudioDecoder::new( format!("decoder_{}", self.index), &format_context.lock().unwrap(), self.index as isize, )?; let audio_graph = graph::build_audio_filter_graph(&audio_descriptor.filters, &audio_decoder)?; Ok(Decoder::new_audio_decoder(audio_decoder, audio_graph)) } Descriptor::ImageDescriptor(video_descriptor) => { // VideoDecoder can decode any codec, not only video let video_decoder = VideoDecoder::new( format!("decoder_{}", self.index), &format_context.lock().unwrap(), self.index as isize, )?; let video_graph = graph::build_video_filter_graph(&video_descriptor.filters, &video_decoder)?; Ok(Decoder::new_video_decoder(video_decoder, video_graph)) } _ => unimplemented!(), } } } #[derive(Debug, PartialEq)] pub enum Descriptor { AudioDescriptor(AudioDescriptor), ImageDescriptor(ImageDescriptor), DataDescriptor, } impl From<Vec<AudioFilter>> for Descriptor { fn from(filters: Vec<AudioFilter>) -> Self { let audio_descriptor = AudioDescriptor { filters }; Descriptor::AudioDescriptor(audio_descriptor) } } impl From<Vec<VideoFilter>> for Descriptor { fn from(filters: Vec<VideoFilter>) -> Self { let image_descriptor = ImageDescriptor { filters }; Descriptor::ImageDescriptor(image_descriptor) } } #[derive(Debug, PartialEq)] pub struct AudioDescriptor { filters: Vec<AudioFilter>, } #[derive(Debug, PartialEq)] pub struct ImageDescriptor { filters: Vec<VideoFilter>, }
use std::io::{Write, Read}; #[derive(Debug)] struct TempDir(std::path::PathBuf, std::process::Child); impl TempDir { fn new<P: AsRef<std::path::Path>> (p: P) -> TempDir { let here = std::env::current_dir().unwrap(); let p = here.join(p); println!("remove test repository"); std::fs::remove_dir_all(&p).ok(); println!("create {:?}", &p); assert!(std::fs::create_dir_all(&p.join("data")).is_ok()); assert!(std::fs::create_dir_all(&p.join("mnt")).is_ok()); println!("current_dir = {:?}", &p); let e = location_of_executables().join("raftfs"); println!("executable = {:?}", &e); // Now run raftfs to mount us let s = std::process::Command::new(e) .args(&["data", "mnt"]) .current_dir(&p).spawn(); if !s.is_ok() { println!("Bad news: {:?}", s); } std::thread::sleep(std::time::Duration::from_secs(1)); TempDir(std::path::PathBuf::from(&p), s.unwrap()) } fn path(&self, p: &str) -> std::path::PathBuf { self.0.join(p) } } impl Drop for TempDir { fn drop(&mut self) { self.1.kill().ok(); } } fn location_of_executables() -> std::path::PathBuf { // The key here is that this test executable is located in almost // the same place as the built `fac` is located. let mut path = std::env::current_exe().unwrap(); path.pop(); // chop off exe name path.pop(); // chop off "deps" path } macro_rules! test_case { (fn $testname:ident($t:ident) $body:block) => { mod $testname { use super::*; #[test] fn $testname() { let path = std::path::PathBuf::from( format!("tmp/{}", module_path!())); { let $t = TempDir::new(&path); $body; } std::thread::sleep(std::time::Duration::from_secs(1)); // Remove temporary directory (we did not panic!), but // ignore errors that might happen on windows. std::fs::remove_dir_all(&path).ok(); } } } } test_case!{ fn nothing(t) { println!("Testing: {:?}", t); } } test_case!{ fn read_empty_directory(t) { for entry in std::fs::read_dir(t.path("mnt")).unwrap() { let entry = entry.unwrap(); let path = entry.path(); println!("entry: {:?}", &path); assert!(false); } } } test_case!{ fn file_write_read(t) { let contents = b"hello\n"; { let mut f = std::fs::File::create(t.path("mnt/testfile")).unwrap(); f.write(contents).unwrap(); } { let mut f = std::fs::File::open(t.path("mnt/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } { println!("verify that the file actually got stored in data"); let mut f = std::fs::File::open(t.path("data/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } } } test_case!{ fn file_write_read_snapshot(t) { let contents = b"hello\n"; { let mut f = std::fs::File::create(t.path("mnt/testfile")).unwrap(); f.write(contents).unwrap(); } { let mut f = std::fs::File::open(t.path("mnt/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } println!("creating .snapshots"); std::fs::create_dir_all(t.path("mnt/.snapshots/snap")).unwrap(); println!("done creating .snapshots/snap"); { println!("verify that the file actually got stored in data"); let mut f = std::fs::File::open(t.path("data/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } { println!("verify that the file can be read from the snapshot."); let mut f = std::fs::File::open(t.path("mnt/.snapshots/snap/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } } } test_case!{ fn file_rename(t) { let contents = b"hello\n"; { let mut f = std::fs::File::create(t.path("mnt/testfile")).unwrap(); f.write(contents).unwrap(); } assert!(std::fs::File::open(t.path("mnt/testfile")).is_ok()); assert!(std::fs::File::open(t.path("mnt/newname")).is_err()); std::fs::rename(t.path("mnt/testfile"), t.path("mnt/newname")).unwrap(); assert!(std::fs::File::open(t.path("mnt/testfile")).is_err()); assert!(std::fs::File::open(t.path("data/testfile")).is_err()); assert!(std::fs::File::open(t.path("mnt/newname")).is_ok()); assert!(std::fs::File::open(t.path("data/newname")).is_ok()); { let mut f = std::fs::File::open(t.path("mnt/newname")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } { println!("verify that the file actually got stored in data"); let mut f = std::fs::File::open(t.path("data/newname")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } } } test_case!{ fn file_rename_in_snapshot(t) { let contents = b"hello\n"; { let mut f = std::fs::File::create(t.path("mnt/testfile")).unwrap(); f.write(contents).unwrap(); } { let mut f = std::fs::File::open(t.path("mnt/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } println!("creating .snapshots"); std::fs::create_dir_all(t.path("mnt/.snapshots/snap")).unwrap(); println!("done creating .snapshots/snap"); { println!("verify that the file actually got stored in data"); let mut f = std::fs::File::open(t.path("data/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } { println!("verify that the file can be read from the snapshot."); let mut f = std::fs::File::open(t.path("mnt/.snapshots/snap/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } let e = std::fs::rename(t.path("mnt/.snapshots/snap/testfile"), t.path("mnt/.snapshots/snap/newname")); println!("rename gives: {:?}", &e); assert!(e.is_err()); } } test_case!{ fn file_readdir_of_snapshot(t) { let contents = b"hello\n"; { let mut f = std::fs::File::create(t.path("mnt/testfile")).unwrap(); f.write(contents).unwrap(); } { let mut f = std::fs::File::open(t.path("mnt/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } println!("creating .snapshots"); std::fs::create_dir_all(t.path("mnt/.snapshots/snap")).unwrap(); println!("done creating .snapshots/snap"); { println!("verify that the file actually got stored in data"); let mut f = std::fs::File::open(t.path("data/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } { println!("verify that the file can be read from the snapshot."); let mut f = std::fs::File::open(t.path("mnt/.snapshots/snap/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } assert!(!t.path("data/.snapshots/snap/testfile").exists()); let mut visited = std::collections::HashSet::new(); for entry in std::fs::read_dir(t.path("mnt/.snapshots/snap")).unwrap() { let entry = entry.unwrap(); let path = entry.file_name(); println!("path: {:?}", path); visited.insert(std::path::PathBuf::from(path)); } assert!(visited.contains(std::path::Path::new("testfile"))); } } test_case!{ fn file_rename_snapshot(t) { let contents = b"hello\n"; { let mut f = std::fs::File::create(t.path("mnt/testfile")).unwrap(); f.write(contents).unwrap(); } { let mut f = std::fs::File::open(t.path("mnt/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } println!("creating .snapshots"); std::fs::create_dir_all(t.path("mnt/.snapshots/snap")).unwrap(); println!("done creating .snapshots/snap"); { println!("verify that the file actually got stored in data"); let mut f = std::fs::File::open(t.path("data/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } { println!("verify that the file can be read from the snapshot."); let mut f = std::fs::File::open(t.path("mnt/.snapshots/snap/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } std::fs::rename(t.path("mnt/testfile"), t.path("mnt/newname")).unwrap(); assert!(t.path("mnt/.snapshots/snap/testfile").exists()); assert!(!t.path("mnt/.snapshots/snap/newname").exists()); assert!(std::fs::File::open(t.path("mnt/testfile")).is_err()); assert!(std::fs::File::open(t.path("data/testfile")).is_err()); assert!(std::fs::File::open(t.path("mnt/.snapshots/snap/testfile")).is_ok()); assert!(std::fs::File::open(t.path("mnt/newname")).is_ok()); assert!(std::fs::File::open(t.path("data/newname")).is_ok()); assert!(std::fs::File::open(t.path("mnt/.snapshots/snap/newname")).is_err()); { let mut f = std::fs::File::open(t.path("mnt/newname")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } { println!("verify that the file actually got stored in data"); let mut f = std::fs::File::open(t.path("data/newname")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } } } test_case!{ fn file_directory_in_snapshot(t) { std::fs::create_dir(t.path("mnt/testdir")).unwrap(); assert!(t.path("mnt/testdir").is_dir()); println!("creating .snapshots"); std::fs::create_dir_all(t.path("mnt/.snapshots/snap")).unwrap(); println!("done creating .snapshots/snap"); assert!(t.path("mnt/.snapshots/snap/testdir").is_dir()); } } test_case!{ fn rmdir_in_snapshot(t) { std::fs::create_dir(t.path("mnt/testdir")).unwrap(); assert!(t.path("mnt/testdir").is_dir()); assert!(t.path("data/testdir").is_dir()); assert!(!t.path("mnt/.snapshots/snap/testdir").is_dir()); println!("creating .snapshots"); std::fs::create_dir_all(t.path("mnt/.snapshots/snap")).unwrap(); println!("done creating .snapshots/snap"); assert!(t.path("mnt/.snapshots/snap/testdir").is_dir()); assert!(t.path("data/testdir").is_dir()); assert!(t.path("mnt/.snapshots/snap/testdir").is_dir()); assert!(!t.path("data/.snapshots/snap/testdir").is_dir()); std::fs::remove_dir(t.path("mnt/testdir")).unwrap(); assert!(!t.path("mnt/testdir").is_dir()); assert!(!t.path("data/testdir").is_dir()); assert!(t.path("mnt/.snapshots/snap/testdir").is_dir()); } } test_case!{ fn file_mkdir_after_snapshot(t) { println!("creating .snapshots"); std::fs::create_dir_all(t.path("mnt/.snapshots/snap")).unwrap(); println!("done creating .snapshots/snap"); assert!(!t.path("mnt/testdir").is_dir()); assert!(!t.path("data/testdir").is_dir()); assert!(!t.path("mnt/.snapshots/snap/testdir").is_dir()); assert!(!t.path("data/.snapshots/snap/testdir").is_dir()); std::fs::create_dir(t.path("mnt/testdir")).unwrap(); assert!(t.path("mnt/testdir").is_dir()); assert!(t.path("data/testdir").is_dir()); assert!(!t.path("data/.snapshots/snap/testdir").is_dir()); assert!(!t.path("mnt/.snapshots/snap/testdir").is_dir()); } } test_case!{ fn mkdir_in_snapshot(t) { std::fs::create_dir_all(t.path("mnt/subdir")).unwrap(); println!("creating .snapshots"); std::fs::create_dir_all(t.path("mnt/.snapshots/snap")).unwrap(); println!("done creating .snapshots/snap"); assert!(t.path("mnt/subdir").is_dir()); assert!(t.path("mnt/.snapshots/snap/subdir").is_dir()); assert!(std::fs::create_dir(t.path("mnt/.snapshots/snap/testdir")).is_err()); assert!(std::fs::create_dir(t.path("mnt/.snapshots/snap/subdir/testdir")).is_err()); } } test_case!{ fn unlink_after_snapshot(t) { let contents = b"hello\n"; { let mut f = std::fs::File::create(t.path("mnt/testfile")).unwrap(); f.write(contents).unwrap(); } std::fs::create_dir_all(t.path("mnt/subdir")).unwrap(); { let mut f = std::fs::File::create(t.path("mnt/subdir/testfile")).unwrap(); f.write(contents).unwrap(); } println!("creating .snapshots"); std::fs::create_dir_all(t.path("mnt/.snapshots/snap")).unwrap(); println!("done creating .snapshots/snap"); { println!("verify that the file is in snapshot"); let mut f = std::fs::File::open(t.path("mnt/.snapshots/snap/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } { println!("verify that the file is present"); let mut f = std::fs::File::open(t.path("mnt/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } assert!(t.path("mnt/subdir").is_dir()); assert!(t.path("mnt/subdir/testfile").is_file()); assert!(t.path("mnt/.snapshots/snap/subdir").is_dir()); assert!(std::fs::remove_file(t.path("mnt/.snapshots/snap/testfile")).is_err()); std::fs::remove_file(t.path("mnt/testfile")).unwrap(); assert!(!t.path("mnt/testfiler").exists()); assert!(t.path("mnt/.snapshots/snap/testfile").exists()); { println!("verify that the file is correct in snapshot"); let mut f = std::fs::File::open(t.path("mnt/.snapshots/snap/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } { println!("verify that the subdir file is correct in snapshot"); let mut f = std::fs::File::open(t.path("mnt/.snapshots/snap/subdir/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } assert!(t.path("data/subdir").is_dir()); assert!(t.path("data/subdir/testfile").is_file()); assert!(!t.path("data/.snapshots/snap/subdir/testfile").is_file()); assert!(t.path("mnt/subdir").is_dir()); assert!(t.path("mnt/subdir/testfile").is_file()); //std::fs::remove_dir_all(t.path("mnt/.snapshots/snap/subdir")).is_err(); assert!(t.path("data/subdir").is_dir()); assert!(t.path("data/subdir/testfile").is_file()); assert!(!t.path("data/.snapshots/snap/subdir/testfile").is_file()); assert!(t.path("mnt/subdir").is_dir()); assert!(t.path("mnt/subdir/testfile").is_file()); println!("remove file from subdir"); //std::fs::remove_file(t.path("mnt/subdir/testfile")).unwrap(); std::fs::remove_dir_all(t.path("mnt/subdir")).unwrap(); assert!(!t.path("mnt/subdir").is_dir()); assert!(!t.path("mnt/subdir/testfile").is_file()); assert!(t.path("mnt/.snapshots/snap/subdir").is_dir()); assert!(t.path("mnt/.snapshots/snap/subdir/testfile").is_file()); println!("we should have written subdir to the snap directory"); assert!(t.path("data/.snapshots/snap/subdir").is_dir()); assert!(t.path("data/.snapshots/snap/subdir/testfile").is_file()); { println!("verify that the subdir file is still correct in snapshot"); let mut f = std::fs::File::open(t.path("mnt/.snapshots/snap/subdir/testfile")).unwrap(); let mut actual_contents = Vec::new(); f.read_to_end(&mut actual_contents).unwrap(); assert_eq!(std::str::from_utf8(&actual_contents), std::str::from_utf8(contents)); } } }
use nix::sched::{clone, CloneFlags}; use nix::sys::signal::Signal; use nix::sys::utsname::uname; use nix::sys::wait::waitpid; use nix::unistd::sethostname; use std::env; use std::process; use std::thread; use std::time::Duration; const STACK_LENGTH: usize = 1024 * 1024; fn child_func(hostname: &String) -> isize { // Change hostname in UTS namespace of child sethostname(hostname).expect("sethostname() failed"); let uts = uname(); println!("uts.nodename in child: {}", uts.nodename()); // Keep the namespace open for a while, by sleeping. This allows some // experimentation --- for example, another process might join the // namespace. thread::sleep(Duration::from_secs(100)); // Terminates child. 0 } fn main() { let args: Vec<String> = env::args().collect(); if args.len() < 2 { eprintln!("Usage: {} <child-hostname>", args[0]); process::exit(1); } let mut child_stack: [u8; STACK_LENGTH] = [0; STACK_LENGTH]; // Create a child that has its own UTS namespace; the child commences // execution in `child_func` above. let pid = clone( Box::new(|| child_func(&args[1])), &mut child_stack, CloneFlags::CLONE_NEWUTS, Some(Signal::SIGCHLD as i32), ) .expect("clone() failed"); println!("PID of child created by clone(): {}", pid); // Give child time to change its hostname. thread::sleep(Duration::from_secs(1)); // Display the hostname in parent's UTS namespace. This will be different // from the hostname in child's UTS namespace. let uts = uname(); println!("uts.nodename in parent: {}", uts.nodename()); waitpid(pid, None).expect("waitpid() failed"); println!("child has terminated"); process::exit(0); }
use super::*; use osgood_v8::wrapper::{Local, Valuable}; use osgood_v8::V8; pub fn v8_headers(header_map: &HeaderMap) -> Local<V8::Object> { let context = get_context(); let mut v8_headers = V8::Object::new(); for (h_name, h_value) in header_map { v8_headers.set(context, h_name.as_str(), h_value.to_str().unwrap()); } v8_headers } pub fn rust_headers(v8_headers: Local<V8::Value>, context: Local<V8::Context>) -> HeaderMap { let mut header_map = HeaderMap::new(); for (h_name, h_value) in v8_headers.to_object().iter(context) { header_map.insert( HeaderName::from_bytes((&h_name.as_rust_string()).as_bytes()).unwrap(), (&h_value.as_rust_string()).parse().unwrap(), ); } header_map }
// This file is part of Substrate. // Copyright (C) 2017-2021 Parity Technologies (UK) Ltd. // SPDX-License-Identifier: Apache-2.0 // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use crate::{ chain_spec, cli::{Cli, RelayChainCli, Subcommand}, }; use codec::Encode; use cumulus_client_service::genesis::generate_genesis_block; use cumulus_primitives_core::ParaId; use log::info; use polkadot_parachain::primitives::AccountIdConversion; use sc_cli::{ ChainSpec, CliConfiguration, DefaultConfigurationValues, ImportParams, KeystoreParams, NetworkParams, Result, RuntimeVersion, SharedParams, SubstrateCli, }; use sc_service::config::{BasePath, PrometheusConfig}; use sp_core::hexdisplay::HexDisplay; use sp_runtime::traits::Block as BlockT; use sp_runtime::{generic, OpaqueExtrinsic}; use std::{io::Write, net::SocketAddr}; use runtime_common::Header; pub type Block = generic::Block<Header, OpaqueExtrinsic>; pub const PARACHAIN_ID: u32 = 1000; fn load_spec( id: &str, para_id: ParaId, ) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> { Ok(match id { "statemint-dev" => Box::new(chain_spec::statemint_development_config(para_id)), "statemint-local" => Box::new(chain_spec::statemint_local_config(para_id)), "statemine-dev" => Box::new(chain_spec::statemine_development_config(para_id)), "statemine-local" => Box::new(chain_spec::statemine_local_config(para_id)), "statemine" => Box::new(chain_spec::statemine_config(para_id)), "westmint-dev" => Box::new(chain_spec::westmint_development_config(para_id)), "westmint-local" => Box::new(chain_spec::westmint_local_config(para_id)), "westmint" => Box::new(chain_spec::westmint_config(para_id)), path => { let chain_spec = chain_spec::ChainSpec::from_json_file( path.into(), )?; if use_statemine_runtime(&chain_spec) { Box::new(chain_spec::StatemineChainSpec::from_json_file(path.into())?) } else if use_westmint_runtime(&chain_spec) { Box::new(chain_spec::WestmintChainSpec::from_json_file(path.into())?) } else { Box::new(chain_spec) } }, }) } impl SubstrateCli for Cli { fn impl_name() -> String { "Statemint Collator".into() } fn impl_version() -> String { env!("SUBSTRATE_CLI_IMPL_VERSION").into() } fn description() -> String { format!( "Statemint Collator\n\nThe command-line arguments provided first will be \ passed to the parachain node, while the arguments provided after -- will be passed \ to the relaychain node.\n\n\ {} [parachain-args] -- [relaychain-args]", Self::executable_name() ) } fn author() -> String { env!("CARGO_PKG_AUTHORS").into() } fn support_url() -> String { "https://github.com/paritytech/statemint/issues/new".into() } fn copyright_start_year() -> i32 { 2017 } fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> { load_spec(id, self.run.parachain_id.unwrap_or(PARACHAIN_ID).into()) } fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion { if use_statemine_runtime(&**chain_spec) { &statemine_runtime::VERSION } else if use_westmint_runtime(&**chain_spec) { &westmint_runtime::VERSION } else { &statemint_runtime::VERSION } } } impl SubstrateCli for RelayChainCli { fn impl_name() -> String { "Statemint Collator".into() } fn impl_version() -> String { env!("SUBSTRATE_CLI_IMPL_VERSION").into() } fn description() -> String { "Statemint Collator\n\nThe command-line arguments provided first will be \ passed to the parachain node, while the arguments provided after -- will be passed \ to the relaychain node.\n\n\ rococo-collator [parachain-args] -- [relaychain-args]" .into() } fn author() -> String { env!("CARGO_PKG_AUTHORS").into() } fn support_url() -> String { "https://github.com/paritytech/statemint/issues/new".into() } fn copyright_start_year() -> i32 { 2017 } fn load_spec(&self, id: &str) -> std::result::Result<Box<dyn sc_service::ChainSpec>, String> { polkadot_cli::Cli::from_iter([RelayChainCli::executable_name().to_string()].iter()) .load_spec(id) } fn native_runtime_version(chain_spec: &Box<dyn ChainSpec>) -> &'static RuntimeVersion { polkadot_cli::Cli::native_runtime_version(chain_spec) } } fn extract_genesis_wasm(chain_spec: &Box<dyn sc_service::ChainSpec>) -> Result<Vec<u8>> { let mut storage = chain_spec.build_storage()?; storage .top .remove(sp_core::storage::well_known_keys::CODE) .ok_or_else(|| "Could not find wasm file in genesis state!".into()) } fn use_statemine_runtime(chain_spec: &dyn ChainSpec) -> bool { chain_spec.id().starts_with("statemine") } fn use_westmint_runtime(chain_spec: &dyn ChainSpec) -> bool { chain_spec.id().starts_with("westmint") } use crate::service::{new_partial, StatemintRuntimeExecutor, StatemineRuntimeExecutor, WestmintRuntimeExecutor}; macro_rules! construct_async_run { (|$components:ident, $cli:ident, $cmd:ident, $config:ident| $( $code:tt )* ) => {{ let runner = $cli.create_runner($cmd)?; if use_statemine_runtime(&*runner.config().chain_spec) { runner.async_run(|$config| { let $components = new_partial::<statemine_runtime::RuntimeApi, StatemineRuntimeExecutor>( &$config, )?; let task_manager = $components.task_manager; { $( $code )* }.map(|v| (v, task_manager)) }) } else if use_westmint_runtime(&*runner.config().chain_spec) { runner.async_run(|$config| { let $components = new_partial::<westmint_runtime::RuntimeApi, WestmintRuntimeExecutor>( &$config, )?; let task_manager = $components.task_manager; { $( $code )* }.map(|v| (v, task_manager)) }) } else { runner.async_run(|$config| { let $components = new_partial::<statemint_runtime::RuntimeApi, StatemintRuntimeExecutor>( &$config, )?; let task_manager = $components.task_manager; { $( $code )* }.map(|v| (v, task_manager)) }) } }} } /// Parse command line arguments into service configuration. pub fn run() -> Result<()> { let cli = Cli::from_args(); match &cli.subcommand { Some(Subcommand::BuildSpec(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| cmd.run(config.chain_spec, config.network)) } Some(Subcommand::CheckBlock(cmd)) => { construct_async_run!(|components, cli, cmd, config| { Ok(cmd.run(components.client, components.import_queue)) }) } Some(Subcommand::ExportBlocks(cmd)) => { construct_async_run!(|components, cli, cmd, config| { Ok(cmd.run(components.client, config.database)) }) } Some(Subcommand::ExportState(cmd)) => { construct_async_run!(|components, cli, cmd, config| { Ok(cmd.run(components.client, config.chain_spec)) }) } Some(Subcommand::ImportBlocks(cmd)) => { construct_async_run!(|components, cli, cmd, config| { Ok(cmd.run(components.client, components.import_queue)) }) } Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| { let polkadot_cli = RelayChainCli::new( &config, [RelayChainCli::executable_name().to_string()] .iter() .chain(cli.relaychain_args.iter()), ); let polkadot_config = SubstrateCli::create_configuration( &polkadot_cli, &polkadot_cli, config.task_executor.clone(), ) .map_err(|err| format!("Relay chain argument error: {}", err))?; cmd.run(config, polkadot_config) }) } Some(Subcommand::Revert(cmd)) => construct_async_run!(|components, cli, cmd, config| { Ok(cmd.run(components.client, components.backend)) }), Some(Subcommand::ExportGenesisState(params)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); let _ = builder.init(); let block: Block = generate_genesis_block(&load_spec( &params.chain.clone().unwrap_or_default(), params.parachain_id.unwrap_or(PARACHAIN_ID).into(), )?)?; let raw_header = block.header().encode(); let output_buf = if params.raw { raw_header } else { format!("0x{:?}", HexDisplay::from(&block.header().encode())).into_bytes() }; if let Some(output) = &params.output { std::fs::write(output, output_buf)?; } else { std::io::stdout().write_all(&output_buf)?; } Ok(()) } Some(Subcommand::ExportGenesisWasm(params)) => { let mut builder = sc_cli::LoggerBuilder::new(""); builder.with_profiling(sc_tracing::TracingReceiver::Log, ""); let _ = builder.init(); let raw_wasm_blob = extract_genesis_wasm(&cli.load_spec(&params.chain.clone().unwrap_or_default())?)?; let output_buf = if params.raw { raw_wasm_blob } else { format!("0x{:?}", HexDisplay::from(&raw_wasm_blob)).into_bytes() }; if let Some(output) = &params.output { std::fs::write(output, output_buf)?; } else { std::io::stdout().write_all(&output_buf)?; } Ok(()) }, Some(Subcommand::Benchmark(cmd)) => { if cfg!(feature = "runtime-benchmarks") { let runner = cli.create_runner(cmd)?; if use_statemine_runtime(&*runner.config().chain_spec) { runner.sync_run(|config| cmd.run::<Block, StatemineRuntimeExecutor>(config)) } else if use_westmint_runtime(&*runner.config().chain_spec) { runner.sync_run(|config| cmd.run::<Block, WestmintRuntimeExecutor>(config)) } else { runner.sync_run(|config| cmd.run::<Block, StatemintRuntimeExecutor>(config)) } } else { Err("Benchmarking wasn't enabled when building the node. \ You can enable it with `--features runtime-benchmarks`.".into()) } }, None => { let runner = cli.create_runner(&cli.run.normalize())?; let use_statemine = use_statemine_runtime(&*runner.config().chain_spec); let use_westmint = use_westmint_runtime(&*runner.config().chain_spec); runner.run_node_until_exit(|config| async move { let key = sp_core::Pair::generate().0; let para_id = chain_spec::Extensions::try_get(&*config.chain_spec).map(|e| e.para_id); let polkadot_cli = RelayChainCli::new( &config, [RelayChainCli::executable_name().to_string()] .iter() .chain(cli.relaychain_args.iter()), ); let id = ParaId::from(cli.run.parachain_id.or(para_id).unwrap_or(PARACHAIN_ID)); let parachain_account = AccountIdConversion::<polkadot_primitives::v0::AccountId>::into_account(&id); let block: Block = generate_genesis_block(&config.chain_spec).map_err(|e| format!("{:?}", e))?; let genesis_state = format!("0x{:?}", HexDisplay::from(&block.header().encode())); let task_executor = config.task_executor.clone(); let polkadot_config = SubstrateCli::create_configuration( &polkadot_cli, &polkadot_cli, task_executor, ) .map_err(|err| format!("Relay chain argument error: {}", err))?; info!("Parachain id: {:?}", id); info!("Parachain Account: {}", parachain_account); info!("Parachain genesis state: {}", genesis_state); info!("Is collating: {}", if config.role.is_authority() { "yes" } else { "no" }); if use_statemine { crate::service::start_node::<statemine_runtime::RuntimeApi, StatemineRuntimeExecutor, _>( config, key, polkadot_config, id, |_| Default::default(), ) .await .map(|r| r.0) .map_err(Into::into) } else if use_westmint { crate::service::start_node::<westmint_runtime::RuntimeApi, WestmintRuntimeExecutor, _>( config, key, polkadot_config, id, |_| Default::default(), ) .await .map(|r| r.0) .map_err(Into::into) } else { crate::service::start_node::<statemint_runtime::RuntimeApi, StatemintRuntimeExecutor, _>( config, key, polkadot_config, id, |_| Default::default(), ) .await .map(|r| r.0) .map_err(Into::into) } }) } } } impl DefaultConfigurationValues for RelayChainCli { fn p2p_listen_port() -> u16 { 30334 } fn rpc_ws_listen_port() -> u16 { 9945 } fn rpc_http_listen_port() -> u16 { 9934 } fn prometheus_listen_port() -> u16 { 9616 } } impl CliConfiguration<Self> for RelayChainCli { fn shared_params(&self) -> &SharedParams { self.base.base.shared_params() } fn import_params(&self) -> Option<&ImportParams> { self.base.base.import_params() } fn network_params(&self) -> Option<&NetworkParams> { self.base.base.network_params() } fn keystore_params(&self) -> Option<&KeystoreParams> { self.base.base.keystore_params() } fn base_path(&self) -> Result<Option<BasePath>> { Ok(self .shared_params() .base_path() .or_else(|| self.base_path.clone().map(Into::into))) } fn rpc_http(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> { self.base.base.rpc_http(default_listen_port) } fn rpc_ipc(&self) -> Result<Option<String>> { self.base.base.rpc_ipc() } fn rpc_ws(&self, default_listen_port: u16) -> Result<Option<SocketAddr>> { self.base.base.rpc_ws(default_listen_port) } fn prometheus_config(&self, default_listen_port: u16) -> Result<Option<PrometheusConfig>> { self.base.base.prometheus_config(default_listen_port) } fn init<C: SubstrateCli>(&self) -> Result<()> { unreachable!("PolkadotCli is never initialized; qed"); } fn chain_id(&self, is_dev: bool) -> Result<String> { let chain_id = self.base.base.chain_id(is_dev)?; Ok(if chain_id.is_empty() { self.chain_id.clone().unwrap_or_default() } else { chain_id }) } fn role(&self, is_dev: bool) -> Result<sc_service::Role> { self.base.base.role(is_dev) } fn transaction_pool(&self) -> Result<sc_service::config::TransactionPoolOptions> { self.base.base.transaction_pool() } fn state_cache_child_ratio(&self) -> Result<Option<usize>> { self.base.base.state_cache_child_ratio() } fn rpc_methods(&self) -> Result<sc_service::config::RpcMethods> { self.base.base.rpc_methods() } fn rpc_ws_max_connections(&self) -> Result<Option<usize>> { self.base.base.rpc_ws_max_connections() } fn rpc_cors(&self, is_dev: bool) -> Result<Option<Vec<String>>> { self.base.base.rpc_cors(is_dev) } fn telemetry_external_transport(&self) -> Result<Option<sc_service::config::ExtTransport>> { self.base.base.telemetry_external_transport() } fn default_heap_pages(&self) -> Result<Option<u64>> { self.base.base.default_heap_pages() } fn force_authoring(&self) -> Result<bool> { self.base.base.force_authoring() } fn disable_grandpa(&self) -> Result<bool> { self.base.base.disable_grandpa() } fn max_runtime_instances(&self) -> Result<Option<usize>> { self.base.base.max_runtime_instances() } fn announce_block(&self) -> Result<bool> { self.base.base.announce_block() } fn telemetry_endpoints( &self, chain_spec: &Box<dyn ChainSpec>, ) -> Result<Option<sc_telemetry::TelemetryEndpoints>> { self.base.base.telemetry_endpoints(chain_spec) } }
pub fn sum_of_multiples(limit: u32, factors: &[u32]) -> u32 { let mut mult = Vec::new(); for num in 1..limit { let multiples = factors.iter().map(|f| { if *f == 0 { 0 } else { match num % f { 0 => 1, _ => 0 }} }).fold(0, |sum, x| sum + x); if multiples > 0 { mult.push(num); } } mult.iter().fold(0, |sum, x| sum + x) }
use crate::conv_req::convert_req; use crate::Options; use actix_web::{http::StatusCode, web, HttpRequest, HttpResponse}; use fmterr::fmt_err; use perseus::{ err_to_status_code, serve::get_page_for_template, stores::{ImmutableStore, MutableStore}, TranslationsManager, }; use serde::Deserialize; #[derive(Deserialize)] pub struct PageDataReq { pub template_name: String, pub was_incremental_match: bool, } /// The handler for calls to `.perseus/page/*`. This will manage returning errors and the like. pub async fn page_data<M: MutableStore, T: TranslationsManager>( req: HttpRequest, opts: web::Data<Options>, immutable_store: web::Data<ImmutableStore>, mutable_store: web::Data<M>, translations_manager: web::Data<T>, web::Query(query_params): web::Query<PageDataReq>, ) -> HttpResponse { let templates = &opts.templates_map; let locale = req.match_info().query("locale"); let PageDataReq { template_name, was_incremental_match, } = query_params; // Check if the locale is supported if opts.locales.is_supported(locale) { let path = req.match_info().query("filename"); // We need to turn the Actix Web request into one acceptable for Perseus (uses `http` internally) let http_req = convert_req(&req); let http_req = match http_req { Ok(http_req) => http_req, // If this fails, the client request is malformed, so it's a 400 Err(err) => { return HttpResponse::build(StatusCode::from_u16(400).unwrap()).body(fmt_err(&err)) } }; // Get the template to use let template = templates.get(&template_name); let template = match template { Some(template) => template, None => { // We know the template has been pre-routed and should exist, so any failure here is a 500 return HttpResponse::InternalServerError().body("template not found".to_string()); } }; let page_data = get_page_for_template( path, locale, template, was_incremental_match, http_req, (immutable_store.get_ref(), mutable_store.get_ref()), translations_manager.get_ref(), ) .await; match page_data { Ok(page_data) => { let mut http_res = HttpResponse::Ok(); http_res.content_type("text/html"); // Generate and add HTTP headers for (key, val) in template.get_headers(page_data.state.clone()) { http_res.set_header(key.unwrap(), val); } http_res.body(serde_json::to_string(&page_data).unwrap()) } // We parse the error to return an appropriate status code Err(err) => { HttpResponse::build(StatusCode::from_u16(err_to_status_code(&err)).unwrap()) .body(fmt_err(&err)) } } } else { HttpResponse::NotFound().body("locale not supported".to_string()) } }
use alloc::vec::Vec; use util::Hash; use super::{EdonR, P384}; pub struct EdonR384(EdonR<u64>); impl EdonR384 { pub fn new() -> Self { Self::default() } } impl Default for EdonR384 { fn default() -> Self { Self(EdonR::<u64>::new(P384)) } } impl Hash for EdonR384 { fn hash_to_bytes(&mut self, message: &[u8]) -> Vec<u8> { self.0.edonr(message); self.0.state[10..16] .iter() .flat_map(|word| word.to_le_bytes().to_vec()) .collect() } }
pub mod vec2; pub mod vec3; pub mod quaternion; pub mod mat4x4; pub mod transform; pub use vec2::Vec2 as Vec2; pub use vec3::Vec3 as Vec3; pub use quaternion::Quaternion as Quaternion; pub use mat4x4::Mat4x4 as Mat4x4; pub use transform::Transform as Transform;
//! Bindings to [HDF5][1]. //! //! [1]: http://www.hdfgroup.org/HDF5 #![allow(non_camel_case_types, non_snake_case)] extern crate libc; mod H5ACpublic; mod H5Apublic; mod H5Cpublic; mod H5Dpublic; mod H5Epublic; mod H5FDpublic; mod H5Fpublic; mod H5Gpublic; mod H5Ipublic; mod H5Lpublic; mod H5MMpublic; mod H5Opublic; mod H5PLpublic; mod H5Ppublic; mod H5Rpublic; mod H5Spublic; mod H5Tpublic; mod H5Zpublic; mod H5public; pub use H5ACpublic::*; pub use H5Apublic::*; pub use H5Cpublic::*; pub use H5Dpublic::*; pub use H5Epublic::*; pub use H5FDpublic::*; pub use H5Fpublic::*; pub use H5Gpublic::*; pub use H5Ipublic::*; pub use H5Lpublic::*; pub use H5MMpublic::*; pub use H5Opublic::*; pub use H5PLpublic::*; pub use H5Ppublic::*; pub use H5Rpublic::*; pub use H5Spublic::*; pub use H5Tpublic::*; pub use H5Zpublic::*; pub use H5public::*; #[cfg(test)] mod tests { #[test] fn link() { let (mut majnum, mut minnum, mut relnum) = (0, 0, 0); assert!(unsafe { ::H5get_libversion(&mut majnum, &mut minnum, &mut relnum) } >= 0); assert_eq!((majnum, minnum), (1, 8)); } }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - control register 1"] pub cr1: CR1, #[doc = "0x04 - control register 2"] pub cr2: CR2, #[doc = "0x08 - slave mode control register"] pub smcr: SMCR, #[doc = "0x0c - DMA/Interrupt enable register"] pub dier: DIER, #[doc = "0x10 - status register"] pub sr: SR, #[doc = "0x14 - event generation register"] pub egr: EGR, _reserved_6_ccmr1: [u8; 0x04], _reserved7: [u8; 0x04], #[doc = "0x20 - capture/compare enable register"] pub ccer: CCER, #[doc = "0x24 - counter"] pub cnt: CNT, #[doc = "0x28 - prescaler"] pub psc: PSC, #[doc = "0x2c - auto-reload register"] pub arr: ARR, #[doc = "0x30 - repetition counter register"] pub rcr: RCR, #[doc = "0x34..0x3c - capture/compare register"] pub ccr: [CCR; 2], _reserved13: [u8; 0x08], #[doc = "0x44 - break and dead-time register"] pub bdtr: BDTR, #[doc = "0x48 - DMA control register"] pub dcr: DCR, #[doc = "0x4c - DMA address for full transfer"] pub dmar: DMAR, _reserved16: [u8; 0x10], #[doc = "0x60 - TIM15 alternate fdfsdm1_breakon register 1"] pub af1: AF1, _reserved17: [u8; 0x04], #[doc = "0x68 - TIM15 input selection register"] pub tisel: TISEL, } impl RegisterBlock { #[doc = "0x18 - capture/compare mode register 1 (input mode)"] #[inline(always)] pub const fn ccmr1_input(&self) -> &CCMR1_INPUT { unsafe { &*(self as *const Self).cast::<u8>().add(24usize).cast() } } #[doc = "0x18 - capture/compare mode register (output mode)"] #[inline(always)] pub const fn ccmr1_output(&self) -> &CCMR1_OUTPUT { unsafe { &*(self as *const Self).cast::<u8>().add(24usize).cast() } } #[doc = "0x34 - capture/compare register"] #[inline(always)] pub fn ccr1(&self) -> &CCR { &self.ccr[0] } #[doc = "0x38 - capture/compare register"] #[inline(always)] pub fn ccr2(&self) -> &CCR { &self.ccr[1] } } #[doc = "CR1 (rw) register accessor: control register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr1`] module"] pub type CR1 = crate::Reg<cr1::CR1_SPEC>; #[doc = "control register 1"] pub mod cr1; #[doc = "CR2 (rw) register accessor: control register 2\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cr2::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cr2::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cr2`] module"] pub type CR2 = crate::Reg<cr2::CR2_SPEC>; #[doc = "control register 2"] pub mod cr2; #[doc = "SMCR (rw) register accessor: slave mode control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`smcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`smcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`smcr`] module"] pub type SMCR = crate::Reg<smcr::SMCR_SPEC>; #[doc = "slave mode control register"] pub mod smcr; #[doc = "DIER (rw) register accessor: DMA/Interrupt enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dier::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dier::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`dier`] module"] pub type DIER = crate::Reg<dier::DIER_SPEC>; #[doc = "DMA/Interrupt enable register"] pub mod dier; #[doc = "SR (rw) register accessor: status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`sr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`sr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`sr`] module"] pub type SR = crate::Reg<sr::SR_SPEC>; #[doc = "status register"] pub mod sr; #[doc = "EGR (w) register accessor: event generation register\n\nYou can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`egr::W`]. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`egr`] module"] pub type EGR = crate::Reg<egr::EGR_SPEC>; #[doc = "event generation register"] pub mod egr; #[doc = "CCMR1_Output (rw) register accessor: capture/compare mode register (output mode)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccmr1_output::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccmr1_output::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccmr1_output`] module"] pub type CCMR1_OUTPUT = crate::Reg<ccmr1_output::CCMR1_OUTPUT_SPEC>; #[doc = "capture/compare mode register (output mode)"] pub mod ccmr1_output; #[doc = "CCMR1_Input (rw) register accessor: capture/compare mode register 1 (input mode)\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccmr1_input::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccmr1_input::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccmr1_input`] module"] pub type CCMR1_INPUT = crate::Reg<ccmr1_input::CCMR1_INPUT_SPEC>; #[doc = "capture/compare mode register 1 (input mode)"] pub mod ccmr1_input; #[doc = "CCER (rw) register accessor: capture/compare enable register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccer::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccer::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccer`] module"] pub type CCER = crate::Reg<ccer::CCER_SPEC>; #[doc = "capture/compare enable register"] pub mod ccer; #[doc = "CNT (rw) register accessor: counter\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`cnt::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`cnt::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`cnt`] module"] pub type CNT = crate::Reg<cnt::CNT_SPEC>; #[doc = "counter"] pub mod cnt; #[doc = "PSC (rw) register accessor: prescaler\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`psc::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`psc::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`psc`] module"] pub type PSC = crate::Reg<psc::PSC_SPEC>; #[doc = "prescaler"] pub mod psc; #[doc = "ARR (rw) register accessor: auto-reload register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`arr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`arr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`arr`] module"] pub type ARR = crate::Reg<arr::ARR_SPEC>; #[doc = "auto-reload register"] pub mod arr; #[doc = "RCR (rw) register accessor: repetition counter register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`rcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`rcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`rcr`] module"] pub type RCR = crate::Reg<rcr::RCR_SPEC>; #[doc = "repetition counter register"] pub mod rcr; #[doc = "CCR (rw) register accessor: capture/compare register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`ccr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`ccr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`ccr`] module"] pub type CCR = crate::Reg<ccr::CCR_SPEC>; #[doc = "capture/compare register"] pub mod ccr; #[doc = "BDTR (rw) register accessor: break and dead-time register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bdtr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`bdtr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`bdtr`] module"] pub type BDTR = crate::Reg<bdtr::BDTR_SPEC>; #[doc = "break and dead-time register"] pub mod bdtr; #[doc = "DCR (rw) register accessor: DMA control register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dcr::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dcr::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`dcr`] module"] pub type DCR = crate::Reg<dcr::DCR_SPEC>; #[doc = "DMA control register"] pub mod dcr; #[doc = "DMAR (rw) register accessor: DMA address for full transfer\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`dmar::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`dmar::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`dmar`] module"] pub type DMAR = crate::Reg<dmar::DMAR_SPEC>; #[doc = "DMA address for full transfer"] pub mod dmar; #[doc = "AF1 (rw) register accessor: TIM15 alternate fdfsdm1_breakon register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`af1::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`af1::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`af1`] module"] pub type AF1 = crate::Reg<af1::AF1_SPEC>; #[doc = "TIM15 alternate fdfsdm1_breakon register 1"] pub mod af1; #[doc = "TISEL (rw) register accessor: TIM15 input selection register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`tisel::R`]. You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`tisel::W`]. You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [`tisel`] module"] pub type TISEL = crate::Reg<tisel::TISEL_SPEC>; #[doc = "TIM15 input selection register"] pub mod tisel;
use js_sys::Date; use log; use log::{Level, LevelFilter, Metadata, Record}; struct SimpleLogger; impl log::Log for SimpleLogger { fn enabled(&self, metadata: &Metadata) -> bool { //metadata.level() < Level::Trace true } fn log(&self, record: &Record) { if self.enabled(record.metadata()) { let color = match record.level() { Level::Warn => "color: #FF4500", Level::Error => "color: #f00", Level::Info => "color: #006", Level::Debug => "color: #f09", _ => "", }; log( &format!( "%c {} {}:{} - {}", Date::now() as u64, record.level(), record.target(), record.args() ), color, ); } } fn flush(&self) {} } static LOGGER: SimpleLogger = SimpleLogger; pub fn init() { log::set_logger(&LOGGER) .map(|()| log::set_max_level(LevelFilter::Trace)) .unwrap(); }
use kompact::prelude::*; use std::marker::PhantomData; use tokio::sync::broadcast::Receiver; use tokio::sync::broadcast::Sender; use crate::control::Control; use crate::data::Sharable; use crate::prelude::*; #[derive(Collectable, Finalize, NoTrace, NoSerde, NoDebug)] pub struct Pushable<T: Sharable>(Sender<T::T>); impl<T: Sharable> Clone for Pushable<T> { fn clone(&self) -> Self { Pushable(self.0.clone()) } } #[derive(Collectable, Finalize, NoTrace, NoSerde, NoDebug)] pub struct Pullable<T: Sharable>(Sender<T::T>, Receiver<T::T>); impl<T: Sharable> Clone for Pullable<T> { fn clone(&self) -> Self { Pullable(self.0.clone(), self.0.subscribe()) } } crate::data::convert_reflexive!({T: Sharable} Pushable<T>); crate::data::convert_reflexive!({T: Sharable} Pullable<T>); crate::data::channels::impl_channel!(); /// TODO: Processing will currently only stop if all pullers are dropped. pub fn channel<T: Sharable>(_: Context) -> (Pushable<T>, Pullable<T>) where T::T: Sendable, { let (l, r) = tokio::sync::broadcast::channel(100); (Pushable(l.clone()), Pullable(l, r)) } impl<T: Sharable> Pushable<T> { pub async fn push(&self, data: T, ctx: Context) -> Control<()> { self.0 .send(data.into_sendable(ctx)) .map(|_| Control::Continue(())) .unwrap_or(Control::Finished) } } impl<T: Sharable> Pullable<T> { pub async fn pull(&mut self, ctx: Context) -> Control<<T::T as DynSendable>::T> { self.1 .recv() .await .map(|v| Control::Continue(v.into_sharable(ctx))) .unwrap_or(Control::Finished) } }
#[cfg(test)] pub mod test_formatting { use super::super::super::euler_library::utilities; #[test] fn milliseconds_less_than_10() { assert_eq!(utilities::format_milliseconds(6),"00:00:00:006"); } #[test] fn milliseconds_less_than_100() { assert_eq!(utilities::format_milliseconds(76),"00:00:00:076"); } #[test] fn seconds_less_than_10() { assert_eq!(utilities::format_milliseconds(5000),"00:00:05:000"); } #[test] fn minutes_less_than_10() { assert_eq!(utilities::format_milliseconds(180000),"00:03:00:000"); } #[test] fn hours_less_than_10() { assert_eq!(utilities::format_milliseconds(7200000),"02:00:00:000"); } #[test] fn milliseconds_not_more_than_999() { assert_eq!(utilities::format_milliseconds(1000),"00:00:01:000"); } #[test] fn seconds_less_than_60() { assert_eq!(utilities::format_milliseconds(60000),"00:01:00:000"); } #[test] fn minutess_less_than_60() { assert_eq!(utilities::format_milliseconds(3600000),"01:00:00:000"); } #[test] fn hours_more_than_99() { assert_eq!(utilities::format_milliseconds(360000000),"100:00:00:000"); } }
//! Encoding of a binary [`Envelope`]. //! //! ```text //! //! +-------------+--------------+----------------+----------------+ //! | | | | | //! | Principal | Amount | Gas Limit | Gas Fee | //! | (Address) | (u64) | (u64) | (u64) | //! | | | | | //! | 20 bytes | 8 bytes | 8 bytes | 8 bytes | //! | | (Big-Endian) | (Big-Endian) | (Big-Endian) | //! | | | | | //! +-------------+--------------+----------------+----------------+ //! //! ``` use std::io::Cursor; use svm_types::{Envelope, Gas}; use crate::{ReadExt, WriteExt}; /// Returns the number of bytes required to hold a binary [`Envelope`]. pub const fn byte_size() -> usize { 20 + 8 + 8 + 8 } /// Encodes a binary [`Envelope`] of a transaction. pub fn encode(envelope: &Envelope, w: &mut Vec<u8>) { w.write_address(envelope.principal()); w.write_u64_be(envelope.amount()); w.write_u64_be(envelope.gas_limit().unwrap_or(0)); w.write_u64_be(envelope.gas_fee()); } /// Decodes a binary [`Envelope`] of a transaction. /// /// Returns the decoded [`Envelope`], /// On failure, returns [`std::io::Result`]. pub fn decode(cursor: &mut Cursor<&[u8]>) -> std::io::Result<Envelope> { let principal = cursor.read_address()?; let amount = cursor.read_u64_be()?; let gas_limit = cursor.read_u64_be()?; let gas_fee = cursor.read_u64_be()?; let gas_limit = if gas_limit > 0 { Gas::with(gas_limit) } else { Gas::new() }; let envelope = Envelope::new(principal, amount, gas_limit, gas_fee); Ok(envelope) }
#[derive(Debug)] struct BigStruct { one : i32, two : i32, three : i32 } fn foo(x : Box<BigStruct>) -> BigStruct { *x } fn main() { let a = BigStruct {one:1, two:2, three:3}; println!("address of struct {:p}", &a); let x = Box::new(a); println!("address of boxed struct {:p}", &*x); println!("value of x {:?}", *x); let mut y = foo(x); println!("address of returned struct {:p}", &y); y.two = 20; let z = Box::new(y); println!("address of boxed returned struct {:p}", &*z); println!("value of z {:?}", *z); let b = Box::new(BigStruct {one:10, two:20, three:30}); println!("address of boxed struct {:p}", &*b); let p = Box::new(foo(b)); println!("address of returned boxed struct {:p}", &*p); }
//! Hydroflow surface syntax #![warn(missing_docs)] #![cfg_attr( feature = "diagnostics", feature(proc_macro_diagnostic, proc_macro_span) )] #![allow(clippy::let_and_return)] #![allow(clippy::explicit_auto_deref)] pub mod diagnostic; pub mod graph; pub mod parse; pub mod pretty_span; pub mod union_find;
/* * 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. */ // This module defines only macros which don't show up on module level // documentation anyway so hide it. #![doc(hidden)] #[doc(hidden)] pub mod common_macro_prelude { pub use lazy_static::lazy_static; pub use perthread::{PerThread, ThreadMap}; pub use stats_traits::{ dynamic_stat_types::DynamicStat, stat_types::{BoxCounter, BoxHistogram, BoxSingletonCounter, BoxTimeseries}, stats_manager::{AggregationType::*, BoxStatsManager, BucketConfig, StatsManager}, }; pub use std::sync::Arc; pub use std::time::Duration; pub use crate::create_singleton_counter; pub use crate::create_stats_manager; pub use crate::thread_local_aggregator::create_map; } /// The macro to define STATS module that contains static variables, one per counter you want to /// export. This is the main and recomended way to interact with statistics provided by this crate. /// If non empty prefix is passed then the exported counter name will be "{prefix}.{name}" /// /// Examples: /// ``` /// use stats::prelude::*; /// use fbinit::FacebookInit; /// /// define_stats! { /// prefix = "my.test.counters"; /// manual_c: singleton_counter(), /// test_c: counter(), /// test_c2: counter("test_c.two"), /// test_t: timeseries(Sum, Average), /// test_t2: timeseries("test_t.two"; Sum, Average), /// test_h: histogram(1, 0, 1000, Sum; P 99; P 50), /// dtest_c: dynamic_counter("test_c.{}", (job: u64)), /// dtest_t: dynamic_timeseries("test_t.{}", (region: &'static str); Rate, Sum), /// dtest_t2: dynamic_timeseries("test_t.two.{}.{}", (job: u64, region: &'static str); Count), /// dtest_h: dynamic_histogram("test_h.{}", (region: &'static str); 1, 0, 1000, Sum; P 99), /// } /// /// #[allow(non_snake_case)] /// mod ALT_STATS { /// use stats::define_stats; /// define_stats! { /// test_t: timeseries(Sum, Average), /// test_t2: timeseries("test.two"; Sum, Average), /// } /// pub use self::STATS::*; /// } /// /// #[fbinit::main] /// fn main(fb: FacebookInit) { /// STATS::manual_c.set_value(fb, 1); /// STATS::test_c.increment_value(1); /// STATS::test_c2.increment_value(100); /// STATS::test_t.add_value(1); /// STATS::test_t2.add_value_aggregated(79, 10); // Add 79 and note it came from 10 samples /// STATS::test_h.add_value(1); /// STATS::test_h.add_repeated_value(1, 44); // 44 times repeat adding 1 /// STATS::dtest_c.increment_value(7, (1000,)); /// STATS::dtest_t.add_value(77, ("lla",)); /// STATS::dtest_t2.add_value_aggregated(81, 12, (7, "lla")); /// STATS::dtest_h.add_value(2, ("frc",)); /// /// ALT_STATS::test_t.add_value(1); /// ALT_STATS::test_t2.add_value(1); /// } /// ``` #[macro_export] macro_rules! define_stats { // Fill the optional prefix with empty string, all matching is repeated here to avoid the // recursion limit reached error in case the macro is misused. ($( $name:ident: $stat_type:tt($( $params:tt )*), )*) => (define_stats!(prefix = ""; $( $name: $stat_type($( $params )*), )*);); (prefix = $prefix:expr; $( $name:ident: $stat_type:tt($( $params:tt )*), )*) => ( #[allow(non_snake_case, non_upper_case_globals, unused_imports)] pub(crate) mod STATS { use $crate::macros::common_macro_prelude::*; lazy_static! { static ref STATS_MAP: Arc<ThreadMap<BoxStatsManager>> = create_map(); } thread_local! { static TL_STATS: PerThread<BoxStatsManager> = STATS_MAP.register(create_stats_manager()); } $( $crate::__define_stat!($prefix; $name: $stat_type($( $params )*)); )* } ); } #[doc(hidden)] #[macro_export] macro_rules! __define_key_generator { ($name:ident($prefix:expr, $key:expr; $( $placeholder:ident: $type:ty ),+)) => ( fn $name(&($( ref $placeholder, )+): &($( $type, )+)) -> String { let key = format!($key, $( $placeholder ),+); if $prefix.is_empty() { key } else { [$prefix, &key].join(".") } } ); } #[doc(hidden)] #[macro_export] macro_rules! __define_stat { ($prefix:expr; $name:ident: singleton_counter()) => ( $crate::__define_stat!($prefix; $name: singleton_counter(stringify!($name))); ); ($prefix:expr; $name:ident: singleton_counter($key:expr)) => ( lazy_static! { pub static ref $name: BoxSingletonCounter = create_singleton_counter($crate::__create_stat_key!($prefix, $key).to_string()); } ); ($prefix:expr; $name:ident: counter()) => ( $crate::__define_stat!($prefix; $name: counter(stringify!($name))); ); ($prefix:expr; $name:ident: counter($key:expr)) => ( thread_local! { pub static $name: BoxCounter = TL_STATS.with(|stats| { stats.create_counter(&$crate::__create_stat_key!($prefix, $key)) }); } ); // There are 4 inputs we use to produce a timeseries: the the prefix, the name (used in // STATS::name), the key (used in ODS or to query the key), the export types (SUM, RATE, etc.), // and the intervals (e.g. 60, 600). The key defaults to the name, and the intervals default to // whatever default Folly uses (which happens to be 60, 600, 3600); ($prefix:expr; $name:ident: timeseries($( $aggregation_type:expr ),*)) => ( $crate::__define_stat!($prefix; $name: timeseries(stringify!($name); $( $aggregation_type ),*)); ); ($prefix:expr; $name:ident: timeseries($key:expr; $( $aggregation_type:expr ),*)) => ( $crate::__define_stat!($prefix; $name: timeseries($key; $( $aggregation_type ),* ; )); ); ($prefix:expr; $name:ident: timeseries($key:expr; $( $aggregation_type:expr ),* ; $( $interval: expr ),*)) => ( thread_local! { pub static $name: BoxTimeseries = TL_STATS.with(|stats| { stats.create_timeseries( &$crate::__create_stat_key!($prefix, $key), &[$( $aggregation_type ),*], &[$( $interval ),*] ) }); } ); ($prefix:expr; $name:ident: histogram($bucket_width:expr, $min:expr, $max:expr $(, $aggregation_type:expr )* $(; P $percentile:expr )*)) => ( $crate::__define_stat!($prefix; $name: histogram(stringify!($name); $bucket_width, $min, $max $(, $aggregation_type )* $(; P $percentile )*)); ); ($prefix:expr; $name:ident: histogram($key:expr; $bucket_width:expr, $min:expr, $max:expr $(, $aggregation_type:expr )* $(; P $percentile:expr )*)) => ( thread_local! { pub static $name: BoxHistogram = TL_STATS.with(|stats| { stats.create_histogram( &$crate::__create_stat_key!($prefix, $key), &[$( $aggregation_type ),*], BucketConfig { width: $bucket_width, min: $min, max: $max, }, &[$( $percentile ),*]) }); } ); ($prefix:expr; $name:ident: dynamic_singleton_counter($key:expr, ($( $placeholder:ident: $type:ty ),+))) => ( thread_local! { pub static $name: DynamicStat<($( $type, )+), BoxSingletonCounter> = { $crate::__define_key_generator!( __key_generator($prefix, $key; $( $placeholder: $type ),+) ); fn __stat_generator(key: &str) -> BoxSingletonCounter { create_singleton_counter(key.to_string()) } DynamicStat::new(__key_generator, __stat_generator) } } ); ($prefix:expr; $name:ident: dynamic_counter($key:expr, ($( $placeholder:ident: $type:ty ),+))) => ( thread_local! { pub static $name: DynamicStat<($( $type, )+), BoxCounter> = { $crate::__define_key_generator!( __key_generator($prefix, $key; $( $placeholder: $type ),+) ); fn __stat_generator(key: &str) -> BoxCounter { TL_STATS.with(|stats| { stats.create_counter(key) }) } DynamicStat::new(__key_generator, __stat_generator) } } ); ($prefix:expr; $name:ident: dynamic_timeseries($key:expr, ($( $placeholder:ident: $type:ty ),+); $( $aggregation_type:expr ),*)) => ( $crate::__define_stat!( $prefix; $name: dynamic_timeseries( $key, ($( $placeholder: $type ),+); $( $aggregation_type ),* ; ) ); ); ($prefix:expr; $name:ident: dynamic_timeseries($key:expr, ($( $placeholder:ident: $type:ty ),+); $( $aggregation_type:expr ),* ; $( $interval:expr ),*)) => ( thread_local! { pub static $name: DynamicStat<($( $type, )+), BoxTimeseries> = { $crate::__define_key_generator!( __key_generator($prefix, $key; $( $placeholder: $type ),+) ); fn __stat_generator(key: &str) -> BoxTimeseries { TL_STATS.with(|stats| { stats.create_timeseries(key, &[$( $aggregation_type ),*], &[$( $interval ),*]) }) } DynamicStat::new(__key_generator, __stat_generator) }; } ); ($prefix:expr; $name:ident: dynamic_histogram($key:expr, ($( $placeholder:ident: $type:ty ),+); $bucket_width:expr, $min:expr, $max:expr $(, $aggregation_type:expr )* $(; P $percentile:expr )*)) => ( thread_local! { pub static $name: DynamicStat<($( $type, )+), BoxHistogram> = { $crate::__define_key_generator!( __key_generator($prefix, $key; $( $placeholder: $type ),+) ); fn __stat_generator(key: &str) -> BoxHistogram { TL_STATS.with(|stats| { stats.create_histogram(key, &[$( $aggregation_type ),*], BucketConfig { width: $bucket_width, min: $min, max: $max, }, &[$( $percentile ),*]) }) } DynamicStat::new(__key_generator, __stat_generator) }; } ); } #[doc(hidden)] #[macro_export] macro_rules! __create_stat_key { ($prefix:expr, $key:expr) => {{ use std::borrow::Cow; if $prefix.is_empty() { Cow::Borrowed($key) } else { Cow::Owned(format!("{}.{}", $prefix, $key)) } }}; } /// Define a group of stats with dynamic names all parameterized by the same set of parameters. /// The intention is that when setting up a structure for some entity with associated stats, then /// the type produced by this macro can be included in that structure, and initialized with the /// appropriate name(s). This is more efficient than using single static "dynamic_" versions of /// the counters. /// /// ``` /// use stats::prelude::*; /// /// define_stats_struct! { /// // struct name, key prefix template, key template params /// MyThingStat("things.{}.{}", mything_name: String, mything_idx: usize), /// cache_miss: counter() // default name from the field /// } /// /// struct MyThing { /// stats: MyThingStat, /// } /// /// impl MyThing { /// fn new(somename: String, someidx: usize) -> Self { /// MyThing { /// stats: MyThingStat::new(somename, someidx), /// //... /// } /// } /// } /// # /// # fn main() {} /// ``` #[macro_export] macro_rules! define_stats_struct { // Handle trailing comma ($name:ident ($key:expr, $($pr_name:ident: $pr_type:ty),*) , $( $stat_name:ident: $stat_type:tt($( $params:tt )*) , )+) => { define_stats_struct!($name ( $key, $($pr_name: $pr_type),*), $($stat_name: $stat_type($($params)*)),* ); }; // Handle no params ($name:ident ($key:expr) , $( $stat_name:ident: $stat_type:tt($( $params:tt )*) ),*) => { define_stats_struct!($name ( $key, ), $($stat_name: $stat_type($($params)*)),* ); }; ($name:ident ($key:expr) , $( $stat_name:ident: $stat_type:tt($( $params:tt )*) , )+) => { define_stats_struct!($name ( $key, ), $($stat_name: $stat_type($($params)*)),* ); }; // Define struct and its methods. ($name:ident ($key:expr, $($pr_name:ident: $pr_type:ty),*) , $( $stat_name:ident: $stat_type:tt($( $params:tt )*) ),*) => { #[allow(missing_docs)] pub struct $name { $(pub $stat_name: $crate::__struct_field_type!($stat_type), )* } impl $name { #[allow(unused_imports, missing_docs)] pub fn new($($pr_name: $pr_type),*) -> $name { use $crate::macros::common_macro_prelude::*; lazy_static! { static ref STATS_MAP: Arc<ThreadMap<BoxStatsManager>> = create_map(); } thread_local! { static TL_STATS: PerThread<BoxStatsManager> = STATS_MAP.register(create_stats_manager()); } let prefix = format!($key, $($pr_name),*); $name { $($stat_name: $crate::__struct_field_init!(prefix, $stat_name, $stat_type, $($params)*)),* } } } impl std::fmt::Debug for $name { fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(fmt, "<{}>", stringify!($name)) } } } } #[macro_export] #[doc(hidden)] macro_rules! __struct_field_type { (singleton_counter) => { $crate::macros::common_macro_prelude::BoxSingletonCounter }; (counter) => { $crate::macros::common_macro_prelude::BoxCounter }; (timeseries) => { $crate::macros::common_macro_prelude::BoxTimeseries }; (histogram) => { $crate::macros::common_macro_prelude::BoxHistogram }; } #[macro_export] #[doc(hidden)] macro_rules! __struct_field_init { ($prefix:expr, $name:ident, singleton_counter, ) => { $crate::__struct_field_init! ($prefix, $name, singleton_counter, stringify!($name)) }; ($prefix:expr, $name:ident, singleton_counter, $key:expr) => { $crate::__struct_field_init! ($prefix, $name, singleton_counter, $key ; ) }; ($prefix:expr, $name:ident, singleton_counter, $key:expr ; ) => {{ let key = format!("{}.{}", $prefix, $key); create_singleton_counter(key) }}; ($prefix:expr, $name:ident, counter, ) => { $crate::__struct_field_init! ($prefix, $name, counter, stringify!($name)) }; ($prefix:expr, $name:ident, counter, $key:expr) => { $crate::__struct_field_init! ($prefix, $name, counter, $key ; ) }; ($prefix:expr, $name:ident, counter, $key:expr ; ) => {{ let key = format!("{}.{}", $prefix, $key); TL_STATS.with(|stats| { stats.create_counter(&key) }) }}; ($prefix:expr, $name:ident, timeseries, $( $aggregation_type:expr ),+) => { $crate::__struct_field_init! ($prefix, $name, timeseries, stringify!($name) ; $($aggregation_type),*) }; ($prefix:expr, $name:ident, timeseries, $key:expr ; $( $aggregation_type:expr ),* ) => {{ $crate::__struct_field_init! ($prefix, $name, timeseries, $key ; $($aggregation_type),* ;) }}; ($prefix:expr, $name:ident, timeseries, $key:expr ; $( $aggregation_type:expr ),* ; $( $interval:expr ),* ) => {{ let key = format!("{}.{}", $prefix, $key); TL_STATS.with(|stats| { stats.create_timeseries(&key, &[$( $aggregation_type ),*], &[$( $interval),*]) }) }}; ($prefix:expr, $name:ident, histogram, $bucket_width:expr, $min:expr, $max:expr $(, $aggregation_type:expr)* $(; P $percentile:expr )*) => { $crate::__struct_field_init! ($prefix, $name, histogram, stringify!($name) ; $bucket_width, $min, $max $(, $aggregation_type)* $(; P $percentile)* ) }; ($prefix:expr, $name:ident, histogram, $key:expr ; $bucket_width:expr, $min:expr, $max:expr $(, $aggregation_type:expr)* $(; P $percentile:expr )*) => {{ let key = format!("{}.{}", $prefix, $key); TL_STATS.with(|stats| { stats.create_histogram( &key, &[$( $aggregation_type ),*], BucketConfig { width: $bucket_width, min: $min, max: $max, }, &[$( $percentile ),*]) }) }}; }
use super::*; #[test] fn greet_yields_greeting() { // given a greeter let greeter = greet; // when it is invoked let result = greeter(); // then it should return the appropriate greeting let expected_greeting = match 0_usize.count_zeros() { 32 => "Hello, 32-bit world!".to_owned(), 64 => "Hello, 64-bit world!".to_owned(), _ => unreachable!(), }; assert!(result == expected_greeting); }
#[doc = "Reader of register SM_SHIFTCTRL"] pub type R = crate::R<u32, super::SM_SHIFTCTRL>; #[doc = "Writer for register SM_SHIFTCTRL"] pub type W = crate::W<u32, super::SM_SHIFTCTRL>; #[doc = "Register SM_SHIFTCTRL `reset()`'s with value 0x000c_0000"] impl crate::ResetValue for super::SM_SHIFTCTRL { type Type = u32; #[inline(always)] fn reset_value() -> Self::Type { 0x000c_0000 } } #[doc = "Reader of field `FJOIN_RX`"] pub type FJOIN_RX_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FJOIN_RX`"] pub struct FJOIN_RX_W<'a> { w: &'a mut W, } impl<'a> FJOIN_RX_W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits = (self.w.bits & !(0x01 << 31)) | (((value as u32) & 0x01) << 31); self.w } } #[doc = "Reader of field `FJOIN_TX`"] pub type FJOIN_TX_R = crate::R<bool, bool>; #[doc = "Write proxy for field `FJOIN_TX`"] pub struct FJOIN_TX_W<'a> { w: &'a mut W, } impl<'a> FJOIN_TX_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 << 30)) | (((value as u32) & 0x01) << 30); self.w } } #[doc = "Reader of field `PULL_THRESH`"] pub type PULL_THRESH_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PULL_THRESH`"] pub struct PULL_THRESH_W<'a> { w: &'a mut W, } impl<'a> PULL_THRESH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 25)) | (((value as u32) & 0x1f) << 25); self.w } } #[doc = "Reader of field `PUSH_THRESH`"] pub type PUSH_THRESH_R = crate::R<u8, u8>; #[doc = "Write proxy for field `PUSH_THRESH`"] pub struct PUSH_THRESH_W<'a> { w: &'a mut W, } impl<'a> PUSH_THRESH_W<'a> { #[doc = r"Writes raw bits to the field"] #[inline(always)] pub unsafe fn bits(self, value: u8) -> &'a mut W { self.w.bits = (self.w.bits & !(0x1f << 20)) | (((value as u32) & 0x1f) << 20); self.w } } #[doc = "Reader of field `OUT_SHIFTDIR`"] pub type OUT_SHIFTDIR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `OUT_SHIFTDIR`"] pub struct OUT_SHIFTDIR_W<'a> { w: &'a mut W, } impl<'a> OUT_SHIFTDIR_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 `IN_SHIFTDIR`"] pub type IN_SHIFTDIR_R = crate::R<bool, bool>; #[doc = "Write proxy for field `IN_SHIFTDIR`"] pub struct IN_SHIFTDIR_W<'a> { w: &'a mut W, } impl<'a> IN_SHIFTDIR_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 `AUTOPULL`"] pub type AUTOPULL_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AUTOPULL`"] pub struct AUTOPULL_W<'a> { w: &'a mut W, } impl<'a> AUTOPULL_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 `AUTOPUSH`"] pub type AUTOPUSH_R = crate::R<bool, bool>; #[doc = "Write proxy for field `AUTOPUSH`"] pub struct AUTOPUSH_W<'a> { w: &'a mut W, } impl<'a> AUTOPUSH_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 } } impl R { #[doc = "Bit 31 - When 1, RX FIFO steals the TX FIFO's storage, and becomes twice as deep.\\n TX FIFO is disabled as a result (always reads as both full and empty).\\n FIFOs are flushed when this bit is changed."] #[inline(always)] pub fn fjoin_rx(&self) -> FJOIN_RX_R { FJOIN_RX_R::new(((self.bits >> 31) & 0x01) != 0) } #[doc = "Bit 30 - When 1, TX FIFO steals the RX FIFO's storage, and becomes twice as deep.\\n RX FIFO is disabled as a result (always reads as both full and empty).\\n FIFOs are flushed when this bit is changed."] #[inline(always)] pub fn fjoin_tx(&self) -> FJOIN_TX_R { FJOIN_TX_R::new(((self.bits >> 30) & 0x01) != 0) } #[doc = "Bits 25:29 - Number of bits shifted out of OSR before autopull, or conditional pull (PULL IFEMPTY), will take place.\\n Write 0 for value of 32."] #[inline(always)] pub fn pull_thresh(&self) -> PULL_THRESH_R { PULL_THRESH_R::new(((self.bits >> 25) & 0x1f) as u8) } #[doc = "Bits 20:24 - Number of bits shifted into ISR before autopush, or conditional push (PUSH IFFULL), will take place.\\n Write 0 for value of 32."] #[inline(always)] pub fn push_thresh(&self) -> PUSH_THRESH_R { PUSH_THRESH_R::new(((self.bits >> 20) & 0x1f) as u8) } #[doc = "Bit 19 - 1 = shift out of output shift register to right. 0 = to left."] #[inline(always)] pub fn out_shiftdir(&self) -> OUT_SHIFTDIR_R { OUT_SHIFTDIR_R::new(((self.bits >> 19) & 0x01) != 0) } #[doc = "Bit 18 - 1 = shift input shift register to right (data enters from left). 0 = to left."] #[inline(always)] pub fn in_shiftdir(&self) -> IN_SHIFTDIR_R { IN_SHIFTDIR_R::new(((self.bits >> 18) & 0x01) != 0) } #[doc = "Bit 17 - Pull automatically when the output shift register is emptied, i.e. on or following an OUT instruction which causes the output shift counter to reach or exceed PULL_THRESH."] #[inline(always)] pub fn autopull(&self) -> AUTOPULL_R { AUTOPULL_R::new(((self.bits >> 17) & 0x01) != 0) } #[doc = "Bit 16 - Push automatically when the input shift register is filled, i.e. on an IN instruction which causes the input shift counter to reach or exceed PUSH_THRESH."] #[inline(always)] pub fn autopush(&self) -> AUTOPUSH_R { AUTOPUSH_R::new(((self.bits >> 16) & 0x01) != 0) } } impl W { #[doc = "Bit 31 - When 1, RX FIFO steals the TX FIFO's storage, and becomes twice as deep.\\n TX FIFO is disabled as a result (always reads as both full and empty).\\n FIFOs are flushed when this bit is changed."] #[inline(always)] pub fn fjoin_rx(&mut self) -> FJOIN_RX_W { FJOIN_RX_W { w: self } } #[doc = "Bit 30 - When 1, TX FIFO steals the RX FIFO's storage, and becomes twice as deep.\\n RX FIFO is disabled as a result (always reads as both full and empty).\\n FIFOs are flushed when this bit is changed."] #[inline(always)] pub fn fjoin_tx(&mut self) -> FJOIN_TX_W { FJOIN_TX_W { w: self } } #[doc = "Bits 25:29 - Number of bits shifted out of OSR before autopull, or conditional pull (PULL IFEMPTY), will take place.\\n Write 0 for value of 32."] #[inline(always)] pub fn pull_thresh(&mut self) -> PULL_THRESH_W { PULL_THRESH_W { w: self } } #[doc = "Bits 20:24 - Number of bits shifted into ISR before autopush, or conditional push (PUSH IFFULL), will take place.\\n Write 0 for value of 32."] #[inline(always)] pub fn push_thresh(&mut self) -> PUSH_THRESH_W { PUSH_THRESH_W { w: self } } #[doc = "Bit 19 - 1 = shift out of output shift register to right. 0 = to left."] #[inline(always)] pub fn out_shiftdir(&mut self) -> OUT_SHIFTDIR_W { OUT_SHIFTDIR_W { w: self } } #[doc = "Bit 18 - 1 = shift input shift register to right (data enters from left). 0 = to left."] #[inline(always)] pub fn in_shiftdir(&mut self) -> IN_SHIFTDIR_W { IN_SHIFTDIR_W { w: self } } #[doc = "Bit 17 - Pull automatically when the output shift register is emptied, i.e. on or following an OUT instruction which causes the output shift counter to reach or exceed PULL_THRESH."] #[inline(always)] pub fn autopull(&mut self) -> AUTOPULL_W { AUTOPULL_W { w: self } } #[doc = "Bit 16 - Push automatically when the input shift register is filled, i.e. on an IN instruction which causes the input shift counter to reach or exceed PUSH_THRESH."] #[inline(always)] pub fn autopush(&mut self) -> AUTOPUSH_W { AUTOPUSH_W { w: self } } }
#[doc = "Register `HASH_CSR48` reader"] pub type R = crate::R<HASH_CSR48_SPEC>; #[doc = "Register `HASH_CSR48` writer"] pub type W = crate::W<HASH_CSR48_SPEC>; #[doc = "Field `CS48` reader - CS48"] pub type CS48_R = crate::FieldReader<u32>; #[doc = "Field `CS48` writer - CS48"] pub type CS48_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 32, O, u32>; impl R { #[doc = "Bits 0:31 - CS48"] #[inline(always)] pub fn cs48(&self) -> CS48_R { CS48_R::new(self.bits) } } impl W { #[doc = "Bits 0:31 - CS48"] #[inline(always)] #[must_use] pub fn cs48(&mut self) -> CS48_W<HASH_CSR48_SPEC, 0> { CS48_W::new(self) } #[doc = "Writes raw bits to the register."] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } } #[doc = "HASH context swap registers\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`hash_csr48::R`](R). You can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero) this register using [`hash_csr48::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct HASH_CSR48_SPEC; impl crate::RegisterSpec for HASH_CSR48_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`hash_csr48::R`](R) reader structure"] impl crate::Readable for HASH_CSR48_SPEC {} #[doc = "`write(|w| ..)` method takes [`hash_csr48::W`](W) writer structure"] impl crate::Writable for HASH_CSR48_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets HASH_CSR48 to value 0"] impl crate::Resettable for HASH_CSR48_SPEC { const RESET_VALUE: Self::Ux = 0; }