text
stringlengths
8
4.13M
pub use glyph_brush::HorizontalAlign as HAlign; pub use glyph_brush::VerticalAlign as VAlign; /// Defines an object's alignment. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] pub struct Alignment { pub horizontal: HAlign, pub vertical: VAlign, } impl From<HAlign> for Alignment { #[inline] fn from(horizontal: HAlign) -> Self { Alignment { horizontal, vertical: VAlign::Top, } } } impl From<VAlign> for Alignment { #[inline] fn from(vertical: VAlign) -> Self { Alignment { horizontal: HAlign::Left, vertical, } } } impl Default for Alignment { fn default() -> Self { Alignment { horizontal: HAlign::Left, vertical: VAlign::Top, } } } impl_from_unit_default!(Alignment); /* TODO: pull request this stuff, or make a wrapper /// Horizontal alignment. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum HAlign { Left, Center, Right, } impl HAlign { #[inline] pub fn flip(self) -> Self { match self { HAlign::Left => HAlign::Right, HAlign::Center => HAlign::Center, HAlign::Right => HAlign::Left, } } #[inline] pub fn value(self) -> f32 { match self { HAlign::Left => 0.0, HAlign::Center => 0.5, HAlign::Right => 1.0, } } } impl Default for HAlign { #[inline] fn default() -> Self { HAlign::Left } } /// Vertical alignment. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] pub enum VAlign { Top, Center, Bottom, } impl VAlign { #[inline] pub fn flip(self) -> Self { match self { VAlign::Top => VAlign::Bottom, VAlign::Center => VAlign::Center, VAlign::Bottom => VAlign::Top, } } #[inline] pub fn value(self) -> f32 { match self { VAlign::Top => 0.0, VAlign::Center => 0.5, VAlign::Bottom => 1.0, } } } impl Default for VAlign { #[inline] fn default() -> Self { VAlign::Top } } */
use crate::core::alloc; use crate::core::bigarray; use crate::core::mlvalues; use crate::core::mlvalues::empty_list; use crate::error::Error; use crate::tag::Tag; use std::marker::PhantomData; use std::{mem, ptr, slice}; use crate::value::{Size, Value}; /// OCaml Tuple type pub struct Tuple(Value, Size); impl From<Tuple> for Value { fn from(t: Tuple) -> Value { t.0 } } impl From<Value> for Tuple { fn from(v: Value) -> Tuple { let len = v.array_length(); Tuple(v, len) } } impl<'a, V: crate::ToValue> From<&'a [V]> for Tuple { fn from(a: &'a [V]) -> Tuple { Tuple( caml_frame!(|t| { t.0 = unsafe { alloc::caml_alloc_tuple(a.len()) }; for (n, i) in a.iter().enumerate() { t.store_field(n, i.to_value()); } t }), a.len(), ) } } impl Tuple { /// Create a new tuple pub fn new(n: Size) -> Tuple { let x = caml_frame!(|x| { x.0 = unsafe { alloc::caml_alloc_tuple(n) }; x }); Tuple(x, n) } /// Tuple length pub fn len(&self) -> Size { self.1 } pub fn is_empty(&self) -> bool { self.len() == 0 } /// Set tuple index pub fn set(&mut self, i: Size, v: Value) -> Result<(), Error> { if i < self.1 { self.0.store_field(i, v); Ok(()) } else { Err(Error::OutOfBounds) } } /// Get tuple index pub fn get(&self, i: Size) -> Result<Value, Error> { if i < self.1 { Ok(self.0.field(i)) } else { Err(Error::OutOfBounds) } } } /// OCaml Array type pub struct Array(Value); impl From<Array> for Value { fn from(t: Array) -> Value { t.0 } } impl From<Value> for Array { fn from(v: Value) -> Array { Array(v) } } impl<'a, V: crate::ToValue> From<&'a [V]> for Array { fn from(a: &'a [V]) -> Array { Array(caml_frame!(|x| { x.0 = unsafe { alloc::caml_alloc(a.len(), Tag::Zero.into()) }; for (n, i) in a.iter().enumerate() { x.store_field(n, i.to_value()); } x })) } } impl crate::ToValue for Array { fn to_value(&self) -> Value { self.0.to_value() } } impl Array { /// Create a new array of the given size pub fn new(n: Size) -> Array { let x = caml_frame!(|x| { x.0 = unsafe { alloc::caml_alloc(n, Tag::Zero.into()) }; x }); Array(x) } /// Check if Array contains only doubles pub fn is_double_array(&self) -> bool { unsafe { alloc::caml_is_double_array(self.0.value()) == 1 } } /// Array length pub fn len(&self) -> Size { unsafe { mlvalues::caml_array_length(self.0.value()) } } pub fn is_empty(&self) -> bool { self.len() == 0 } /// Set value to double array pub fn set_double(&mut self, i: Size, f: f64) -> Result<(), Error> { if i < self.len() { if !self.is_double_array() { return Err(Error::NotDoubleArray); } unsafe { let ptr = self.0.ptr_val::<f64>().add(i) as *mut f64; *ptr = f; }; Ok(()) } else { Err(Error::OutOfBounds) } } /// Get a value from a double array pub fn get_double(&mut self, i: Size) -> Result<f64, Error> { if i < self.len() { if !self.is_double_array() { return Err(Error::NotDoubleArray); } Ok(unsafe { self.get_double_unchecked(i) }) } else { Err(Error::OutOfBounds) } } /// Get a value from a double array without checking if the array is actually a double array unsafe fn get_double_unchecked(&mut self, i: Size) -> f64 { *self.0.ptr_val::<f64>().add(i) } /// Set array index pub fn set(&mut self, i: Size, v: Value) -> Result<(), Error> { if i < self.len() { self.0.store_field(i, v); Ok(()) } else { Err(Error::OutOfBounds) } } /// Get array index pub fn get(&self, i: Size) -> Result<Value, Error> { if i < self.len() { self.get_unchecked(i) } else { Err(Error::OutOfBounds) } } /// Get array index without bounds checking pub fn get_unchecked(&self, i: Size) -> Result<Value, Error> { Ok(self.0.field(i)) } } /// OCaml list type pub struct List(Value); impl From<List> for Value { fn from(t: List) -> Value { t.0 } } impl From<Value> for List { fn from(v: Value) -> List { List(v) } } impl<'a, V: crate::ToValue> From<&'a [V]> for List { fn from(a: &'a [V]) -> List { crate::list!(_ a.iter().map(|x| x.to_value())) } } impl crate::ToValue for List { fn to_value(&self) -> Value { self.0.to_value() } } impl Default for List { fn default() -> Self { List::new() } } impl List { /// Create a new OCaml list pub fn new() -> List { List(caml_frame!(|x| { x })) } /// Returns the number of items in `self` pub fn len(&self) -> Size { let mut length = 0; let mut tmp = self.0.clone(); while tmp.0 != empty_list() { tmp = tmp.field(1); length += 1; } length } /// Returns true when the list is empty pub fn is_empty(&self) -> bool { let item: usize = (self.0).0; item == empty_list() } /// Add an element to the front of the list pub fn push_hd(&mut self, v: Value) { let tmp = caml_frame!(|x, tmp| { x.0 = (self.0).0; tmp = Value::alloc_small(2, Tag::Zero); tmp.store_field(0, v); tmp.store_field(1, x); tmp }); self.0 = tmp; } /// List head pub fn hd(&self) -> Option<Value> { if self.is_empty() { return None; } Some(self.0.field(0)) } /// List tail pub fn tl(&self) -> Value { self.0.field(1) } /// List as vector pub fn to_vec(&self) -> Vec<Value> { let mut vec: Vec<Value> = Vec::new(); let mut tmp = self.0.clone(); while tmp.0 != empty_list() { let val = tmp.field(0); vec.push(val); tmp = tmp.field(1); } vec } } /// OCaml String type pub struct Str(Value); impl From<Str> for Value { fn from(t: Str) -> Value { t.0 } } impl<'a> From<&'a str> for Str { fn from(s: &'a str) -> Str { unsafe { let len = s.len(); let x = caml_frame!(|x| { x.0 = alloc::caml_alloc_string(len); let ptr = string_val!(x.0) as *mut u8; ptr::copy(s.as_ptr(), ptr, len); x }); Str(x) } } } impl<'a> From<&'a [u8]> for Str { fn from(s: &'a [u8]) -> Str { unsafe { let len = s.len(); let x = caml_frame!(|x| { x.0 = alloc::caml_alloc_string(len); let ptr = string_val!(x.0) as *mut u8; ptr::copy(s.as_ptr(), ptr, len); x }); Str(x) } } } impl From<Value> for Str { fn from(v: Value) -> Str { if v.tag() != Tag::String { panic!("Invalid string value, got tag {:?}", v.tag()); } else { Str(v) } } } impl crate::ToValue for Str { fn to_value(&self) -> Value { self.0.to_value() } } impl Str { /// Create a new string of a given length pub fn new(n: Size) -> Str { Str(caml_frame!(|s| { s.0 = unsafe { alloc::caml_alloc_string(n) }; s })) } /// String length pub fn len(&self) -> Size { unsafe { mlvalues::caml_string_length(self.0.value()) } } /// Check if a string is empty pub fn is_empty(&self) -> bool { self.len() == 0 } /// Access OCaml string as `&str` pub fn as_str(&self) -> &str { let ptr = string_val!((self.0).0); unsafe { let slice = ::std::slice::from_raw_parts(ptr, self.len()); ::std::str::from_utf8_unchecked(slice) } } /// Access OCaml string as `&mut str` pub fn as_str_mut(&mut self) -> &mut str { let ptr = string_val!((self.0).0) as *mut u8; unsafe { let slice = ::std::slice::from_raw_parts_mut(ptr, self.len()); ::std::str::from_utf8_unchecked_mut(slice) } } /// Access OCaml string as `&[u8]` pub fn data(&self) -> &[u8] { let ptr = string_val!((self.0).0); unsafe { ::std::slice::from_raw_parts(ptr, self.len()) } } /// Access OCaml string as `&mut [u8]` pub fn data_mut(&mut self) -> &mut [u8] { let ptr = string_val!((self.0).0) as *mut u8; unsafe { ::std::slice::from_raw_parts_mut(ptr, self.len()) } } } pub trait BigarrayKind { type T; fn kind() -> i32; } macro_rules! make_kind { ($t:ty, $k:ident) => { impl BigarrayKind for $t { type T = $t; fn kind() -> i32 { bigarray::Kind::$k as i32 } } }; } make_kind!(u8, UINT8); make_kind!(i8, SINT8); make_kind!(u16, UINT16); make_kind!(i16, SINT16); make_kind!(f32, FLOAT32); make_kind!(f64, FLOAT64); make_kind!(i64, INT64); make_kind!(i32, INT32); make_kind!(char, CHAR); /// OCaml Bigarray.Array1 type pub struct Array1<T>(Value, PhantomData<T>); impl<T: BigarrayKind> From<Array1<T>> for Value { fn from(t: Array1<T>) -> Value { t.0 } } impl<T: BigarrayKind> From<Value> for Array1<T> { fn from(v: Value) -> Array1<T> { Array1(v, PhantomData) } } impl<T: BigarrayKind> crate::ToValue for Array1<T> { fn to_value(&self) -> Value { self.0.to_value() } } impl<T: Copy + BigarrayKind> From<&[T]> for Array1<T> { fn from(x: &[T]) -> Array1<T> { let mut arr = Array1::<T>::create(x.len()); let data = arr.data_mut(); for (n, i) in x.iter().enumerate() { data[n] = *i; } arr } } impl<T: BigarrayKind> Array1<T> { /// Array1::of_slice is used to convert from a slice to OCaml Bigarray, /// the `data` parameter must outlive the resulting bigarray or there is /// no guarantee the data will be valid. Use `Array1::from` to clone the /// contents of a slice. pub fn of_slice(data: &mut [T]) -> Array1<T> { let x = caml_frame!(|x| { x.0 = unsafe { bigarray::caml_ba_alloc_dims( T::kind() | bigarray::Managed::EXTERNAL as i32, 1, data.as_mut_ptr() as bigarray::Data, data.len() as i32, ) }; x }); Array1(x, PhantomData) } /// Create a new OCaml `Bigarray.Array1` with the given type and size pub fn create(n: Size) -> Array1<T> { let x = caml_frame!(|x| { let data = unsafe { bigarray::malloc(n * mem::size_of::<T>()) }; x.0 = unsafe { bigarray::caml_ba_alloc_dims( T::kind() | bigarray::Managed::MANAGED as i32, 1, data, n as mlvalues::Intnat, ) }; x }); Array1(x, PhantomData) } /// Returns the number of items in `self` pub fn len(&self) -> Size { let ba = self.0.custom_ptr_val::<bigarray::Bigarray>(); unsafe { (*ba).dim as usize } } /// Returns true when `self.len() == 0` pub fn is_empty(&self) -> bool { self.len() == 0 } /// Get underlying data as Rust slice pub fn data(&self) -> &[T] { let ba = self.0.custom_ptr_val::<bigarray::Bigarray>(); unsafe { slice::from_raw_parts((*ba).data as *const T, self.len()) } } /// Get underlying data as mutable Rust slice pub fn data_mut(&mut self) -> &mut [T] { let ba = self.0.custom_ptr_val::<bigarray::Bigarray>(); unsafe { slice::from_raw_parts_mut((*ba).data as *mut T, self.len()) } } }
use std::{ collections::HashMap, env::consts::OS, time::{Duration, Instant}, }; use bytes::Bytes; use futures_util::{future::IntoStream, FutureExt}; use governor::{ clock::MonotonicClock, middleware::NoOpMiddleware, state::InMemoryState, Quota, RateLimiter, }; use http::{header::HeaderValue, Uri}; use hyper::{ client::{HttpConnector, ResponseFuture}, header::USER_AGENT, Body, Client, HeaderMap, Request, Response, StatusCode, }; use hyper_proxy::{Intercept, Proxy, ProxyConnector}; use hyper_rustls::{HttpsConnector, HttpsConnectorBuilder}; use nonzero_ext::nonzero; use once_cell::sync::OnceCell; use parking_lot::Mutex; use sysinfo::{System, SystemExt}; use thiserror::Error; use url::Url; use crate::{ date::Date, version::{spotify_version, FALLBACK_USER_AGENT, VERSION_STRING}, Error, }; // The 30 seconds interval is documented by Spotify, but the calls per interval // is a guesstimate and probably subject to licensing (purchasing extra calls) // and may change at any time. pub const RATE_LIMIT_INTERVAL: Duration = Duration::from_secs(30); pub const RATE_LIMIT_MAX_WAIT: Duration = Duration::from_secs(10); pub const RATE_LIMIT_CALLS_PER_INTERVAL: u32 = 300; #[derive(Debug, Error)] pub enum HttpClientError { #[error("Response status code: {0}")] StatusCode(hyper::StatusCode), } impl From<HttpClientError> for Error { fn from(err: HttpClientError) -> Self { match err { HttpClientError::StatusCode(code) => { // not exhaustive, but what reasonably could be expected match code { StatusCode::GATEWAY_TIMEOUT | StatusCode::REQUEST_TIMEOUT => { Error::deadline_exceeded(err) } StatusCode::GONE | StatusCode::NOT_FOUND | StatusCode::MOVED_PERMANENTLY | StatusCode::PERMANENT_REDIRECT | StatusCode::TEMPORARY_REDIRECT => Error::not_found(err), StatusCode::FORBIDDEN | StatusCode::PAYMENT_REQUIRED => { Error::permission_denied(err) } StatusCode::NETWORK_AUTHENTICATION_REQUIRED | StatusCode::PROXY_AUTHENTICATION_REQUIRED | StatusCode::UNAUTHORIZED => Error::unauthenticated(err), StatusCode::EXPECTATION_FAILED | StatusCode::PRECONDITION_FAILED | StatusCode::PRECONDITION_REQUIRED => Error::failed_precondition(err), StatusCode::RANGE_NOT_SATISFIABLE => Error::out_of_range(err), StatusCode::INTERNAL_SERVER_ERROR | StatusCode::MISDIRECTED_REQUEST | StatusCode::SERVICE_UNAVAILABLE | StatusCode::UNAVAILABLE_FOR_LEGAL_REASONS => Error::unavailable(err), StatusCode::BAD_REQUEST | StatusCode::HTTP_VERSION_NOT_SUPPORTED | StatusCode::LENGTH_REQUIRED | StatusCode::METHOD_NOT_ALLOWED | StatusCode::NOT_ACCEPTABLE | StatusCode::PAYLOAD_TOO_LARGE | StatusCode::REQUEST_HEADER_FIELDS_TOO_LARGE | StatusCode::UNSUPPORTED_MEDIA_TYPE | StatusCode::URI_TOO_LONG => Error::invalid_argument(err), StatusCode::TOO_MANY_REQUESTS => Error::resource_exhausted(err), StatusCode::NOT_IMPLEMENTED => Error::unimplemented(err), _ => Error::unknown(err), } } } } } type HyperClient = Client<ProxyConnector<HttpsConnector<HttpConnector>>, Body>; pub struct HttpClient { user_agent: HeaderValue, proxy_url: Option<Url>, hyper_client: OnceCell<HyperClient>, // while the DashMap variant is more performant, our level of concurrency // is pretty low so we can save pulling in that extra dependency rate_limiter: RateLimiter<String, Mutex<HashMap<String, InMemoryState>>, MonotonicClock, NoOpMiddleware>, } impl HttpClient { pub fn new(proxy_url: Option<&Url>) -> Self { let zero_str = String::from("0"); let os_version = System::new() .os_version() .unwrap_or_else(|| zero_str.clone()); let (spotify_platform, os_version) = match OS { "android" => ("Android", os_version), "ios" => ("iOS", os_version), "macos" => ("OSX", zero_str), "windows" => ("Win32", zero_str), _ => ("Linux", zero_str), }; let user_agent_str = &format!( "Spotify/{} {}/{} ({})", spotify_version(), spotify_platform, os_version, VERSION_STRING ); let user_agent = HeaderValue::from_str(user_agent_str).unwrap_or_else(|err| { error!("Invalid user agent <{}>: {}", user_agent_str, err); HeaderValue::from_static(FALLBACK_USER_AGENT) }); let replenish_interval_ns = RATE_LIMIT_INTERVAL.as_nanos() / RATE_LIMIT_CALLS_PER_INTERVAL as u128; let quota = Quota::with_period(Duration::from_nanos(replenish_interval_ns as u64)) .expect("replenish interval should be valid") .allow_burst(nonzero![RATE_LIMIT_CALLS_PER_INTERVAL]); let rate_limiter = RateLimiter::keyed(quota); Self { user_agent, proxy_url: proxy_url.cloned(), hyper_client: OnceCell::new(), rate_limiter, } } fn try_create_hyper_client(proxy_url: Option<&Url>) -> Result<HyperClient, Error> { // configuring TLS is expensive and should be done once per process let https_connector = HttpsConnectorBuilder::new() .with_native_roots() .https_or_http() .enable_http1() .enable_http2() .build(); // When not using a proxy a dummy proxy is configured that will not intercept any traffic. // This prevents needing to carry the Client Connector generics through the whole project let proxy = match &proxy_url { Some(proxy_url) => Proxy::new(Intercept::All, proxy_url.to_string().parse()?), None => Proxy::new(Intercept::None, Uri::from_static("0.0.0.0")), }; let proxy_connector = ProxyConnector::from_proxy(https_connector, proxy)?; let client = Client::builder() .http2_adaptive_window(true) .build(proxy_connector); Ok(client) } fn hyper_client(&self) -> Result<&HyperClient, Error> { self.hyper_client .get_or_try_init(|| Self::try_create_hyper_client(self.proxy_url.as_ref())) } pub async fn request(&self, req: Request<Body>) -> Result<Response<Body>, Error> { debug!("Requesting {}", req.uri().to_string()); // `Request` does not implement `Clone` because its `Body` may be a single-shot stream. // As correct as that may be technically, we now need all this boilerplate to clone it // ourselves, as any `Request` is moved in the loop. let (parts, body) = req.into_parts(); let body_as_bytes = hyper::body::to_bytes(body) .await .unwrap_or_else(|_| Bytes::new()); loop { let mut req = Request::builder() .method(parts.method.clone()) .uri(parts.uri.clone()) .version(parts.version) .body(Body::from(body_as_bytes.clone()))?; *req.headers_mut() = parts.headers.clone(); let request = self.request_fut(req)?; let response = request.await; if let Ok(response) = &response { let code = response.status(); if code == StatusCode::TOO_MANY_REQUESTS { if let Some(duration) = Self::get_retry_after(response.headers()) { warn!( "Rate limited by service, retrying in {} seconds...", duration.as_secs() ); tokio::time::sleep(duration).await; continue; } } if code != StatusCode::OK { return Err(HttpClientError::StatusCode(code).into()); } } return Ok(response?); } } pub async fn request_body(&self, req: Request<Body>) -> Result<Bytes, Error> { let response = self.request(req).await?; Ok(hyper::body::to_bytes(response.into_body()).await?) } pub fn request_stream(&self, req: Request<Body>) -> Result<IntoStream<ResponseFuture>, Error> { Ok(self.request_fut(req)?.into_stream()) } pub fn request_fut(&self, mut req: Request<Body>) -> Result<ResponseFuture, Error> { let headers_mut = req.headers_mut(); headers_mut.insert(USER_AGENT, self.user_agent.clone()); // For rate limiting we cannot *just* depend on Spotify sending us HTTP/429 // Retry-After headers. For example, when there is a service interruption // and HTTP/500 is returned, we don't want to DoS the Spotify infrastructure. let domain = match req.uri().host() { Some(host) => { // strip the prefix from *.domain.tld (assume rate limit is per domain, not subdomain) let mut parts = host .split('.') .map(|s| s.to_string()) .collect::<Vec<String>>(); let n = parts.len().saturating_sub(2); parts.drain(n..).collect() } None => String::from(""), }; self.rate_limiter.check_key(&domain).map_err(|e| { Error::resource_exhausted(format!( "rate limited for at least another {} seconds", e.wait_time_from(Instant::now()).as_secs() )) })?; Ok(self.hyper_client()?.request(req)) } pub fn get_retry_after(headers: &HeaderMap<HeaderValue>) -> Option<Duration> { let now = Date::now_utc().as_timestamp_ms(); let mut retry_after_ms = None; if let Some(header_val) = headers.get("X-RateLimit-Next") { // *.akamaized.net (Akamai) if let Ok(date_str) = header_val.to_str() { if let Ok(target) = Date::from_iso8601(date_str) { retry_after_ms = Some(target.as_timestamp_ms().saturating_sub(now)) } } } else if let Some(header_val) = headers.get("Fastly-RateLimit-Reset") { // *.scdn.co (Fastly) if let Ok(timestamp) = header_val.to_str() { if let Ok(target) = timestamp.parse::<i64>() { retry_after_ms = Some(target.saturating_sub(now)) } } } else if let Some(header_val) = headers.get("Retry-After") { // Generic RFC compliant (including *.spotify.com) if let Ok(retry_after) = header_val.to_str() { if let Ok(duration) = retry_after.parse::<i64>() { retry_after_ms = Some(duration * 1000) } } } if let Some(retry_after) = retry_after_ms { let duration = Duration::from_millis(retry_after as u64); if duration <= RATE_LIMIT_MAX_WAIT { return Some(duration); } else { debug!( "Waiting {} seconds would exceed {} second limit", duration.as_secs(), RATE_LIMIT_MAX_WAIT.as_secs() ); } } None } }
#[cfg(test)] mod tests { use lib::factorial; #[test] fn test_factorial() { let value: u32 = 4; let expected_result: u32 = 24; assert_eq!( expected_result, factorial(value), ); } }
use crate::typing::Type; use std::{ collections::{BTreeMap, BTreeSet}, fmt, }; #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct AttrSetType { pub attrs: BTreeMap<String, Type>, pub rest: Box<Type>, } impl fmt::Display for AttrSetType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("{ ")?; for (name, ty) in self.attrs.iter() { write!(f, "{} = {}; ", name, ty)?; } write!(f, "... = {}; ", self.rest)?; f.write_str("}") } } impl AttrSetType { pub fn union_names<'a>(&'a self, other: &'a Self) -> BTreeSet<&'a String> { self.attrs.keys().chain(other.attrs.keys()).collect() } fn sup(&self, other: &Self) -> Self { let names = self.union_names(other); let attrs = names .iter() .map(|&name| { let t = match (self.attrs.get(name), other.attrs.get(name)) { (Some(t1), Some(t2)) => t1.sup(t2), (Some(t1), None) => t1.sup(&other.rest), (None, Some(t2)) => t2.sup(&self.rest), (None, None) => unreachable!(), }; (name.clone(), t) }) .collect(); Self { attrs, rest: self.rest.sup(&other.rest).into(), } } fn inf(&self, other: &Self) -> Self { let names = self.union_names(other); let attrs = names .iter() .map(|&name| { let t = match (self.attrs.get(name), other.attrs.get(name)) { (Some(t1), Some(t2)) => t1.inf(t2), (Some(t1), None) => t1.inf(&other.rest), (None, Some(t2)) => t2.inf(&self.rest), (None, None) => unreachable!(), }; (name.clone(), t) }) .collect(); Self { attrs, rest: self.rest.inf(&other.rest).into(), } } } #[derive(Debug, Default, Clone, PartialEq, Eq, PartialOrd, Ord)] pub struct AttrSetDomain { attrs: Option<AttrSetType>, } impl AttrSetDomain { pub fn new(attrs: AttrSetType) -> Self { Self { attrs: Some(attrs) } } pub fn is_bottom(&self) -> bool { self.attrs.is_none() } pub fn sup(&self, other: &Self) -> Self { let attrs = match (&self.attrs, &other.attrs) { (Some(a1), Some(a2)) => Some(a1.sup(a2)), (Some(a), _) | (_, Some(a)) => Some(a.clone()), (None, None) => None, }; Self { attrs } } pub fn inf(&self, other: &Self) -> Self { let attrs = match (&self.attrs, &other.attrs) { (Some(a1), Some(a2)) => Some(a1.inf(a2)), (None, _) | (_, None) => None, }; Self { attrs } } pub fn fmt(&self, f: &mut fmt::Formatter, first: bool) -> fmt::Result { match &self.attrs { None => Ok(()), Some(attrs) => { if !first { f.write_str(" ∪ ")?; } write!(f, "{}", attrs) } } } pub fn as_attrs(&self) -> Option<&AttrSetType> { self.attrs.as_ref() } }
use crate::rl::prelude::*; use crate::rl::trainers::q_learning::QFunction; use ndarray::prelude::*; use ndarray_stats::QuantileExt; use std::collections::HashMap; #[derive(Clone)] pub struct QTableAgent { action_space: usize, q_table: HashMap<Vec<i32>, Array1<Reward>>, } impl QTableAgent { pub fn new(action_space: usize) -> Self { Self { action_space, q_table: HashMap::new(), } } fn get_state_vec(&self, state: &State) -> Vec<i32> { state.iter().map(|&x| x.round() as i32).collect() } } impl QFunction for QTableAgent { fn get_action_values(&mut self, state: &State) -> Array1<Reward> { let state_vec = self.get_state_vec(state); if let Some(action_values) = self.q_table.get(&state_vec) { action_values.clone() } else { let new_action_values = Array1::zeros(self.action_space); self.q_table .insert(state_vec.clone(), new_action_values.clone()); new_action_values } } fn update_q_function( &mut self, state: &State, action: &DiscreteAction, reward: &f32, next_state: &State, learning_rate: f32, gamma: f32, ) { let next_rewards = self.get_action_values(next_state); let state_vec = self.get_state_vec(state); if let Some(action_values) = self.q_table.get_mut(&state_vec) { let update = (1. - learning_rate) * action_values[action.0] + learning_rate * (reward + gamma * next_rewards.max().unwrap()); action_values[action.0] = update; } else { let mut action_values = Array1::zeros(self.action_space).map(|x: &i32| *x as f32); action_values[action.0] = *reward; self.q_table.insert(state_vec, action_values); } } } impl Agent<DiscreteAction> for QTableAgent { fn act(&mut self, state: &State) -> DiscreteAction { DiscreteAction(self.get_action_values(state).argmax().unwrap()) } }
use derive_more::{AsRef, Deref, DerefMut, Display, From, Into}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::str::FromStr; use url::Url; #[derive(Debug, Clone, From, Into, PartialEq, Eq, Deref, DerefMut, Display, AsRef)] pub struct UrlWrapper(pub Url); impl FromStr for UrlWrapper { type Err = url::ParseError; fn from_str(input: &str) -> Result<Self, Self::Err> { Url::from_str(input).map(Into::into) } } impl Serialize for UrlWrapper { fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> where S: Serializer, { serializer.serialize_str(self.0.as_str()) } } impl<'de> Deserialize<'de> for UrlWrapper { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: Deserializer<'de>, { String::deserialize(deserializer).and_then(|s| s.parse().map_err(serde::de::Error::custom)) } }
use super::{Pages, Pagination}; use crate::{commands::osu::MedalType, embeds::MedalsMissingEmbed, BotResult}; use rosu_v2::model::user::User; use twilight_model::channel::Message; pub struct MedalsMissingPagination { msg: Message, pages: Pages, user: User, medals: Vec<MedalType>, medal_count: (usize, usize), } impl MedalsMissingPagination { pub fn new( msg: Message, user: User, medals: Vec<MedalType>, medal_count: (usize, usize), ) -> Self { Self { msg, pages: Pages::new(15, medals.len()), user, medals, medal_count, } } } #[async_trait] impl Pagination for MedalsMissingPagination { type PageData = MedalsMissingEmbed; fn msg(&self) -> &Message { &self.msg } fn pages(&self) -> Pages { self.pages } fn pages_mut(&mut self) -> &mut Pages { &mut self.pages } fn single_step(&self) -> usize { self.pages.per_page } async fn build_page(&mut self) -> BotResult<Self::PageData> { let page = self.page(); let idx = (page - 1) * self.pages.per_page; let limit = self.medals.len().min(idx + self.pages.per_page); Ok(MedalsMissingEmbed::new( &self.user, &self.medals[idx..limit], self.medal_count, limit == self.medals.len(), (page, self.pages.total_pages), )) } }
//! Logger that prints messages like `[WARN] Lorem ipsum`. use atty; use log::{self, Log, Level, Metadata, Record}; use std::io::Write; use termcolor::{Color, ColorChoice, ColorSpec, StandardStream, WriteColor}; struct Logger { level: Level, use_color: bool, } impl Log for Logger { fn enabled(&self, metadata: &Metadata) -> bool { metadata.level() <= self.level } fn log(&self, record: &Record) { if !self.enabled(record.metadata()) { return; } let color_choice = match self.use_color { true => ColorChoice::Auto, false => ColorChoice::Never, }; let mut stderr = StandardStream::stderr(color_choice); let _ = stderr.set_color(ColorSpec::new().set_fg(Some(Color::Green))); let _ = writeln!(&mut stderr, "[{}] {}", record.level().to_string(), record.args(), ); let _ = stderr.reset(); } fn flush(&self) { } } pub fn init(level: Level) { let use_color = atty::is(atty::Stream::Stderr); let logger = Logger { level, use_color }; let _ = log::set_boxed_logger(Box::new(logger)); log::set_max_level(level.to_level_filter()); }
use proconio::input; use proconio::marker::*; use std::cmp::*; fn main() { input! { n: u32, s: Bytes, t: Bytes, } for i in 0..n{ print!("{}{}", s[i as usize] as char, t[i as usize] as char ); } println!(); }
use rust_decimal::Decimal; use serde::{Deserialize, Serialize}; /// This calls ::Default for types that use the serde /// deserialize_with attribute fn decimal_default_if_empy<'de, D, T>(de: D) -> Result<T, D::Error> where D: serde::Deserializer<'de>, T: serde::Deserialize<'de> + Default, { Option::<T>::deserialize(de).map(|x| x.unwrap_or_else(|| T::default())) } /// Holds information about a transaction #[derive(Debug, Serialize, Deserialize, Clone)] pub struct Transaction { #[serde(rename = "type")] pub type_: String, #[serde(rename = "client")] pub client_id: u16, #[serde(rename = "tx")] pub id: u32, #[serde(deserialize_with = "decimal_default_if_empy")] pub amount: Decimal, } impl Transaction { /// Create a new account with default values. /// /// Arguments: /// * id - the id for the transaction /// return: /// a new Transaction object /// /// # example /// ```rust /// mod transaction; /// Transaction::new(1); /// ``` pub fn new(id: u32) -> Transaction { Transaction { type_: String::from(""), client_id: 0, id: id, amount: Decimal::new(0, 4), } } } #[cfg(test)] mod test { use super::Transaction; #[test] fn test_new() { assert_eq!(Transaction::new(1).id, 1); } }
// https://www.codewars.com/kata/58712dfa5c538b6fc7000569/train/rust fn count_red_beads(n: u32) -> u32 { if n < 2 { return 0 } (n * 2) - 2 } #[cfg(test)] mod tests { use super::*; #[test] fn test_count_red_beads() { assert_eq!(count_red_beads(0), 0); assert_eq!(count_red_beads(1), 0); assert_eq!(count_red_beads(2), 2); assert_eq!(count_red_beads(3), 4); } }
//! GoodReads work schemas and record processing. use serde::Deserialize; use crate::arrow::*; use crate::parsing::*; use crate::prelude::*; const OUT_FILE: &'static str = "gr-author-info.parquet"; /// Author records as parsed from JSON. #[derive(Deserialize)] pub struct RawAuthor { pub author_id: String, pub name: String, } /// Rows in the processed work Parquet table. #[derive(ArrowField, ArrowSerialize)] pub struct AuthorRecord { pub author_id: i32, pub name: Option<String>, } /// Object writer to transform and write GoodReads works pub struct AuthorWriter { writer: TableWriter<AuthorRecord>, n_recs: usize, } impl AuthorWriter { /// Open a new output pub fn open() -> Result<AuthorWriter> { let writer = TableWriter::open(OUT_FILE)?; Ok(AuthorWriter { writer, n_recs: 0 }) } } impl DataSink for AuthorWriter { fn output_files(&self) -> Vec<PathBuf> { path_list(&[OUT_FILE]) } } impl ObjectWriter<RawAuthor> for AuthorWriter { fn write_object(&mut self, row: RawAuthor) -> Result<()> { let author_id: i32 = row.author_id.parse()?; self.writer.write_object(AuthorRecord { author_id, name: trim_owned(&row.name), })?; self.n_recs += 1; Ok(()) } fn finish(self) -> Result<usize> { self.writer.finish()?; Ok(self.n_recs) } }
#[doc = "Reader of register EFUSE_RDATA_L"] pub type R = crate::R<u32, super::EFUSE_RDATA_L>; #[doc = "Reader of field `DATA`"] pub type DATA_R = crate::R<u32, u32>; impl R { #[doc = "Bits 0:31 - This register has the read value from the Efuse macro, fuse bits\\[31:0\\]"] #[inline(always)] pub fn data(&self) -> DATA_R { DATA_R::new((self.bits & 0xffff_ffff) as u32) } }
pub use self::{ circle::*, fill::*, group::*, padding::*, paint::*, path::*, rect::*, rounding::*, stroke::*, text::*, translate::*, }; use crate::{Real, Transform}; pub mod circle; pub mod fill; pub mod group; pub mod padding; pub mod paint; pub mod path; pub mod rect; pub mod rounding; pub mod stroke; pub mod text; pub mod translate; #[derive(Debug, Clone, PartialEq)] pub enum Shape { Rect(Rect), Circle(Circle), Path(Path), Group(Group), Text(Text), } pub trait Shaped { fn rect(&self) -> Option<&Rect>; fn rect_mut(&mut self) -> Option<&mut Rect>; fn circle(&self) -> Option<&Circle>; fn circle_mut(&mut self) -> Option<&mut Circle>; fn path(&self) -> Option<&Path>; fn path_mut(&mut self) -> Option<&mut Path>; fn group(&self) -> Option<&Group>; fn group_mut(&mut self) -> Option<&mut Group>; fn text(&self) -> Option<&Text>; fn text_mut(&mut self) -> Option<&mut Text>; } pub struct ShapeRef<'a>(pub &'a Shape); pub struct ShapeRefMut<'a>(pub &'a mut Shape); impl Shape { pub fn id(&self) -> Option<&str> { match self { Shape::Rect(rect) => rect.id(), Shape::Circle(circle) => circle.id(), Shape::Path(path) => path.id(), Shape::Group(group) => group.id(), Shape::Text(text) => text.id(), } } pub fn set_id(&mut self, id: impl Into<String>) { let id = Some(id.into()); match self { Shape::Rect(rect) => rect.id = id, Shape::Circle(circle) => circle.id = id, Shape::Path(path) => path.id = id, Shape::Group(group) => group.id = id, Shape::Text(text) => text.id = id, } } pub fn transform(&self) -> &Transform { match self { Shape::Rect(rect) => &rect.transform, Shape::Circle(circle) => &circle.transform, Shape::Path(path) => &path.transform, Shape::Group(group) => &group.transform, Shape::Text(text) => &text.transform, } } pub fn transform_mut(&mut self) -> &mut Transform { match self { Shape::Rect(rect) => &mut rect.transform, Shape::Circle(circle) => &mut circle.transform, Shape::Path(path) => &mut path.transform, Shape::Group(group) => &mut group.transform, Shape::Text(text) => &mut text.transform, } } #[inline] pub fn as_ref(&self) -> ShapeRef { ShapeRef(self) } #[inline] pub fn as_ref_mut(&mut self) -> ShapeRefMut { ShapeRefMut(self) } } impl Shaped for Shape { #[inline] fn rect(&self) -> Option<&Rect> { match self { Shape::Rect(rect) => Some(rect), _ => None, } } #[inline] fn rect_mut(&mut self) -> Option<&mut Rect> { match self { Shape::Rect(rect) => Some(rect), _ => None, } } #[inline] fn circle(&self) -> Option<&Circle> { match self { Shape::Circle(circle) => Some(circle), _ => None, } } #[inline] fn circle_mut(&mut self) -> Option<&mut Circle> { match self { Shape::Circle(circle) => Some(circle), _ => None, } } #[inline] fn path(&self) -> Option<&Path> { match self { Shape::Path(path) => Some(path), _ => None, } } #[inline] fn path_mut(&mut self) -> Option<&mut Path> { match self { Shape::Path(path) => Some(path), _ => None, } } #[inline] fn group(&self) -> Option<&Group> { match self { Shape::Group(group) => Some(group), _ => None, } } #[inline] fn group_mut(&mut self) -> Option<&mut Group> { match self { Shape::Group(group) => Some(group), _ => None, } } #[inline] fn text(&self) -> Option<&Text> { match self { Shape::Text(text) => Some(text), _ => None, } } #[inline] fn text_mut(&mut self) -> Option<&mut Text> { match self { Shape::Text(text) => Some(text), _ => None, } } } impl<'a> ShapeRef<'a> { #[inline] pub fn rect(&self) -> Option<&Rect> { self.0.rect() } #[inline] pub fn circle(&self) -> Option<&Circle> { self.0.circle() } #[inline] pub fn path(&self) -> Option<&Path> { self.0.path() } #[inline] pub fn group(&self) -> Option<&Group> { self.0.group() } #[inline] pub fn text(&self) -> Option<&Text> { self.0.text() } } impl<'a> ShapeRefMut<'a> { #[inline] pub fn rect(&mut self) -> Option<&mut Rect> { self.0.rect_mut() } #[inline] pub fn circle(&mut self) -> Option<&mut Circle> { self.0.circle_mut() } #[inline] pub fn path(&mut self) -> Option<&mut Path> { self.0.path_mut() } #[inline] pub fn group(&mut self) -> Option<&mut Group> { self.0.group_mut() } #[inline] pub fn text(&mut self) -> Option<&mut Text> { self.0.text_mut() } } impl From<Rect> for Shape { fn from(rect: Rect) -> Self { Shape::Rect(rect) } } impl From<Circle> for Shape { fn from(circle: Circle) -> Self { Shape::Circle(circle) } } impl From<Path> for Shape { fn from(path: Path) -> Self { Shape::Path(path) } } impl From<Group> for Shape { fn from(group: Group) -> Self { Shape::Group(group) } } impl From<Text> for Shape { fn from(text: Text) -> Self { Shape::Text(text) } } impl From<String> for Shape { fn from(text: String) -> Self { Shape::Text(Text { content: text, ..Default::default() }) } } pub type CompositeShapeIter<'a> = Box<dyn Iterator<Item = &'a dyn CompositeShape> + 'a>; pub type CompositeShapeIterMut<'a> = Box<dyn Iterator<Item = &'a mut dyn CompositeShape> + 'a>; pub trait CompositeShape { fn shape(&self) -> Option<&Shape>; fn shape_mut(&mut self) -> Option<&mut Shape>; fn children(&self) -> Option<CompositeShapeIter>; fn children_mut(&mut self) -> Option<CompositeShapeIterMut>; fn need_recalc(&self) -> Option<bool>; fn need_redraw(&self) -> Option<bool>; fn intersect(&self, x: Real, y: Real) -> bool { if let Some(shape) = self.shape() { match shape { Shape::Rect(rect) => rect.intersect(x, y), Shape::Circle(circle) => circle.intersect(x, y), Shape::Path(path) => path.intersect(x, y), _ => false, } } else { false } } }
struct Foo { bar: bool, } impl Foo { fn abc(&mut self) {} fn xyz(mut self) { loop { self.bar = false; // Panic trigger requires both statements let _ = self.abc(); } } } fn main() {} /* thread 'rustc' panicked at 'Adding a write root node to an existing tree.', prusti-interface/src/environment/loops_utils.rs:282:13 stack backtrace: 0: std::panicking::begin_panic 1: prusti_interface::environment::loops_utils::PermissionTree::add 2: prusti_interface::environment::loops_utils::PermissionForest::new::add_paths 3: prusti_interface::environment::loops_utils::PermissionForest::new 4: prusti_viper::encoder::loop_encoder::LoopEncoder::compute_loop_invariant 5: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode_loop_invariant_permissions 6: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode_loop_invariant_exhale_stmts 7: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode_loop 8: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode_blocks_group 9: prusti_viper::encoder::procedure_encoder::ProcedureEncoder::encode 10: prusti_viper::encoder::encoder::Encoder::encode_procedure 11: prusti_viper::encoder::encoder::Encoder::process_encoding_queue 12: prusti_viper::verifier::Verifier::verify 13: prusti_driver::verifier::verify 14: <prusti_driver::callbacks::PrustiCompilerCalls as rustc_driver::Callbacks>::after_analysis 15: rustc_interface::queries::<impl rustc_interface::interface::Compiler>::enter 16: rustc_span::with_source_map 17: rustc_interface::interface::create_compiler_and_run 18: scoped_tls::ScopedKey<T>::set */
#![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 CertificateVerificationDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub certificate: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateListDescription { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<CertificateDescription>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateBodyDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub certificate: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CertificateProperties>, #[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 etag: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateWithNonceDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<CertificatePropertiesWithNonce>, #[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 etag: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SharedAccessSignatureAuthorizationRule { #[serde(rename = "keyName")] pub key_name: String, #[serde(rename = "primaryKey", default, skip_serializing_if = "Option::is_none")] pub primary_key: Option<String>, #[serde(rename = "secondaryKey", default, skip_serializing_if = "Option::is_none")] pub secondary_key: Option<String>, pub rights: shared_access_signature_authorization_rule::Rights, } pub mod shared_access_signature_authorization_rule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Rights { RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect, #[serde(rename = "RegistryRead, RegistryWrite")] RegistryReadRegistryWrite, #[serde(rename = "RegistryRead, ServiceConnect")] RegistryReadServiceConnect, #[serde(rename = "RegistryRead, DeviceConnect")] RegistryReadDeviceConnect, #[serde(rename = "RegistryWrite, ServiceConnect")] RegistryWriteServiceConnect, #[serde(rename = "RegistryWrite, DeviceConnect")] RegistryWriteDeviceConnect, #[serde(rename = "ServiceConnect, DeviceConnect")] ServiceConnectDeviceConnect, #[serde(rename = "RegistryRead, RegistryWrite, ServiceConnect")] RegistryReadRegistryWriteServiceConnect, #[serde(rename = "RegistryRead, RegistryWrite, DeviceConnect")] RegistryReadRegistryWriteDeviceConnect, #[serde(rename = "RegistryRead, ServiceConnect, DeviceConnect")] RegistryReadServiceConnectDeviceConnect, #[serde(rename = "RegistryWrite, ServiceConnect, DeviceConnect")] RegistryWriteServiceConnectDeviceConnect, #[serde(rename = "RegistryRead, RegistryWrite, ServiceConnect, DeviceConnect")] RegistryReadRegistryWriteServiceConnectDeviceConnect, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificateProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub subject: Option<String>, #[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 = "isVerified", default, skip_serializing_if = "Option::is_none")] pub is_verified: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub created: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub updated: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub certificate: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CertificatePropertiesWithNonce { #[serde(default, skip_serializing_if = "Option::is_none")] pub subject: Option<String>, #[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 = "isVerified", default, skip_serializing_if = "Option::is_none")] pub is_verified: Option<bool>, #[serde(default, skip_serializing_if = "Option::is_none")] pub created: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub updated: Option<String>, #[serde(rename = "verificationCode", default, skip_serializing_if = "Option::is_none")] pub verification_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub certificate: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubProperties { #[serde(rename = "authorizationPolicies", default, skip_serializing_if = "Vec::is_empty")] pub authorization_policies: Vec<SharedAccessSignatureAuthorizationRule>, #[serde(rename = "publicNetworkAccess", default, skip_serializing_if = "Option::is_none")] pub public_network_access: Option<iot_hub_properties::PublicNetworkAccess>, #[serde(rename = "ipFilterRules", default, skip_serializing_if = "Vec::is_empty")] pub ip_filter_rules: Vec<IpFilterRule>, #[serde(rename = "networkRuleSets", default, skip_serializing_if = "Option::is_none")] pub network_rule_sets: Option<NetworkRuleSetProperties>, #[serde(rename = "minTlsVersion", default, skip_serializing_if = "Option::is_none")] pub min_tls_version: Option<String>, #[serde(rename = "privateEndpointConnections", default, skip_serializing_if = "Vec::is_empty")] pub private_endpoint_connections: Vec<PrivateEndpointConnection>, #[serde(rename = "provisioningState", default, skip_serializing_if = "Option::is_none")] pub provisioning_state: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub state: Option<String>, #[serde(rename = "hostName", default, skip_serializing_if = "Option::is_none")] pub host_name: Option<String>, #[serde(rename = "eventHubEndpoints", default, skip_serializing_if = "Option::is_none")] pub event_hub_endpoints: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub routing: Option<RoutingProperties>, #[serde(rename = "storageEndpoints", default, skip_serializing_if = "Option::is_none")] pub storage_endpoints: Option<serde_json::Value>, #[serde(rename = "messagingEndpoints", default, skip_serializing_if = "Option::is_none")] pub messaging_endpoints: Option<serde_json::Value>, #[serde(rename = "enableFileUploadNotifications", default, skip_serializing_if = "Option::is_none")] pub enable_file_upload_notifications: Option<bool>, #[serde(rename = "cloudToDevice", default, skip_serializing_if = "Option::is_none")] pub cloud_to_device: Option<CloudToDeviceProperties>, #[serde(default, skip_serializing_if = "Option::is_none")] pub comments: Option<String>, #[serde(rename = "deviceStreams", default, skip_serializing_if = "Option::is_none")] pub device_streams: Option<iot_hub_properties::DeviceStreams>, #[serde(default, skip_serializing_if = "Option::is_none")] pub features: Option<iot_hub_properties::Features>, #[serde(default, skip_serializing_if = "Option::is_none")] pub encryption: Option<EncryptionPropertiesDescription>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub locations: Vec<IotHubLocationDescription>, } pub mod iot_hub_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum PublicNetworkAccess { Enabled, Disabled, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct DeviceStreams { #[serde(rename = "streamingEndpoints", default, skip_serializing_if = "Vec::is_empty")] pub streaming_endpoints: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Features { None, DeviceManagement, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubSkuInfo { pub name: iot_hub_sku_info::Name, #[serde(default, skip_serializing_if = "Option::is_none")] pub tier: Option<iot_hub_sku_info::Tier>, #[serde(default, skip_serializing_if = "Option::is_none")] pub capacity: Option<i64>, } pub mod iot_hub_sku_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Name { F1, S1, S2, S3, B1, B2, B3, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Tier { Free, Standard, Basic, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubProperties { #[serde(rename = "retentionTimeInDays", default, skip_serializing_if = "Option::is_none")] pub retention_time_in_days: Option<i64>, #[serde(rename = "partitionCount", default, skip_serializing_if = "Option::is_none")] pub partition_count: Option<i32>, #[serde(rename = "partitionIds", default, skip_serializing_if = "Vec::is_empty")] pub partition_ids: Vec<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub path: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub endpoint: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct StorageEndpointProperties { #[serde(rename = "sasTtlAsIso8601", default, skip_serializing_if = "Option::is_none")] pub sas_ttl_as_iso8601: Option<String>, #[serde(rename = "connectionString")] pub connection_string: String, #[serde(rename = "containerName")] pub container_name: String, #[serde(rename = "authenticationType", default, skip_serializing_if = "Option::is_none")] pub authentication_type: Option<storage_endpoint_properties::AuthenticationType>, } pub mod storage_endpoint_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AuthenticationType { #[serde(rename = "keyBased")] KeyBased, #[serde(rename = "identityBased")] IdentityBased, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MessagingEndpointProperties { #[serde(rename = "lockDurationAsIso8601", default, skip_serializing_if = "Option::is_none")] pub lock_duration_as_iso8601: Option<String>, #[serde(rename = "ttlAsIso8601", default, skip_serializing_if = "Option::is_none")] pub ttl_as_iso8601: Option<String>, #[serde(rename = "maxDeliveryCount", default, skip_serializing_if = "Option::is_none")] pub max_delivery_count: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct CloudToDeviceProperties { #[serde(rename = "maxDeliveryCount", default, skip_serializing_if = "Option::is_none")] pub max_delivery_count: Option<i32>, #[serde(rename = "defaultTtlAsIso8601", default, skip_serializing_if = "Option::is_none")] pub default_ttl_as_iso8601: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub feedback: Option<FeedbackProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IpFilterRule { #[serde(rename = "filterName")] pub filter_name: String, pub action: ip_filter_rule::Action, #[serde(rename = "ipMask")] pub ip_mask: String, } pub mod ip_filter_rule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Action { Accept, Reject, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NetworkRuleSetProperties { #[serde(rename = "defaultAction", default, skip_serializing_if = "Option::is_none")] pub default_action: Option<network_rule_set_properties::DefaultAction>, #[serde(rename = "applyToBuiltInEventHubEndpoint")] pub apply_to_built_in_event_hub_endpoint: bool, #[serde(rename = "ipRules")] pub ip_rules: Vec<NetworkRuleSetIpRule>, } pub mod network_rule_set_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum DefaultAction { Deny, Allow, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct NetworkRuleSetIpRule { #[serde(rename = "filterName")] pub filter_name: String, #[serde(default, skip_serializing_if = "Option::is_none")] pub action: Option<network_rule_set_ip_rule::Action>, #[serde(rename = "ipMask")] pub ip_mask: String, } pub mod network_rule_set_ip_rule { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Action { Allow, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateLinkResources { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<GroupIdInformation>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GroupIdInformation { #[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 properties: GroupIdInformationProperties, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct GroupIdInformationProperties { #[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>, } pub type PrivateEndpointConnectionsList = Vec<PrivateEndpointConnection>; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct PrivateEndpointConnection { #[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 properties: 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")] pub private_link_service_connection_state: PrivateLinkServiceConnectionState, } #[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 { pub status: private_link_service_connection_state::Status, pub description: String, #[serde(rename = "actionsRequired", default, skip_serializing_if = "Option::is_none")] pub actions_required: Option<String>, } pub mod private_link_service_connection_state { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { Pending, Approved, Rejected, Disconnected, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FeedbackProperties { #[serde(rename = "lockDurationAsIso8601", default, skip_serializing_if = "Option::is_none")] pub lock_duration_as_iso8601: Option<String>, #[serde(rename = "ttlAsIso8601", default, skip_serializing_if = "Option::is_none")] pub ttl_as_iso8601: Option<String>, #[serde(rename = "maxDeliveryCount", default, skip_serializing_if = "Option::is_none")] pub max_delivery_count: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoutingProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub endpoints: Option<RoutingEndpoints>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub routes: Vec<RouteProperties>, #[serde(rename = "fallbackRoute", default, skip_serializing_if = "Option::is_none")] pub fallback_route: Option<FallbackRouteProperties>, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub enrichments: Vec<EnrichmentProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoutingEndpoints { #[serde(rename = "serviceBusQueues", default, skip_serializing_if = "Vec::is_empty")] pub service_bus_queues: Vec<RoutingServiceBusQueueEndpointProperties>, #[serde(rename = "serviceBusTopics", default, skip_serializing_if = "Vec::is_empty")] pub service_bus_topics: Vec<RoutingServiceBusTopicEndpointProperties>, #[serde(rename = "eventHubs", default, skip_serializing_if = "Vec::is_empty")] pub event_hubs: Vec<RoutingEventHubProperties>, #[serde(rename = "storageContainers", default, skip_serializing_if = "Vec::is_empty")] pub storage_containers: Vec<RoutingStorageContainerProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoutingServiceBusQueueEndpointProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "connectionString", default, skip_serializing_if = "Option::is_none")] pub connection_string: Option<String>, #[serde(rename = "endpointUri", default, skip_serializing_if = "Option::is_none")] pub endpoint_uri: Option<String>, #[serde(rename = "entityPath", default, skip_serializing_if = "Option::is_none")] pub entity_path: Option<String>, #[serde(rename = "authenticationType", default, skip_serializing_if = "Option::is_none")] pub authentication_type: Option<routing_service_bus_queue_endpoint_properties::AuthenticationType>, pub name: String, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, } pub mod routing_service_bus_queue_endpoint_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AuthenticationType { #[serde(rename = "keyBased")] KeyBased, #[serde(rename = "identityBased")] IdentityBased, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoutingServiceBusTopicEndpointProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "connectionString", default, skip_serializing_if = "Option::is_none")] pub connection_string: Option<String>, #[serde(rename = "endpointUri", default, skip_serializing_if = "Option::is_none")] pub endpoint_uri: Option<String>, #[serde(rename = "entityPath", default, skip_serializing_if = "Option::is_none")] pub entity_path: Option<String>, #[serde(rename = "authenticationType", default, skip_serializing_if = "Option::is_none")] pub authentication_type: Option<routing_service_bus_topic_endpoint_properties::AuthenticationType>, pub name: String, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, } pub mod routing_service_bus_topic_endpoint_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AuthenticationType { #[serde(rename = "keyBased")] KeyBased, #[serde(rename = "identityBased")] IdentityBased, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoutingEventHubProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "connectionString", default, skip_serializing_if = "Option::is_none")] pub connection_string: Option<String>, #[serde(rename = "endpointUri", default, skip_serializing_if = "Option::is_none")] pub endpoint_uri: Option<String>, #[serde(rename = "entityPath", default, skip_serializing_if = "Option::is_none")] pub entity_path: Option<String>, #[serde(rename = "authenticationType", default, skip_serializing_if = "Option::is_none")] pub authentication_type: Option<routing_event_hub_properties::AuthenticationType>, pub name: String, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, } pub mod routing_event_hub_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AuthenticationType { #[serde(rename = "keyBased")] KeyBased, #[serde(rename = "identityBased")] IdentityBased, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoutingStorageContainerProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "connectionString", default, skip_serializing_if = "Option::is_none")] pub connection_string: Option<String>, #[serde(rename = "endpointUri", default, skip_serializing_if = "Option::is_none")] pub endpoint_uri: Option<String>, #[serde(rename = "authenticationType", default, skip_serializing_if = "Option::is_none")] pub authentication_type: Option<routing_storage_container_properties::AuthenticationType>, pub name: String, #[serde(rename = "subscriptionId", default, skip_serializing_if = "Option::is_none")] pub subscription_id: Option<String>, #[serde(rename = "resourceGroup", default, skip_serializing_if = "Option::is_none")] pub resource_group: Option<String>, #[serde(rename = "containerName")] pub container_name: String, #[serde(rename = "fileNameFormat", default, skip_serializing_if = "Option::is_none")] pub file_name_format: Option<String>, #[serde(rename = "batchFrequencyInSeconds", default, skip_serializing_if = "Option::is_none")] pub batch_frequency_in_seconds: Option<i32>, #[serde(rename = "maxChunkSizeInBytes", default, skip_serializing_if = "Option::is_none")] pub max_chunk_size_in_bytes: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub encoding: Option<routing_storage_container_properties::Encoding>, } pub mod routing_storage_container_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AuthenticationType { #[serde(rename = "keyBased")] KeyBased, #[serde(rename = "identityBased")] IdentityBased, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Encoding { Avro, AvroDeflate, #[serde(rename = "JSON")] Json, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RouteProperties { pub name: String, pub source: route_properties::Source, #[serde(default, skip_serializing_if = "Option::is_none")] pub condition: Option<String>, #[serde(rename = "endpointNames")] pub endpoint_names: Vec<String>, #[serde(rename = "isEnabled")] pub is_enabled: bool, } pub mod route_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Source { Invalid, DeviceMessages, TwinChangeEvents, DeviceLifecycleEvents, DeviceJobLifecycleEvents, DigitalTwinChangeEvents, DeviceConnectionStateEvents, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FallbackRouteProperties { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, pub source: fallback_route_properties::Source, #[serde(default, skip_serializing_if = "Option::is_none")] pub condition: Option<String>, #[serde(rename = "endpointNames")] pub endpoint_names: Vec<String>, #[serde(rename = "isEnabled")] pub is_enabled: bool, } pub mod fallback_route_properties { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Source { DeviceMessages, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EnrichmentProperties { pub key: String, pub value: String, #[serde(rename = "endpointNames")] pub endpoint_names: Vec<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubDescription { #[serde(flatten)] pub resource: Resource, #[serde(default, skip_serializing_if = "Option::is_none")] pub etag: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<IotHubProperties>, pub sku: IotHubSkuInfo, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<ArmIdentity>, } #[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>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct SharedAccessSignatureAuthorizationRuleListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<SharedAccessSignatureAuthorizationRule>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<Operation>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Operation { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub display: Option<operation::Display>, } pub mod operation { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Display { #[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 ErrorDetails { #[serde(default, skip_serializing_if = "Option::is_none")] pub code: Option<String>, #[serde(rename = "httpStatusCode", default, skip_serializing_if = "Option::is_none")] pub http_status_code: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubQuotaMetricInfoListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<IotHubQuotaMetricInfo>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EndpointHealthDataListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<EndpointHealthData>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EndpointHealthData { #[serde(rename = "endpointId", default, skip_serializing_if = "Option::is_none")] pub endpoint_id: Option<String>, #[serde(rename = "healthStatus", default, skip_serializing_if = "Option::is_none")] pub health_status: Option<endpoint_health_data::HealthStatus>, #[serde(rename = "lastKnownError", default, skip_serializing_if = "Option::is_none")] pub last_known_error: Option<String>, #[serde(rename = "lastKnownErrorTime", default, skip_serializing_if = "Option::is_none")] pub last_known_error_time: Option<String>, #[serde(rename = "lastSuccessfulSendAttemptTime", default, skip_serializing_if = "Option::is_none")] pub last_successful_send_attempt_time: Option<String>, #[serde(rename = "lastSendAttemptTime", default, skip_serializing_if = "Option::is_none")] pub last_send_attempt_time: Option<String>, } pub mod endpoint_health_data { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum HealthStatus { #[serde(rename = "unknown")] Unknown, #[serde(rename = "healthy")] Healthy, #[serde(rename = "degraded")] Degraded, #[serde(rename = "unhealthy")] Unhealthy, #[serde(rename = "dead")] Dead, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RegistryStatistics { #[serde(rename = "totalDeviceCount", default, skip_serializing_if = "Option::is_none")] pub total_device_count: Option<i64>, #[serde(rename = "enabledDeviceCount", default, skip_serializing_if = "Option::is_none")] pub enabled_device_count: Option<i64>, #[serde(rename = "disabledDeviceCount", default, skip_serializing_if = "Option::is_none")] pub disabled_device_count: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct JobResponseListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<JobResponse>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubSkuDescription { #[serde(rename = "resourceType", default, skip_serializing_if = "Option::is_none")] pub resource_type: Option<String>, pub sku: IotHubSkuInfo, pub capacity: IotHubCapacity, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TagsResource { #[serde(default, skip_serializing_if = "Option::is_none")] pub tags: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubCapacity { #[serde(default, skip_serializing_if = "Option::is_none")] pub minimum: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub maximum: Option<i64>, #[serde(default, skip_serializing_if = "Option::is_none")] pub default: Option<i64>, #[serde(rename = "scaleType", default, skip_serializing_if = "Option::is_none")] pub scale_type: Option<iot_hub_capacity::ScaleType>, } pub mod iot_hub_capacity { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum ScaleType { Automatic, Manual, None, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubConsumerGroupsListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<EventHubConsumerGroupInfo>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubConsumerGroupBodyDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<EventHubConsumerGroupName>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubConsumerGroupName { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct EventHubConsumerGroupInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<serde_json::Value>, #[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(default, skip_serializing_if = "Option::is_none")] pub etag: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubSkuDescriptionListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<IotHubSkuDescription>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct JobResponse { #[serde(rename = "jobId", default, skip_serializing_if = "Option::is_none")] pub job_id: Option<String>, #[serde(rename = "startTimeUtc", default, skip_serializing_if = "Option::is_none")] pub start_time_utc: Option<String>, #[serde(rename = "endTimeUtc", default, skip_serializing_if = "Option::is_none")] pub end_time_utc: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<job_response::Type>, #[serde(default, skip_serializing_if = "Option::is_none")] pub status: Option<job_response::Status>, #[serde(rename = "failureReason", default, skip_serializing_if = "Option::is_none")] pub failure_reason: Option<String>, #[serde(rename = "statusMessage", default, skip_serializing_if = "Option::is_none")] pub status_message: Option<String>, #[serde(rename = "parentJobId", default, skip_serializing_if = "Option::is_none")] pub parent_job_id: Option<String>, } pub mod job_response { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Type { #[serde(rename = "unknown")] Unknown, #[serde(rename = "export")] Export, #[serde(rename = "import")] Import, #[serde(rename = "backup")] Backup, #[serde(rename = "readDeviceProperties")] ReadDeviceProperties, #[serde(rename = "writeDeviceProperties")] WriteDeviceProperties, #[serde(rename = "updateDeviceConfiguration")] UpdateDeviceConfiguration, #[serde(rename = "rebootDevice")] RebootDevice, #[serde(rename = "factoryResetDevice")] FactoryResetDevice, #[serde(rename = "firmwareUpdate")] FirmwareUpdate, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Status { #[serde(rename = "unknown")] Unknown, #[serde(rename = "enqueued")] Enqueued, #[serde(rename = "running")] Running, #[serde(rename = "completed")] Completed, #[serde(rename = "failed")] Failed, #[serde(rename = "cancelled")] Cancelled, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubDescriptionListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<IotHubDescription>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubQuotaMetricInfo { #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<String>, #[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")] pub current_value: Option<i64>, #[serde(rename = "maxValue", default, skip_serializing_if = "Option::is_none")] pub max_value: Option<i64>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct OperationInputs { pub name: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubNameAvailabilityInfo { #[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<iot_hub_name_availability_info::Reason>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, } pub mod iot_hub_name_availability_info { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Reason { Invalid, AlreadyExists, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserSubscriptionQuotaListResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub value: Vec<UserSubscriptionQuota>, #[serde(rename = "nextLink", default, skip_serializing_if = "Option::is_none")] pub next_link: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct UserSubscriptionQuota { #[serde(default, skip_serializing_if = "Option::is_none")] pub id: Option<String>, #[serde(rename = "type", default, skip_serializing_if = "Option::is_none")] pub type_: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub unit: Option<String>, #[serde(rename = "currentValue", default, skip_serializing_if = "Option::is_none")] pub current_value: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub limit: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub name: Option<Name>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Name { #[serde(default, skip_serializing_if = "Option::is_none")] pub value: Option<String>, #[serde(rename = "localizedValue", default, skip_serializing_if = "Option::is_none")] pub localized_value: Option<String>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TestAllRoutesInput { #[serde(rename = "routingSource", default, skip_serializing_if = "Option::is_none")] pub routing_source: Option<test_all_routes_input::RoutingSource>, #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<RoutingMessage>, #[serde(default, skip_serializing_if = "Option::is_none")] pub twin: Option<RoutingTwin>, } pub mod test_all_routes_input { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum RoutingSource { Invalid, DeviceMessages, TwinChangeEvents, DeviceLifecycleEvents, DeviceJobLifecycleEvents, DigitalTwinChangeEvents, DeviceConnectionStateEvents, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoutingTwin { #[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<routing_twin::Properties>, } pub mod routing_twin { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct Properties { #[serde(default, skip_serializing_if = "Option::is_none")] pub desired: Option<serde_json::Value>, #[serde(default, skip_serializing_if = "Option::is_none")] pub reported: Option<serde_json::Value>, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RoutingMessage { #[serde(default, skip_serializing_if = "Option::is_none")] pub body: Option<String>, #[serde(rename = "appProperties", default, skip_serializing_if = "Option::is_none")] pub app_properties: Option<serde_json::Value>, #[serde(rename = "systemProperties", default, skip_serializing_if = "Option::is_none")] pub system_properties: Option<serde_json::Value>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TestAllRoutesResult { #[serde(default, skip_serializing_if = "Vec::is_empty")] pub routes: Vec<MatchedRoute>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct MatchedRoute { #[serde(default, skip_serializing_if = "Option::is_none")] pub properties: Option<RouteProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TestRouteInput { #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<RoutingMessage>, pub route: RouteProperties, #[serde(default, skip_serializing_if = "Option::is_none")] pub twin: Option<RoutingTwin>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TestRouteResult { #[serde(default, skip_serializing_if = "Option::is_none")] pub result: Option<test_route_result::Result>, #[serde(default, skip_serializing_if = "Option::is_none")] pub details: Option<TestRouteResultDetails>, } pub mod test_route_result { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Result { #[serde(rename = "undefined")] Undefined, #[serde(rename = "false")] False, #[serde(rename = "true")] True, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct TestRouteResultDetails { #[serde(rename = "compilationErrors", default, skip_serializing_if = "Vec::is_empty")] pub compilation_errors: Vec<RouteCompilationError>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RouteCompilationError { #[serde(default, skip_serializing_if = "Option::is_none")] pub message: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub severity: Option<route_compilation_error::Severity>, #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<RouteErrorRange>, } pub mod route_compilation_error { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Severity { #[serde(rename = "error")] Error, #[serde(rename = "warning")] Warning, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RouteErrorRange { #[serde(default, skip_serializing_if = "Option::is_none")] pub start: Option<RouteErrorPosition>, #[serde(default, skip_serializing_if = "Option::is_none")] pub end: Option<RouteErrorPosition>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct RouteErrorPosition { #[serde(default, skip_serializing_if = "Option::is_none")] pub line: Option<i32>, #[serde(default, skip_serializing_if = "Option::is_none")] pub column: Option<i32>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ExportDevicesRequest { #[serde(rename = "exportBlobContainerUri")] pub export_blob_container_uri: String, #[serde(rename = "excludeKeys")] pub exclude_keys: bool, #[serde(rename = "exportBlobName", default, skip_serializing_if = "Option::is_none")] pub export_blob_name: Option<String>, #[serde(rename = "authenticationType", default, skip_serializing_if = "Option::is_none")] pub authentication_type: Option<export_devices_request::AuthenticationType>, } pub mod export_devices_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AuthenticationType { #[serde(rename = "keyBased")] KeyBased, #[serde(rename = "identityBased")] IdentityBased, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ImportDevicesRequest { #[serde(rename = "inputBlobContainerUri")] pub input_blob_container_uri: String, #[serde(rename = "outputBlobContainerUri")] pub output_blob_container_uri: String, #[serde(rename = "inputBlobName", default, skip_serializing_if = "Option::is_none")] pub input_blob_name: Option<String>, #[serde(rename = "outputBlobName", default, skip_serializing_if = "Option::is_none")] pub output_blob_name: Option<String>, #[serde(rename = "authenticationType", default, skip_serializing_if = "Option::is_none")] pub authentication_type: Option<import_devices_request::AuthenticationType>, } pub mod import_devices_request { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum AuthenticationType { #[serde(rename = "keyBased")] KeyBased, #[serde(rename = "identityBased")] IdentityBased, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct FailoverInput { #[serde(rename = "failoverRegion")] pub failover_region: String, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct IotHubLocationDescription { #[serde(default, skip_serializing_if = "Option::is_none")] pub location: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub role: Option<iot_hub_location_description::Role>, } pub mod iot_hub_location_description { use super::*; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub enum Role { #[serde(rename = "primary")] Primary, #[serde(rename = "secondary")] Secondary, } } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct ArmIdentity { #[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<arm_identity::Type>, #[serde(rename = "userAssignedIdentities", default, skip_serializing_if = "Option::is_none")] pub user_assigned_identities: Option<serde_json::Value>, } pub mod arm_identity { 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 ArmUserIdentity { #[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 EncryptionPropertiesDescription { #[serde(rename = "keySource", default, skip_serializing_if = "Option::is_none")] pub key_source: Option<String>, #[serde(rename = "keyVaultProperties", default, skip_serializing_if = "Vec::is_empty")] pub key_vault_properties: Vec<KeyVaultKeyProperties>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KeyVaultKeyProperties { #[serde(rename = "keyIdentifier", default, skip_serializing_if = "Option::is_none")] pub key_identifier: Option<String>, #[serde(default, skip_serializing_if = "Option::is_none")] pub identity: Option<KekIdentity>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] pub struct KekIdentity { #[serde(rename = "userAssignedIdentity", default, skip_serializing_if = "Option::is_none")] pub user_assigned_identity: Option<String>, }
#[doc = "Register `ISR` reader"] pub type R = crate::R<ISR_SPEC>; #[doc = "Register `ISR` writer"] pub type W = crate::W<ISR_SPEC>; #[doc = "Field `ALRAWF` reader - Alarm A write flag"] pub type ALRAWF_R = crate::BitReader; #[doc = "Field `ALRBWF` reader - Alarm B write flag"] pub type ALRBWF_R = crate::BitReader; #[doc = "Field `WUTWF` reader - Wakeup timer write flag"] pub type WUTWF_R = crate::BitReader; #[doc = "Field `SHPF` reader - Shift operation pending"] pub type SHPF_R = crate::BitReader; #[doc = "Field `SHPF` writer - Shift operation pending"] pub type SHPF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `INITS` reader - Initialization status flag"] pub type INITS_R = crate::BitReader; #[doc = "Field `RSF` reader - Registers synchronization flag"] pub type RSF_R = crate::BitReader; #[doc = "Field `RSF` writer - Registers synchronization flag"] pub type RSF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `INITF` reader - Initialization flag"] pub type INITF_R = crate::BitReader; #[doc = "Field `INITF` writer - Initialization flag"] pub type INITF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `INIT` reader - Initialization mode"] pub type INIT_R = crate::BitReader; #[doc = "Field `INIT` writer - Initialization mode"] pub type INIT_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ALRAF` reader - Alarm A flag"] pub type ALRAF_R = crate::BitReader; #[doc = "Field `ALRAF` writer - Alarm A flag"] pub type ALRAF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `ALRBF` reader - Alarm B flag"] pub type ALRBF_R = crate::BitReader; #[doc = "Field `ALRBF` writer - Alarm B flag"] pub type ALRBF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `WUTF` reader - Wakeup timer flag"] pub type WUTF_R = crate::BitReader; #[doc = "Field `WUTF` writer - Wakeup timer flag"] pub type WUTF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TSF` reader - Timestamp flag"] pub type TSF_R = crate::BitReader; #[doc = "Field `TSF` writer - Timestamp flag"] pub type TSF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TSOVF` reader - Timestamp overflow flag"] pub type TSOVF_R = crate::BitReader; #[doc = "Field `TSOVF` writer - Timestamp overflow flag"] pub type TSOVF_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP1F` reader - Tamper detection flag"] pub type TAMP1F_R = crate::BitReader; #[doc = "Field `TAMP1F` writer - Tamper detection flag"] pub type TAMP1F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP2F` reader - TAMPER2 detection flag"] pub type TAMP2F_R = crate::BitReader; #[doc = "Field `TAMP2F` writer - TAMPER2 detection flag"] pub type TAMP2F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `TAMP3F` reader - TAMPER3 detection flag"] pub type TAMP3F_R = crate::BitReader; #[doc = "Field `TAMP3F` writer - TAMPER3 detection flag"] pub type TAMP3F_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O>; #[doc = "Field `RECALPF` reader - Recalibration pending Flag"] pub type RECALPF_R = crate::BitReader; impl R { #[doc = "Bit 0 - Alarm A write flag"] #[inline(always)] pub fn alrawf(&self) -> ALRAWF_R { ALRAWF_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - Alarm B write flag"] #[inline(always)] pub fn alrbwf(&self) -> ALRBWF_R { ALRBWF_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - Wakeup timer write flag"] #[inline(always)] pub fn wutwf(&self) -> WUTWF_R { WUTWF_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - Shift operation pending"] #[inline(always)] pub fn shpf(&self) -> SHPF_R { SHPF_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - Initialization status flag"] #[inline(always)] pub fn inits(&self) -> INITS_R { INITS_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - Registers synchronization flag"] #[inline(always)] pub fn rsf(&self) -> RSF_R { RSF_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - Initialization flag"] #[inline(always)] pub fn initf(&self) -> INITF_R { INITF_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - Initialization mode"] #[inline(always)] pub fn init(&self) -> INIT_R { INIT_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - Alarm A flag"] #[inline(always)] pub fn alraf(&self) -> ALRAF_R { ALRAF_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - Alarm B flag"] #[inline(always)] pub fn alrbf(&self) -> ALRBF_R { ALRBF_R::new(((self.bits >> 9) & 1) != 0) } #[doc = "Bit 10 - Wakeup timer flag"] #[inline(always)] pub fn wutf(&self) -> WUTF_R { WUTF_R::new(((self.bits >> 10) & 1) != 0) } #[doc = "Bit 11 - Timestamp flag"] #[inline(always)] pub fn tsf(&self) -> TSF_R { TSF_R::new(((self.bits >> 11) & 1) != 0) } #[doc = "Bit 12 - Timestamp overflow flag"] #[inline(always)] pub fn tsovf(&self) -> TSOVF_R { TSOVF_R::new(((self.bits >> 12) & 1) != 0) } #[doc = "Bit 13 - Tamper detection flag"] #[inline(always)] pub fn tamp1f(&self) -> TAMP1F_R { TAMP1F_R::new(((self.bits >> 13) & 1) != 0) } #[doc = "Bit 14 - TAMPER2 detection flag"] #[inline(always)] pub fn tamp2f(&self) -> TAMP2F_R { TAMP2F_R::new(((self.bits >> 14) & 1) != 0) } #[doc = "Bit 15 - TAMPER3 detection flag"] #[inline(always)] pub fn tamp3f(&self) -> TAMP3F_R { TAMP3F_R::new(((self.bits >> 15) & 1) != 0) } #[doc = "Bit 16 - Recalibration pending Flag"] #[inline(always)] pub fn recalpf(&self) -> RECALPF_R { RECALPF_R::new(((self.bits >> 16) & 1) != 0) } } impl W { #[doc = "Bit 3 - Shift operation pending"] #[inline(always)] #[must_use] pub fn shpf(&mut self) -> SHPF_W<ISR_SPEC, 3> { SHPF_W::new(self) } #[doc = "Bit 5 - Registers synchronization flag"] #[inline(always)] #[must_use] pub fn rsf(&mut self) -> RSF_W<ISR_SPEC, 5> { RSF_W::new(self) } #[doc = "Bit 6 - Initialization flag"] #[inline(always)] #[must_use] pub fn initf(&mut self) -> INITF_W<ISR_SPEC, 6> { INITF_W::new(self) } #[doc = "Bit 7 - Initialization mode"] #[inline(always)] #[must_use] pub fn init(&mut self) -> INIT_W<ISR_SPEC, 7> { INIT_W::new(self) } #[doc = "Bit 8 - Alarm A flag"] #[inline(always)] #[must_use] pub fn alraf(&mut self) -> ALRAF_W<ISR_SPEC, 8> { ALRAF_W::new(self) } #[doc = "Bit 9 - Alarm B flag"] #[inline(always)] #[must_use] pub fn alrbf(&mut self) -> ALRBF_W<ISR_SPEC, 9> { ALRBF_W::new(self) } #[doc = "Bit 10 - Wakeup timer flag"] #[inline(always)] #[must_use] pub fn wutf(&mut self) -> WUTF_W<ISR_SPEC, 10> { WUTF_W::new(self) } #[doc = "Bit 11 - Timestamp flag"] #[inline(always)] #[must_use] pub fn tsf(&mut self) -> TSF_W<ISR_SPEC, 11> { TSF_W::new(self) } #[doc = "Bit 12 - Timestamp overflow flag"] #[inline(always)] #[must_use] pub fn tsovf(&mut self) -> TSOVF_W<ISR_SPEC, 12> { TSOVF_W::new(self) } #[doc = "Bit 13 - Tamper detection flag"] #[inline(always)] #[must_use] pub fn tamp1f(&mut self) -> TAMP1F_W<ISR_SPEC, 13> { TAMP1F_W::new(self) } #[doc = "Bit 14 - TAMPER2 detection flag"] #[inline(always)] #[must_use] pub fn tamp2f(&mut self) -> TAMP2F_W<ISR_SPEC, 14> { TAMP2F_W::new(self) } #[doc = "Bit 15 - TAMPER3 detection flag"] #[inline(always)] #[must_use] pub fn tamp3f(&mut self) -> TAMP3F_W<ISR_SPEC, 15> { TAMP3F_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 = "initialization and status register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`isr::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 [`isr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct ISR_SPEC; impl crate::RegisterSpec for ISR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`isr::R`](R) reader structure"] impl crate::Readable for ISR_SPEC {} #[doc = "`write(|w| ..)` method takes [`isr::W`](W) writer structure"] impl crate::Writable for ISR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets ISR to value 0x07"] impl crate::Resettable for ISR_SPEC { const RESET_VALUE: Self::Ux = 0x07; }
extern crate rust_project; use rust_project::project::{string_to_integer,integer_to_string}; #[test] fn public_test_to_int() { assert_eq!(132, string_to_integer("one three two")); assert_eq!(62, string_to_integer("six two")); } #[test] fn public_test_to_string() { assert_eq!("one three two", integer_to_string(132)); assert_eq!("nine two three", integer_to_string(923)); }
use exonum::{ crypto::PublicKey, }; use std::collections::HashMap; use super::proto; #[derive(Clone, Debug, ProtobufConvert)] #[exonum(pb = "proto::Contract", serde_pb_convert)] pub struct Contract { pub pub_key: PublicKey, pub code: String, pub state: HashMap<String, String>, } impl Contract { pub fn new(pub_key: &PublicKey, code: &str) -> Self { Self { pub_key: *pub_key, code: code.to_string(), state: HashMap::new(), } } }
//! Provides a representation for one or many ready to use compute devices. use std::any::{Any, TypeId}; use super::error::Result; use super::memory::Memory; use super::tensor::TensorShape; /// An device capable of processing data. /// /// A compute device can be a single device, or multiple devices treated as a single device. /// /// ## Load Balancing Multiple Devices /// /// todo.. pub trait ComputeDevice: Any + Allocate<f64> + Allocate<f32> { } /// Implemented by allocators. pub trait Allocate<T> { /// Allocates memory on the device. fn allocate(&self, shape: &TensorShape) -> Result<Box<Memory<T>>>; } impl ComputeDevice { /// Returns `true` if the boxed type is the same as `T`. #[inline] pub fn is<T>(&self) -> bool where T: ComputeDevice { // Get TypeId of the type this function is instantiated with let t = TypeId::of::<T>(); // Get TypeId of the type in the trait object let boxed = self.get_type_id(); // Compare both TypeIds on equality t == boxed } /// Returns some reference to the boxed value if it is of type `T`, or /// `None` if it isn't. #[inline] pub fn downcast_ref<T>(&self) -> Option<&T> where T: ComputeDevice { if self.is::<T>() { unsafe { Some(&*(self as *const ComputeDevice as *const T)) } } else { None } } }
#[derive(Debug)] struct User { email: String, username: String, active: bool, sign_in_count: u32, } struct Color(i32, i32, i32); fn build_user(email: String, username: String) -> User { User { email, username, active: true, sign_in_count: 0, } } fn main() { let user = build_user(String::from("Heisenberg"), String::from("mail@mail.com")); println!("Hello to the User: {:?}!", user); let user2 = User { username: String::from("Jesse"), email: String::from("mail@mail.com"), ..user }; println!("Hello to the User: {:?}!", user2); let color = Color(1, 2, 3); println!("Pretty colors! {}, {}, {}!", color.0, color.1, color.2); }
//! Extra utilities for spawning tasks mod spawn_pinned; pub use spawn_pinned::LocalPoolHandle;
use crate::register::Register; use liblog::storage; use std::sync::Arc; use warp::Filter; // TODO: make AsyncWAL and LogWriter a type arguments. pub async fn main<LW: storage::LogWriter<u64> + Sync + Send + 'static>( log_writer: LW, ) -> Result<(), LW::Error> { let reg = Arc::new(Register::new(0, log_writer)); let routes = warp::post() .and(warp::path("inc")) .and(warp::path::param()) .and(warp::any().map(move || reg.clone())) .and_then(update); warp::serve(routes).run(([127, 0, 0, 1], 3030)).await; Ok(()) } async fn update<L>( val: u64, reg: Arc<Register<L>>, ) -> Result<impl warp::Reply, std::convert::Infallible> where L: storage::LogWriter<u64>, { match reg.add_value(val).await { Ok(res) => Ok(format!("You got {}.\n", res)), Err(e) => Ok(format!("Error: {}", e)), } }
use crate::common::LmdbInstance; use holochain_json_api::json::JsonString; use holochain_persistence_api::{ cas::{ content::{Address, AddressableContent, Content}, storage::ContentAddressableStorage, }, error::{PersistenceError, PersistenceResult}, reporting::{ReportStorage, StorageReport}, }; use rkv::{ error::{DataError, StoreError}, Value, }; use std::{ fmt::{Debug, Error, Formatter}, path::Path, }; use uuid::Uuid; const CAS_BUCKET: &str = "cas"; #[derive(Clone)] pub struct LmdbStorage { id: Uuid, lmdb: LmdbInstance, } impl Debug for LmdbStorage { fn fmt(&self, f: &mut Formatter) -> Result<(), Error> { f.debug_struct("LmdbStorage").field("id", &self.id).finish() } } impl LmdbStorage { pub fn new<P: AsRef<Path> + Clone>( db_path: P, initial_map_bytes: Option<usize>, ) -> LmdbStorage { LmdbStorage { id: Uuid::new_v4(), lmdb: LmdbInstance::new(CAS_BUCKET, db_path, initial_map_bytes), } } } impl LmdbStorage { fn lmdb_add(&mut self, content: &dyn AddressableContent) -> Result<(), StoreError> { self.lmdb.add( content.address(), &Value::Json(&content.content().to_string()), ) } fn lmdb_fetch(&self, address: &Address) -> Result<Option<Content>, StoreError> { let env = self.lmdb.manager.read().unwrap(); let reader = env.read()?; match self.lmdb.store.get(&reader, address.clone()) { Ok(Some(value)) => match value { Value::Json(s) => Ok(Some(JsonString::from_json(s))), _ => Err(StoreError::DataError(DataError::Empty)), }, Ok(None) => Ok(None), Err(e) => Err(e), } } } impl ContentAddressableStorage for LmdbStorage { fn add(&mut self, content: &dyn AddressableContent) -> PersistenceResult<()> { self.lmdb_add(content) .map_err(|e| PersistenceError::from(format!("CAS add error: {}", e))) } fn contains(&self, address: &Address) -> PersistenceResult<bool> { self.fetch(address).map(|result| match result { Some(_) => true, None => false, }) } fn fetch(&self, address: &Address) -> PersistenceResult<Option<Content>> { self.lmdb_fetch(address) .map_err(|e| PersistenceError::from(format!("CAS fetch error: {}", e))) } fn get_id(&self) -> Uuid { self.id } } impl ReportStorage for LmdbStorage { fn get_storage_report(&self) -> PersistenceResult<StorageReport> { Ok(StorageReport::new(0)) // TODO: implement this } } #[cfg(test)] mod tests { use crate::cas::lmdb::LmdbStorage; use holochain_json_api::json::RawString; use holochain_persistence_api::{ cas::{ content::{Content, ExampleAddressableContent, OtherExampleAddressableContent}, storage::{CasBencher, ContentAddressableStorage, StorageTestSuite}, }, reporting::{ReportStorage, StorageReport}, }; use tempfile::{tempdir, TempDir}; pub fn test_lmdb_cas() -> (LmdbStorage, TempDir) { let dir = tempdir().expect("Could not create a tempdir for CAS testing"); (LmdbStorage::new(dir.path(), None), dir) } #[bench] fn bench_lmdb_cas_add(b: &mut test::Bencher) { let (store, _) = test_lmdb_cas(); CasBencher::bench_add(b, store); } #[bench] fn bench_lmdb_cas_fetch(b: &mut test::Bencher) { let (store, _) = test_lmdb_cas(); CasBencher::bench_fetch(b, store); } #[test] /// show that content of different types can round trip through the same storage /// this is copied straight from the example with a file CAS fn lmdb_content_round_trip_test() { let (cas, _dir) = test_lmdb_cas(); let test_suite = StorageTestSuite::new(cas); test_suite.round_trip_test::<ExampleAddressableContent, OtherExampleAddressableContent>( RawString::from("foo").into(), RawString::from("bar").into(), ); } #[test] fn lmdb_report_storage_test() { let (mut cas, _) = test_lmdb_cas(); // add some content cas.add(&Content::from_json("some bytes")) .expect("could not add to CAS"); assert_eq!(cas.get_storage_report().unwrap(), StorageReport::new(0),); // add some more cas.add(&Content::from_json("more bytes")) .expect("could not add to CAS"); assert_eq!(cas.get_storage_report().unwrap(), StorageReport::new(0 + 0),); } }
use crate::nes::cartridge::cartridge::Cartridge; use super::register; use crate::ppu::register::{PpuStatus, PpuCtrl, PpuStatusTrait, PpuCtrlTrait}; use crate::ppu::nametable; use crate::ppu::nametable::NametableMemory; const PATTERN_TABLE_SIZE: usize = 0x1000; const SCANLINE_PRE_RENDER: u16 = 261; const SCANLINE_VISIBLE_START: u16 = 0; const SCANLINE_VISIBLE_END: u16 = 239; const SCANLINE_POST_RENDER: u16 = 240; const SCANLINE_VBLANK_START: u16 = 241; const SCANLINE_VBLANK_END: u16 = 260; const SCANLINE_CYCLE_COUNT: u16 = 341; const PIXEL_OUTPUT_CYCLE_OFFSET: u16 = 1; pub const FRAMEBUFFER_WIDTH: usize = 256; pub const FRAMEBUFFER_HEIGHT: usize = 240; const FRAMEBUFFER_SIZE: usize = FRAMEBUFFER_WIDTH * FRAMEBUFFER_HEIGHT; const PALETTE_RAM_SIZE : usize = 0x20; const PALETTE_START_ADDRESS: u16 = 0x3F00; const PALETTE_END_ADDRESS: u16 = 0x3FFF; const PATTERN_TABLE_START : u16 = 0; const PATTERN_TABLE_END :u16 = 0x1FFF; const VRAM_SIZE:u16 = 0x4000; pub struct Ppu { cartridge_ptr: *mut Cartridge, ppuctrl: PpuCtrl, ppumask: u8, ppustatus: PpuStatus, oamaddr: u8, // TODO oamdata ppuscroll: u16, ppuaddr: u16, latch: Option<u8>, nametable_memory: NametableMemory, palette_ram: [u8; PALETTE_RAM_SIZE], vram_read_buffer :u8, // rendering variables scanline: u16, scanline_cycle: u16, framecount: u64, framebuffer: [u8; FRAMEBUFFER_SIZE], v_horizontal: u8, v_vertical:u8, _tmp_nt_byte :u8, _tmp_at_byte:u8, _tmp_pt_lo:u8, _tmp_pt_hi: u8, bg_pattern_lo_shift: u16, bg_pattern_hi_shift: u16, } impl Ppu { pub fn new(cartridge_ptr: *mut Cartridge) -> Ppu { let cartridge = unsafe { &*cartridge_ptr }; Ppu { cartridge_ptr, ppuctrl: 0, ppumask: 0, ppustatus: 0, oamaddr: 0, ppuscroll: 0, ppuaddr: 0, latch: None, nametable_memory: NametableMemory::new(cartridge.get_mirroring()), palette_ram: [0; PALETTE_RAM_SIZE], vram_read_buffer: 0, scanline: SCANLINE_PRE_RENDER, scanline_cycle: 0, framecount: 0, framebuffer: [0; FRAMEBUFFER_SIZE], v_horizontal : 2, v_vertical : 30, _tmp_nt_byte : 0, _tmp_at_byte : 0, _tmp_pt_lo : 0, _tmp_pt_hi : 0, bg_pattern_lo_shift: 0, bg_pattern_hi_shift: 0, } } pub fn write_register(&mut self, address: u16, data: u8) { match address % register::REGISTER_SIZE { register::PPUCTRL_OFFSET => { self.ppuctrl = data; } register::PPUMASK_OFFSET => { self.ppumask = data; } register::OAMADDR_OFFSET => { self.oamaddr = data; } register::OAMDATA_OFFSET => { self._write_oamdata(data); } register::PPUSCROLL_OFFSET => { self._write_ppuscroll(data); } register::PPUADDR_OFFSET => { self._write_ppuaddr(data); } register::PPUDATA_OFFSET => { self._write_ppudata(data); } _ => { println!("CRASH ppu::write_register ${:04X} = ${:02X}", address, data); unreachable!() } } } pub fn read_register(&mut self, address: u16) -> u8 { match address % register::REGISTER_SIZE { register::PPUSTATUS_OFFSET => { let status = self.ppustatus; self.ppustatus.clear_vblank(); self.latch = None; status } register::PPUDATA_OFFSET => { self._read_ppudata() } _ => { println!("CRASH ppu::read_register ${:04X}", address); unreachable!() } } } fn _write_oamdata(&mut self, data: u8) { // TODO write oamdata; // println!("writing oamdata"); } fn _write_ppuaddr(&mut self, data: u8) { match self.latch { Some(hi) => { self.ppuaddr = (((hi as u16) << 8) + data as u16) % VRAM_SIZE; self.latch = None; } None => { self.latch = Some(data); } } } fn _write_ppuscroll(&mut self, data: u8) { match self.latch { Some(hi) => { self.ppuscroll = ((hi as u16) << 8) + data as u16; } None => { self.latch = Some(data); } } } fn _read_ppudata(&mut self) -> u8 { let mut return_value = self.vram_read_buffer; match self.ppuaddr { PATTERN_TABLE_START..=PATTERN_TABLE_END => unsafe { self.vram_read_buffer = (&mut *self.cartridge_ptr).read_chr(self.ppuaddr); } nametable::START_ADDRESS..=nametable::END_ADDRESS => { self.vram_read_buffer = self.nametable_memory.read(self.ppuaddr); } nametable::MIRROR_START_ADDRESS..=nametable::MIRROR_END_ADDRESS => { let mirrored_address = self.ppuaddr - 0x1000; self.vram_read_buffer = self.nametable_memory.read(mirrored_address); } PALETTE_START_ADDRESS..=PALETTE_END_ADDRESS => { let mirrored_address = self.ppuaddr - 0x1000; return_value = self.palette_ram[(mirrored_address as usize % PALETTE_RAM_SIZE)]; self.vram_read_buffer = self.nametable_memory.read(mirrored_address); } _ => { println!("_read_ppudata {:04x}", self.ppuaddr); unreachable!() } } self.ppuaddr += self.ppuctrl.vram_address_increment(); if self.ppuaddr > VRAM_SIZE { self.ppuaddr = self.ppuaddr % VRAM_SIZE; } return_value } fn _write_ppudata(&mut self, data: u8) { match self.ppuaddr { PATTERN_TABLE_START..=PATTERN_TABLE_END => unsafe { (&mut *self.cartridge_ptr).write_chr(self.ppuaddr, data); } nametable::START_ADDRESS..=nametable::END_ADDRESS => { self.nametable_memory.write(self.ppuaddr, data); } nametable::MIRROR_START_ADDRESS..=nametable::MIRROR_END_ADDRESS => { let mirrored_address = self.ppuaddr - 0x1000; self.nametable_memory.write(mirrored_address, data); } PALETTE_START_ADDRESS..=PALETTE_END_ADDRESS => { self.palette_ram[self.ppuaddr as usize % PALETTE_RAM_SIZE]; } _ => { println!("_write_ppudata {:04x}", self.ppuaddr); unreachable!() } } self.ppuaddr += self.ppuctrl.vram_address_increment(); if self.ppuaddr > VRAM_SIZE { self.ppuaddr = self.ppuaddr % VRAM_SIZE; } } pub fn _output_framebuffer_pixel(&mut self) { match self.scanline { SCANLINE_VISIBLE_START..=SCANLINE_VISIBLE_END => { if self.scanline_cycle >= PIXEL_OUTPUT_CYCLE_OFFSET && self.scanline_cycle < (FRAMEBUFFER_WIDTH as u16 - PIXEL_OUTPUT_CYCLE_OFFSET) { let pixel = self.scanline as usize * FRAMEBUFFER_WIDTH + self.scanline_cycle as usize - PIXEL_OUTPUT_CYCLE_OFFSET as usize; self.framebuffer[pixel] = self._next_pixel_value(); } } _ => {} } } pub fn _next_pixel_value(&mut self) -> u8 { let lo = (self.bg_pattern_lo_shift >> 15) as u8; let hi = (self.bg_pattern_hi_shift >> 15) as u8; self.bg_pattern_lo_shift <<= 1; self.bg_pattern_hi_shift <<= 1; (hi << 1)+ lo } fn _prerender_scanline(&mut self) { self._process_scanline(); match self.scanline_cycle { 1 => { self.ppustatus.clear_vblank(); // TODO clear sprite overflow } 280..=304 => { self.v_vertical = 0; } _ => {} } } fn _inc_v_horizontal(&mut self) { self.v_horizontal += 1; if self.v_horizontal > 32 { self.v_horizontal = 0; } } fn _inc_v_vertical(&mut self) { self.v_vertical += 1; if self.v_vertical >= 240 { self.v_vertical = 0; } } fn _reset_v_horizontal(&mut self) { self.v_horizontal = 0; } fn _fetch_nt_byte(&mut self) { let fetch_addr = (self.v_horizontal as u16 + ((self.v_vertical / 8)as u16 * 32)) + 0x2000; // println!("v.x={} v.y={} scanline={} cycle={}, fetch_addr={:04x}", self.v_horizontal , self.v_vertical, self.scanline, self.scanline_cycle, fetch_addr); self._tmp_nt_byte = self.nametable_memory.read(fetch_addr); if self._tmp_nt_byte > 0 { // println!("nt byte {} scanline={} cycle={}", self._tmp_nt_byte, self.scanline, self.scanline_cycle); } } fn _fetch_bg_lo_byte(&mut self) { let addr = (self._tmp_nt_byte as u16 * 16) + (self.v_vertical % 8) as u16; self._tmp_pt_lo = unsafe { (*self.cartridge_ptr).read_chr(addr + self.ppuctrl.bg_pattern_table_addr()) }; // TODO patterntable offset } fn _fetch_bg_hi_byte(&mut self) { let addr = (self._tmp_nt_byte as u16 * 16 + (self.v_vertical % 8) as u16) + 8; self._tmp_pt_hi = unsafe { (*self.cartridge_ptr).read_chr(addr + self.ppuctrl.bg_pattern_table_addr()) }; // TODO patterntable offset } fn _reload_shift_registers(&mut self) { self.bg_pattern_lo_shift = (self.bg_pattern_lo_shift & 0xFF00) | self._tmp_pt_lo as u16; self.bg_pattern_hi_shift = (self.bg_pattern_hi_shift & 0xFF00) | self._tmp_pt_hi as u16; } fn _shift_byte(&mut self) { self.bg_pattern_lo_shift <<= 8; self.bg_pattern_hi_shift <<= 8; } fn _process_scanline(&mut self) { let cycle_mod = self.scanline_cycle % 8; match self.scanline_cycle { 0 => {} // Idle 1..=256 => { if cycle_mod == 1 && self.scanline_cycle >= 9 { //Reload shift registers self._reload_shift_registers(); } match cycle_mod { 0 => { self._inc_v_horizontal(); } 1 => { self._fetch_nt_byte(); } 3 => { // Attribute } 5 => { // Pattern lo self._fetch_bg_lo_byte(); } 7 => { // Pattern hi self._fetch_bg_hi_byte(); } _ => {} } if self.scanline_cycle == 256 { self._inc_v_vertical(); } } 257 => { self._reset_v_horizontal(); } 321 => { self._fetch_nt_byte(); } 325 => { self._fetch_bg_lo_byte(); } 327 => { self._fetch_bg_hi_byte(); } 328 => { self._inc_v_horizontal(); } 329 => { self._fetch_nt_byte(); self._reload_shift_registers(); self._shift_byte(); } 333 => { self._fetch_bg_lo_byte(); } 335 => { self._fetch_bg_hi_byte(); } 336 => { self._inc_v_horizontal(); } 337 => { self._reload_shift_registers();} 338..=340 => { // Read unknown } _ => { } } } fn _vblank_scanline(&mut self) { if self.scanline_cycle == 1 { self.ppustatus.set_vblank(); } } pub fn tick(&mut self) -> bool { match self.scanline { // Pre-render scanline SCANLINE_PRE_RENDER => { self._prerender_scanline(); } SCANLINE_VISIBLE_START..=SCANLINE_VISIBLE_END => { self._process_scanline(); } SCANLINE_POST_RENDER => {} SCANLINE_VBLANK_START..=SCANLINE_VBLANK_END => { self._vblank_scanline(); } _ => { unreachable!() } } self._output_framebuffer_pixel(); self._increment_scanline_cycle(); if self.scanline == SCANLINE_POST_RENDER && self.scanline_cycle == 0 { true } else { false } } fn _increment_scanline_cycle(&mut self) { self.scanline_cycle += 1; if self.scanline_cycle == SCANLINE_CYCLE_COUNT { if self.scanline == SCANLINE_PRE_RENDER && self.framecount % 2 == 1 { self.scanline_cycle = 1; } else { self.scanline_cycle = 0; } self.scanline += 1; } if self.scanline > SCANLINE_PRE_RENDER { self.scanline = 0; self.framecount += 1; self.v_vertical = 0; // TODO } } pub fn patterntable_to_texture_data(&self, pattern_table_index: u8) -> [u8; 16384] { const PATTERN_TABLE_TILE_COUNT: usize = 256; const PATTERN_TABLE_TILE_WIDTH: usize = 8; const PATTERN_TABLE_TILE_HEIGHT: usize = 8; const PATTERN_TABLE_PLANE_SIZE: usize = 8; const PATTERN_TABLE_BYTES_PER_TILE: usize = PATTERN_TABLE_PLANE_SIZE * 2; const TEXTURE_DATA_WIDTH: usize = 128; // 128 x 128 values const TEXTURE_TILE_COUNT_WIDTH: usize = TEXTURE_DATA_WIDTH / PATTERN_TABLE_TILE_WIDTH; let cartridge = unsafe { &mut *self.cartridge_ptr }; let data = cartridge.read_chr_slice(pattern_table_index as u16 * PATTERN_TABLE_SIZE as u16, PATTERN_TABLE_SIZE); let mut target = [0; PATTERN_TABLE_TILE_COUNT * PATTERN_TABLE_TILE_WIDTH * PATTERN_TABLE_TILE_HEIGHT]; // For every tile for i in 0..PATTERN_TABLE_TILE_COUNT { // For every line in pattern for j in 0..PATTERN_TABLE_TILE_HEIGHT { let lo_plane = data[i * PATTERN_TABLE_BYTES_PER_TILE + j]; let hi_plane = data[i * PATTERN_TABLE_BYTES_PER_TILE + j + PATTERN_TABLE_PLANE_SIZE]; // For every pixel in line for k in 0..PATTERN_TABLE_TILE_WIDTH { let val = ((lo_plane >> k as u8) & 1) + (((hi_plane >> k as u8) & 1) << 1); let x = (i % TEXTURE_TILE_COUNT_WIDTH * PATTERN_TABLE_TILE_WIDTH) + PATTERN_TABLE_TILE_WIDTH - 1 - k; let y = (PATTERN_TABLE_TILE_HEIGHT * (i / TEXTURE_TILE_COUNT_WIDTH)) + j; let target_index = (y * TEXTURE_DATA_WIDTH + x) as usize; target[target_index] = val; } } } target } fn _read_memory(&self, address: u16) -> u8 { match address { 0..=0x1FFF => { let cartridge = unsafe { &mut *self.cartridge_ptr }; cartridge.read_chr(address) } 0x2000..=0x2FFF => { unimplemented!() } 0x3000..=0x3EFF => { // TODO ? unimplemented!() } 0x3F00..=0x3FFF => { // TODO Palette RAM indexes // TODO Mirror unimplemented!() } _ => { unreachable!() } } } fn _write_memory(&self, address: u16) -> u8 { match address { 0x2000..=0x2FFF => { unimplemented!() } 0x3000..=0x3EFF => { // TODO ? unimplemented!() } 0x3F00..=0x3FFF => { // TODO Palette RAM indexes // TODO Mirror unimplemented!() } _ => { unreachable!() } } } pub fn get_ppuctrl(&self) -> u8 { self.ppuctrl } pub fn get_ppumask(&self) -> u8 { self.ppumask } pub fn get_ppustatus(&self) -> u8 { self.ppustatus } pub fn get_oamaddr(&self) -> u8 { self.oamaddr } pub fn get_ppuscroll(&self) -> u16 { self.ppuscroll } pub fn get_nmi_signal(&self) -> bool { self.ppuctrl.generate_nmi() && self.ppustatus.is_vblank() } pub fn get_ppuaddr(&self) -> u16 { self.ppuaddr } pub fn get_framebuffer(&self) -> &[u8] { &self.framebuffer } }
extern crate my_rc; use my_rc::MyRc; use std::cell::Cell; use std::rc::Rc; macro_rules! assert_expected_eq_actual { ($a:expr, $b:expr) => ({ let (a, b) = (&$a, &$b); assert!(*a == *b, "\nExpected `{:?}` is not equal to Actual `{:?}`\nAssertion: `assert_expected_eq_actual!({}, {})`", *a, *b, stringify!($a), stringify!($b)); }) } struct D { d_count: Rc<Cell<i32>>, } impl Drop for D { fn drop(&mut self) { self.d_count.set(self.d_count.get() + 1); } } fn main() { let keep = { let rc = MyRc::new(5); { let rc2 = rc.clone(); } rc.consume() }; println!("{}", keep.is_ok()); }
use num_bigint::{BigUint, ToBigUint}; use num_integer::Integer; use num_traits::{ToPrimitive, Zero}; use std::sync::mpsc::*; use std::thread; use std::time::Instant; use std::io::BufWriter; use std::io::prelude::*; use std::fs::OpenOptions; fn main() { let num_threads: u64 = num_cpus::get() as u64; let (tx, rx) = channel::<BigUint>(); let (sen_timing, rec_timing) = channel::<bool>(); let end: BigUint = ubig_pow(10, 100); let file = OpenOptions::new() .write(true) .create(true) .open("rotatable.txt") .unwrap(); let mut buffer = BufWriter::new(file); println!("Starting {} threads...", num_threads); for i in 0u64..num_threads { let tx = tx.clone(); let sen_timing = sen_timing.clone(); let end = end.clone(); thread::spawn(move || { get_rotatable(tx, sen_timing, 10+i, end, num_threads); }); println!("Started thread {}", i); } // spawns a new thread to calculate the iterations / second thread::spawn(move || { let mut last_sent = Instant::now(); let mut iterations = 0; loop { rec_timing.recv().unwrap(); iterations += 1000; if last_sent.elapsed().as_secs() > 10 { println!("{:.2} iter/s", iterations as f64/last_sent.elapsed().as_secs() as f64); last_sent = Instant::now(); iterations = 0; } } }); loop { let rotatable = rx.recv().unwrap(); println!("{}", rotatable); if let Err(e) = buffer.write(&format!("{}\n", rotatable).into_bytes()) { panic!(e); } let _ = buffer.flush(); } } /// searches for numbers according to [euler-168](https://projecteuler.net/problem=168) /// the resulting numbers are sent via the tx-sender into a channel. /// every iteration a timing-boolean is sent in via the sen_time-sender to calculate /// the speed of the iterations fn get_rotatable(tx: Sender<BigUint>, sen_time: Sender<bool>, start: u64, end: BigUint, step: u64) { let mut num: BigUint = start.to_biguint().unwrap(); let mut count = 0; while num < end { if num.is_odd() || !(&num % 10 as u64).is_zero() { let mut digits = ubig_digits(num.clone()); let first = *digits.first().unwrap() as u64; let last = *digits.last().unwrap() as u64; if (last < 5 || first == last) && !(first % 2 == 0 && digits[1] % 2 != 0) && (first == last || first/2 >= last) { digits.rotate_left(1); let num_rotated = ubig_from_digits(digits); if (&num_rotated % &num).is_zero() { let _ = tx.send(num.clone()); } } } else { count += 1; if count > 100 { let _ = sen_time.send(true); count = 0; } } num += step; } } /// returns a vector containing the digits of the BigUint fn ubig_digits(big_number: BigUint) -> Vec<u8> { let mut num: BigUint = big_number; let mut digits: Vec<u8> = vec![]; let zero: BigUint = 0.to_biguint().unwrap(); let ten: BigUint = 10.to_biguint().unwrap(); while num > zero { let (quot, rem) = num.div_rem(&ten); num = quot; digits.push(rem.to_u8().unwrap()); } digits } /// returns a BigUint for a vector of digits fn ubig_from_digits(digits: Vec<u8>) -> BigUint { let mut num: BigUint = 0.to_biguint().unwrap(); for (index, digit) in digits.iter().enumerate() { num += ubig_pow(10, index) * digit; } num } /// returns ubig^exp fn ubig_pow(base: u128, exp: usize) -> BigUint { let mut num = base.to_biguint().unwrap(); if exp > 1 { for _ in 1..exp { num *= base; } } else if exp == 0 { num = 1.to_biguint().unwrap(); } num } #[allow(dead_code)] fn print_vector(vec: &[u8]) { for i in vec.iter() { print!("{}", i) } }
use shorthand::ShortHand; use std::collections::BTreeMap; #[derive(ShortHand, Default)] #[shorthand(enable(collection_magic))] struct Example { collection: BTreeMap<&'static str, usize>, irrelevant_field: usize, } fn main() { let _: &mut Example = Example::default().insert_collection("value", 0_usize); }
use std::sync::{Arc, Mutex, MutexGuard}; use crate::kv::StatefulKV; use svm_hash::{Blake3Hasher, Hasher}; use svm_types::{Address, State}; /// An Account-aware (and `State`-aware) key-value store interface responsible of /// mapping `u32` input keys (given as a 4 byte-length slice) to global keys under a raw key-value store. /// /// The mapping is dependant on the contextual `Account`'s `Address` (see the `new` method). pub struct AccountKVStore { pub(crate) account_addr: Address, pub(crate) kv: Arc<Mutex<dyn StatefulKV + Send>>, } impl StatefulKV for AccountKVStore { #[inline] #[must_use] fn get(&self, key: &[u8]) -> Option<Vec<u8>> { let key = self.build_key(key); self.kv().get(&key) } #[inline] fn set(&mut self, key: &[u8], value: &[u8]) { let key = self.build_key(key); self.kv().set(&key, value); } #[inline] fn discard(&mut self) { self.kv().discard(); } #[inline] fn flush(&mut self) { self.kv().flush(); } #[inline] #[must_use] fn checkpoint(&mut self) -> State { self.kv().checkpoint() } #[inline] #[must_use] fn rewind(&mut self, state: &State) { self.kv().rewind(state) } #[inline] #[must_use] fn head(&self) -> State { self.kv().head() } } impl AccountKVStore { /// Create a new `AccountStore` instance for `Address` `account_addr`. /// /// Delegates work to underlying key-value store `kv`. pub fn new(account_addr: Address, kv: &Arc<Mutex<dyn StatefulKV + Send>>) -> Self { let kv = Arc::clone(&kv); Self { account_addr, kv } } #[inline] fn build_key(&self, key: &[u8]) -> Vec<u8> { debug_assert_eq!(key.len(), 4); let mut buf = Vec::with_capacity(Address::len() + key.len()); buf.extend_from_slice(self.account_addr.as_slice()); buf.extend_from_slice(key); self.hash(&buf) } #[inline] fn hash(&self, bytes: &[u8]) -> Vec<u8> { Blake3Hasher::hash(bytes).to_vec() } fn kv(&self) -> MutexGuard<dyn StatefulKV + Send + 'static> { self.kv.try_lock().unwrap() } } impl Clone for AccountKVStore { fn clone(&self) -> Self { Self { account_addr: self.account_addr.clone(), kv: Arc::clone(&self.kv), } } }
use nu_engine::CallExt; use nu_protocol::ast::Call; use nu_protocol::ast::CellPath; use nu_protocol::engine::{Command, EngineState, Stack}; use nu_protocol::Category; use nu_protocol::Spanned; use nu_protocol::{Example, PipelineData, ShellError, Signature, Span, SyntaxShape, Value}; use std::sync::Arc; struct Arguments { pattern: String, column_paths: Vec<CellPath>, } #[derive(Clone)] pub struct SubCommand; impl Command for SubCommand { fn name(&self) -> &str { "str starts-with" } fn signature(&self) -> Signature { Signature::build("str starts-with") .required("pattern", SyntaxShape::String, "the pattern to match") .rest( "rest", SyntaxShape::CellPath, "optionally matches prefix of text by column paths", ) .category(Category::Strings) } fn usage(&self) -> &str { "Check if string starts with a pattern" } fn search_terms(&self) -> Vec<&str> { vec!["pattern", "match", "find", "search"] } fn run( &self, engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { operate(engine_state, stack, call, input) } fn examples(&self) -> Vec<Example> { vec![ Example { description: "Checks if string starts with 'my' pattern", example: "'my_library.rb' | str starts-with 'my'", result: Some(Value::Bool { val: true, span: Span::test_data(), }), }, Example { description: "Checks if string starts with 'my' pattern", example: "'Cargo.toml' | str starts-with 'Car'", result: Some(Value::Bool { val: true, span: Span::test_data(), }), }, Example { description: "Checks if string starts with 'my' pattern", example: "'Cargo.toml' | str starts-with '.toml'", result: Some(Value::Bool { val: false, span: Span::test_data(), }), }, ] } } fn operate( engine_state: &EngineState, stack: &mut Stack, call: &Call, input: PipelineData, ) -> Result<PipelineData, ShellError> { let pattern: Spanned<String> = call.req(engine_state, stack, 0)?; let options = Arc::new(Arguments { pattern: pattern.item, column_paths: call.rest(engine_state, stack, 1)?, }); let head = call.head; input.map( move |v| { if options.column_paths.is_empty() { action(&v, &options, head) } else { let mut ret = v; for path in &options.column_paths { let opt = options.clone(); let r = ret.update_cell_path( &path.members, Box::new(move |old| action(old, &opt, head)), ); if let Err(error) = r { return Value::Error { error }; } } ret } }, engine_state.ctrlc.clone(), ) } fn action(input: &Value, Arguments { pattern, .. }: &Arguments, head: Span) -> Value { match input { Value::String { val: s, .. } => { let starts_with = s.starts_with(pattern); Value::Bool { val: starts_with, span: head, } } other => Value::Error { error: ShellError::UnsupportedInput( format!( "Input's type is {}. This command only works with strings.", other.get_type() ), head, ), }, } } #[cfg(test)] mod tests { use super::*; #[test] fn test_examples() { use crate::test_examples; test_examples(SubCommand {}) } }
use clap::{App, Arg}; use ebnf_tools::*; use std::fs; fn main() { let matches = App::new("generate") .arg( Arg::with_name("file") .value_name("file") .takes_value(true) .required(true), ) .get_matches(); let opts = matches.value_of("file").unwrap(); let code = fs::read_to_string(opts).unwrap(); let ast_alloc = ASTAlloc::default(); let flatten_alloc = FlattenAlloc::default(); let ebnf = work(&code, &ast_alloc); if let Ok(ebnf) = ebnf { let res = flatten(&ebnf, &flatten_alloc); for rule in res { print!("{} ::=", rule.name); for prod in rule.prod { match prod { FlatProd::Terminal(name) | FlatProd::NonTerminal(name) => print!(" {}", name), FlatProd::Eps => print!(" _"), } } println!(); } } else { println!("{:?}", ebnf.unwrap_err()); } }
// Reported as issue #126, child leaks the string. use std; import std::task; fn child2(-s: str) { } fn main() { let x = task::spawn(bind child2("hi")); }
#![feature(nll, underscore_imports)] extern crate cgmath; extern crate pbrt; use std::sync::{ Arc, Mutex }; use cgmath::{ Deg, Matrix4 }; use pbrt::prelude::*; use pbrt::camera::PerspectiveCamera; use pbrt::film::Film; use pbrt::filter::TriangleFilter; use pbrt::integrator::{ Integrator, DirectLightingIntegrator, WhittedIntegrator }; use pbrt::integrator::LightStrategy; use pbrt::light::{ Light, PointLight }; use pbrt::material::MatteMaterial; use pbrt::math::{ AnimatedTransform, Transform }; use pbrt::primitive::GeometricPrimitive; use pbrt::sampler::StratifiedSampler; use pbrt::scene::Scene; use pbrt::shape::{ ShapeData, Sphere }; use pbrt::spectrum::{ SpectrumType, Spectrum as PbrtSpectrum }; use pbrt::texture::ConstantTexture; fn main() { let sphere = { let transform = { let transform = Matrix4::from_translation(Vector3f::new( float(0.0), float(0.0), float(0.0), )); let rot = Matrix4::from_angle_x(Deg(float(90.0))); Arc::new(Transform::new(transform * rot)) }; let data = ShapeData::new(transform, false); let radius = float(1.0); let sphere = Sphere::new(radius, -radius, radius, Deg(float(360.0)), data); Arc::new(sphere) }; let material = { let kd = ConstantTexture::new(Spectrum::from_rgb([ float(0.7), float(0.5), float(0.3), ], SpectrumType::Reflectance)); let kd = Arc::new(kd); let sigma = ConstantTexture::new(0.0); let sigma = Arc::new(sigma); MatteMaterial::new(kd, sigma, None) }; let material = Box::new(material); let primitive = GeometricPrimitive { shape: sphere, material: Some(material), area_light: None, medium_interface: None, }; let primitive = Arc::new(primitive); let light = { let transform = Matrix4::from_translation(Vector3f::new( float(5.0), float(0.0), float(0.0), )); let transform = Transform::new(transform); let transform = Arc::new(transform); let light = PointLight::new(Spectrum::from_rgb([ float(1.0), float(1.0), float(1.0), ], SpectrumType::Illumination) * float(10.0), transform); Box::new(light) }; let camera = { let film = { let full_resolution = Point2i::new(512, 512); let crop_window = Bounds2f::new( Point2f::new(float(0.0), float(0.0)), Point2f::new(float(1.0), float(1.0)), ); let filter = TriangleFilter::new(Vector2f::new(float(1.0), float(1.0))); let filter = Box::new(filter); let film = Film::new( full_resolution, crop_window, filter, float(5.0), float(1.0), String::from("test_image"), ); Arc::new(Mutex::new(film)) }; let transform = Matrix4::from_translation(Vector3f::new( float(0.0), float(0.0), float(5.0), )); let rot = Matrix4::from_angle_x(Deg(float(0.0))); let transform = Transform::new(transform * rot); let transform = Arc::new(transform); let transform = AnimatedTransform::new( transform.clone(), float(0.0), transform.clone(), float(1.0), ); let screen_window = Bounds2f::new( Point2f::new(float(-1.0), float(-1.0)), Point2f::new(float(1.0), float(1.0)), ); let camera = PerspectiveCamera::new( transform, screen_window, float(0.0), float(1.0), float(0.0), float(1.0), Deg(float(45.0)), film, None ); Arc::new(camera) }; let scene = Scene::new(primitive, vec![light]); let sampler = StratifiedSampler::new( 4, 4, true, 2, 123456789, ); let sampler = Box::new(sampler); // let mut integrator = WhittedIntegrator::new(2, camera, sampler); let mut integrator = DirectLightingIntegrator::new(2, LightStrategy::UniformSampleOne, camera, sampler); integrator.render(scene); }
use std::io::Write; use termcolor:: { Color, ColorChoice, ColorSpec, StandardStream, WriteColor }; pub trait Printer { fn print_single_banner_line( &mut self, banner_text : &str, banner_color : Color, path : &str); fn print( &mut self, text : &str); fn error( &mut self, text: &str); } #[derive(Clone)] pub struct StandardPrinter { } impl StandardPrinter { pub fn new() -> StandardPrinter { return StandardPrinter{}; } } impl Printer for StandardPrinter { fn print_single_banner_line( &mut self, banner_text : &str, banner_color : Color, path : &str) { let mut stdout = StandardStream::stdout(ColorChoice::Always); match stdout.set_color(ColorSpec::new().set_fg(Some(banner_color))) { Ok(_) => {}, Err(_error) => {}, } match write!(&mut stdout, "{}: ", banner_text) { Ok(_) => {}, Err(_error) => { /* If the write doesn't work, change the color back, but other than that, I don't know what to do. */ match stdout.set_color(ColorSpec::new().set_fg(None)) { Ok(_) => {}, Err(_error) => {}, } return } } match stdout.set_color(ColorSpec::new().set_fg(None)) { Ok(_) => {}, Err(_error) => {}, } match writeln!(&mut stdout, "{}", path) { Ok(_) => {}, Err(_error) => { // Again, just not sure what to do if write fails. }, } } fn print( &mut self, text : &str) { println!("{}", text); } fn error( &mut self, text : &str) { println!("{}", text); } } #[cfg(test)] pub struct EmptyPrinter { } #[cfg(test)] impl EmptyPrinter { pub fn new() -> EmptyPrinter { return EmptyPrinter{} } } #[cfg(test)] impl Printer for EmptyPrinter { fn print_single_banner_line( &mut self, _banner_text : &str, _banner_color : Color, _path : &str) { } fn print( &mut self, _text : &str) { } fn error( &mut self, _text: &str) { } }
pub mod opiterator; pub mod query; pub use memstore::storage_manager::StorageManager;
extern crate common; extern crate day2; use std::env::args; use std::fs::File; use std::io::BufReader; use std::process::exit; fn main() { let ar: Vec<String> = args().collect(); if ar.len() != 2 { eprintln!("Usage: {} <INPUT>", &ar[0]); exit(-1); } let input_file = File::open(&ar[1]).expect("Unable to open input file."); let words = common::read_lines(BufReader::new(input_file)).expect("Failed to read input."); let chksum = day2::checksum(&words); let similar = day2::locate_similar_packages(&words); println!( "Computed checksum: {}, similar packages: {:?}", chksum, similar ); }
pub mod display; pub mod mesh; pub mod shader;
//! # 830. 较大分组的位置 //! https://leetcode-cn.com/problems/positions-of-large-groups/ //! # 思路 //! 一次遍历,记录上一次的字符 pub struct Solution; impl Solution { pub fn large_group_positions(s: String) -> Vec<Vec<i32>> { if s.len() < 3 { return vec![]; } let bytes = s.as_bytes(); let mut ans = vec![]; let mut pre_c = bytes[0]; let mut start = 0; let mut end = 0; for i in 1..bytes.len() { if bytes[i] == pre_c { end = i; } else { if (end - start + 1) >= 3 { ans.push(vec![start as i32, end as i32]); } start = i; end = i; pre_c = bytes[i]; } } if (end - start + 1) >= 3 { ans.push(vec![start as i32, end as i32]); } ans } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!( super::Solution::large_group_positions("abbxxxxzzzyycccccgfesfdsaeee".into()), vec![vec![3, 6], vec![7, 9], vec![12, 16], vec![25, 27]] ); } }
use message_parsing; pub trait AiInterface { fn update_game_state(&self, state: &GameState) -> String; fn get_bot_name(&self) -> String; } #[derive(Default, Debug)] pub struct GameState { pub player_direction: message_parsing::Direction, pub opponent_direction: message_parsing::Direction, pub deck: Vec<message_parsing::Card>, pub colors: Vec<String>, pub colors_vec: Vec<message_parsing::Color>, pub claim_status: Vec<message_parsing::ClaimStatus>, pub opponent_side: Vec<Vec<message_parsing::Card>>, pub player_side: Vec<Vec<message_parsing::Card>>, pub player_hand: Vec<message_parsing::Card>, } impl GameState { pub fn color_from_string(&self, name: &String) -> message_parsing::Color { if let Some(index) = self.colors.iter().position(|i| *i == *name) { match index { 0 => message_parsing::Color::Color1, 1 => message_parsing::Color::Color2, 2 => message_parsing::Color::Color3, 3 => message_parsing::Color::Color4, 4 => message_parsing::Color::Color5, _ => message_parsing::Color::Color6, } } else { message_parsing::Color::Color1 } } pub fn string_from_color(&self, color: message_parsing::Color) -> String { match color { message_parsing::Color::Color1 => self.colors[0].clone(), message_parsing::Color::Color2 => self.colors[1].clone(), message_parsing::Color::Color3 => self.colors[2].clone(), message_parsing::Color::Color4 => self.colors[3].clone(), message_parsing::Color::Color5 => self.colors[4].clone(), message_parsing::Color::Color6 => self.colors[5].clone(), } } pub fn convert_card_string_to_card(&self, cs: &message_parsing::CardString) -> message_parsing::Card { message_parsing::Card { number: cs.number, color: self.color_from_string(&cs.color), } } pub fn convert_vector_card_string_to_cards(&self, cs: &Vec<message_parsing::CardString>) -> Vec<message_parsing::Card> { let mut card_vec: Vec<message_parsing::Card> = vec![]; for card in cs { card_vec.push(self.convert_card_string_to_card(card)); } card_vec } } #[derive(Default)] pub struct GameHandler { pub state: GameState, } impl GameHandler { pub fn run_one_round(&mut self, ai: &AiInterface, message: String) { let x = message_parsing::parse_message(message); match x { message_parsing::Message::OpponentPlay { number: _, card } => { let card = self.state.convert_card_string_to_card(&card); if let Some(index) = self.state.deck.iter().position(|i| *i == card) { self.state.deck.remove(index); } } message_parsing::Message::PlayerHand { direction: _, cards } => { let cards = self.state.convert_vector_card_string_to_cards(&cards); for card in &cards { if let Some(index) = self.state.deck.iter().position(|i| *i == *card) { self.state.deck.remove(index); } } self.state.player_hand = cards; } message_parsing::Message::FlagStatus { flag_num: num, direction, cards } => { let cards = self.state.convert_vector_card_string_to_cards(&cards); for card in &cards { if let Some(index) = self.state.deck.iter().position(|i| *i == *card) { self.state.deck.remove(index); } } if self.state.player_side.len() == 0 || self.state.opponent_side.len() == 0 { for _ in 1..10 { self.state.player_side.push(vec![]); self.state.opponent_side.push(vec![]); } } if direction == self.state.player_direction { self.state.player_side[(num - 1) as usize] = cards; } else { self.state.opponent_side[(num - 1) as usize] = cards; } } message_parsing::Message::FlagClaimStatus { flags_claimed: claims } => { self.state.claim_status = claims; } message_parsing::Message::PlayerDirection { direction, .. } => { self.state.player_direction = if direction == message_parsing::Direction::North { message_parsing::Direction::North } else { message_parsing::Direction::South }; self.state.opponent_direction = if direction == message_parsing::Direction::South { message_parsing::Direction::North } else { message_parsing::Direction::South }; println!("player {} {}", message_parsing::get_direction_string(direction), ai.get_bot_name()); } message_parsing::Message::ColorNames { colors } => { for _ in 1..10 { self.state.player_side.push(vec![]); self.state.opponent_side.push(vec![]); self.state.claim_status.push(message_parsing::ClaimStatus::Unclaimed); } self.state.colors = colors.clone(); self.state.colors_vec = vec![]; for color in &colors { let temp = self.state.color_from_string(color); { self.state.colors_vec.push(temp); } } for i in 1..10 { for x in colors.to_vec() { let temp = self.state.color_from_string(&x); { self.state.deck.push(message_parsing::Card { color: temp, number: i, }) }; } } } message_parsing::Message::PlayCard => { println!("{}", ai.update_game_state(&self.state)); } _ => {} } } } #[cfg(test)] mod test_game_state { use super::*; use message_parsing; use message_parsing as mp; struct TestAi { } impl AiInterface for TestAi { fn update_game_state(&self, _: &GameState) -> String { return String::from("play 1 red,1"); } fn get_bot_name(&self) -> String { return String::from("rusty_battleline_bot"); } } #[test] fn starter_player_check() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; handler.run_one_round(&ai, String::from("player north name")); assert!(message_parsing::Direction::North == handler.state.player_direction); assert!(message_parsing::Direction::South == handler.state.opponent_direction); handler.run_one_round(&ai, String::from("player south name")); assert!(message_parsing::Direction::South == handler.state.player_direction); assert!(message_parsing::Direction::North == handler.state.opponent_direction); } #[test] fn starter_deck_check() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; let colors = vec![String::from("a"), String::from("b"), String::from("c"), String::from("d"), String::from("e"), String::from("f")]; let colors_vec = vec![mp::Color::Color1, mp::Color::Color2, mp::Color::Color3, mp::Color::Color4, mp::Color::Color5, mp::Color::Color6]; handler.run_one_round(&ai, String::from("colors a b c d e f")); assert_eq!(54, handler.state.deck.len()); assert_eq!(colors, handler.state.colors); assert_eq!(colors_vec, handler.state.colors_vec); } #[test] fn claim_status_check() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; let claims = vec![mp::ClaimStatus::North, mp::ClaimStatus::South, mp::ClaimStatus::South, mp::ClaimStatus::North, mp::ClaimStatus::Unclaimed, mp::ClaimStatus::Unclaimed, mp::ClaimStatus::North, mp::ClaimStatus::South, mp::ClaimStatus::North, ]; handler.run_one_round(&ai, String::from("flag claim-status north south south north unclaimed \ unclaimed north south north")); assert_eq!(9, handler.state.claim_status.len()); assert_eq!(claims, handler.state.claim_status); } #[test] fn sides_check() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; let mut expected: Vec<Vec<mp::Card>> = Vec::with_capacity(9); for _ in 1..10 { expected.push(vec![]); } expected[0] = vec![mp::Card { color: mp::Color::Color1, number: 3, }, mp::Card { color: mp::Color::Color2, number: 7, }]; handler.run_one_round(&ai, String::from("colors red blue 3 4 5 6")); handler.run_one_round(&ai, String::from("player north name")); handler.run_one_round(&ai, String::from("flag 1 cards north red,3 blue,7")); assert_eq!(expected, handler.state.player_side); } #[test] fn sides_check_1() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; let mut expected: Vec<Vec<mp::Card>> = Vec::with_capacity(9); for _ in 1..10 { expected.push(vec![]); } expected[1] = vec![mp::Card { color: mp::Color::Color1, number: 3, }, mp::Card { color: mp::Color::Color2, number: 7, }]; handler.run_one_round(&ai, String::from("colors red blue 3 4 5 6")); handler.run_one_round(&ai, String::from("player north name")); handler.run_one_round(&ai, String::from("flag 2 cards south red,3 blue,7")); assert_eq!(expected, handler.state.opponent_side); } #[test] fn remove_card_when_opponent_played() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; let expected_card = mp::Card { color: mp::Color::Color1, number: 7, }; handler.run_one_round(&ai, String::from("colors a b c d e f")); assert!(handler.state.deck.contains(&expected_card)); handler.run_one_round(&ai, String::from("opponent play 1 a,7")); assert_eq!(53, handler.state.deck.len()); assert!(!handler.state.deck.contains(&expected_card)); } #[test] fn remove_card_when_given_player_hand() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; let expected_cards = vec![mp::Card { color: mp::Color::Color1, number: 7, }, mp::Card { color: mp::Color::Color3, number: 3, }]; handler.run_one_round(&ai, String::from("colors a b c d e f")); handler.run_one_round(&ai, String::from("player north name")); for x in &expected_cards { assert!(handler.state.deck.contains(&x)); } handler.run_one_round(&ai, String::from("player north hand a,7 c,3")); assert_eq!(52, handler.state.deck.len()); for x in &expected_cards { assert!(!handler.state.deck.contains(&x)); } } #[test] fn hand_update_when_given_player_hand() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; let expected_cards = vec![mp::Card { color: mp::Color::Color1, number: 7, }, mp::Card { color: mp::Color::Color3, number: 3, }]; handler.run_one_round(&ai, String::from("colors a b c d e f")); handler.run_one_round(&ai, String::from("player north name")); handler.run_one_round(&ai, String::from("player north hand a,7 c,3")); assert_eq!(expected_cards, handler.state.player_hand); } #[test] fn remove_from_deck_when_flag_status() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; let expected_cards = vec![mp::Card { color: mp::Color::Color1, number: 7, }, mp::Card { color: mp::Color::Color3, number: 3, }]; handler.run_one_round(&ai, String::from("colors a b c d e f")); handler.run_one_round(&ai, String::from("player north name")); for x in &expected_cards { assert!(handler.state.deck.contains(&x)); } handler.run_one_round(&ai, String::from("flag 1 cards north a,7 c,3")); assert_eq!(52, handler.state.deck.len()); for x in &expected_cards { assert!(!handler.state.deck.contains(&x)); } } #[test] fn default_vectors_after_certain_commands() { let mut handler: GameHandler = Default::default(); let ai = TestAi {}; handler.run_one_round(&ai, String::from("colors a b c d e f")); assert_eq!(54, handler.state.deck.len()); assert_eq!(6, handler.state.colors.len()); assert_eq!(9, handler.state.claim_status.len()); assert_eq!(9, handler.state.opponent_side.len()); assert_eq!(9, handler.state.player_side.len()); } }
use mobc_postgres::{tokio_postgres, PgConnectionManager}; use std::time::Duration; use std::env; use crate::{DbConnectionPool, DbConnection}; use super::errors::ErrorVariant; const DB_POOL_MAX_OPEN: u64 = 32; const DB_POOL_MAX_IDLE: u64 = 8; const DB_POOL_TIMEOUT_SECONDS: u64 = 15; pub fn create_pool() -> std::result::Result<DbConnectionPool, mobc::Error<tokio_postgres::Error>> { let db_host = match env::var("DB_HOST") { Ok(val) => val, Err(_) => panic!("Missing DB_HOST variable") }; let db_port: u16 = match env::var("DB_PORT") { Ok(val) => val.parse().unwrap(), Err(_) => panic!("Missing DB_PORT variable") }; let db_user = match env::var("DB_USER") { Ok(val) => val, Err(_) => panic!("Missing DB_USER variable") }; let db_password = match env::var("DB_PASSWORD") { Ok(val) => val, Err(_) => panic!("Missing DB_PASSWORD variable") }; let db_name = match env::var("DB_NAME") { Ok(val) => val, Err(_) => panic!("Missing DB_NAME variable") }; let mut config = tokio_postgres::Config::new(); config.user(&db_user[..]); config.password(&db_password[..]); config.host(&db_host[..]); config.port(db_port); config.dbname(&db_name[..]); let manager = PgConnectionManager::new( config, tokio_postgres::NoTls ); Ok( mobc::Pool::builder() .max_open(DB_POOL_MAX_OPEN) .max_idle(DB_POOL_MAX_IDLE) .get_timeout(Some(Duration::from_secs(DB_POOL_TIMEOUT_SECONDS))) .build(manager) ) } pub async fn get_db_conn(db_pool: &DbConnectionPool) -> Result<DbConnection, super::errors::ErrorVariant> { db_pool .get() .await .map_err(ErrorVariant::DbPoolError) }
// Copyright (c) 2018-2020 Jeron Aldaron Lau // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0>, the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, or the ZLib // license <LICENSE-ZLIB or https://www.zlib.net/zlib_license.html> at // your option. This file may not be copied, modified, or distributed // except according to those terms. //! Sample types use crate::{chan::Channel, config::Config, ops::Blend, private::Sealed}; use std::{fmt::Debug, marker::PhantomData}; /// Sample with one [channel](chan/trait.Channel.html). #[derive(Default, PartialEq, Copy, Clone, Debug)] pub struct Sample1<C: Channel, F: Config> { channels: [C; 1], _config: PhantomData<F>, } impl<C: Channel, F: Config> Sample1<C, F> { /// Create a one-channel Sample. pub fn new<H>(one: H) -> Self where C: From<H>, { let _config = PhantomData; let one = C::from(one); let channels = [one]; Self { channels, _config } } } impl<C: Channel, F: Config> Sample for Sample1<C, F> { type Chan = C; type Conf = F; fn channels(&self) -> &[Self::Chan] { &self.channels } fn channels_mut(&mut self) -> &mut [Self::Chan] { &mut self.channels } fn from_channels(ch: &[Self::Chan]) -> Self { let one = ch[0]; Self::new::<C>(one) } } /// Sample with two [channel](chan/trait.Channel.html)s. #[derive(Default, PartialEq, Copy, Clone, Debug)] pub struct Sample2<C: Channel, F: Config> { channels: [C; 2], _config: PhantomData<F>, } impl<C: Channel, F: Config> Sample2<C, F> { /// Create a two-channel Sample. pub fn new<H>(one: H, two: H) -> Self where C: From<H>, { let _config = PhantomData; let one = C::from(one); let two = C::from(two); let channels = [one, two]; Self { channels, _config } } } impl<C: Channel, F: Config> Sample for Sample2<C, F> { type Chan = C; type Conf = F; fn channels(&self) -> &[Self::Chan] { &self.channels } fn channels_mut(&mut self) -> &mut [Self::Chan] { &mut self.channels } fn from_channels(ch: &[Self::Chan]) -> Self { let one = ch[0]; let two = ch[1]; Self::new::<C>(one, two) } } /// Sample with six [channel](chan/trait.Channel.html)s. #[derive(Default, PartialEq, Copy, Clone, Debug)] pub struct Sample6<C: Channel, F: Config> { channels: [C; 6], _config: PhantomData<F>, } impl<C: Channel, F: Config> Sample6<C, F> { /// Create a six-channel Sample. pub fn new<H>(one: H, two: H, three: H, four: H, five: H, six: H) -> Self where C: From<H>, { let _config = PhantomData; let one = C::from(one); let two = C::from(two); let three = C::from(three); let four = C::from(four); let five = C::from(five); let six = C::from(six); let channels = [one, two, three, four, five, six]; Self { channels, _config } } } impl<C: Channel, F: Config> Sample for Sample6<C, F> { type Chan = C; type Conf = F; fn channels(&self) -> &[Self::Chan] { &self.channels } fn channels_mut(&mut self) -> &mut [Self::Chan] { &mut self.channels } fn from_channels(ch: &[Self::Chan]) -> Self { let one = ch[0]; let two = ch[1]; let three = ch[2]; let four = ch[3]; let five = ch[4]; let six = ch[5]; Self::new::<C>(one, two, three, four, five, six) } } /// Sample with six [channel](chan/trait.Channel.html)s. #[derive(Default, PartialEq, Copy, Clone, Debug)] pub struct Sample8<C: Channel, F: Config> { channels: [C; 8], _config: PhantomData<F>, } impl<C: Channel, F: Config> Sample8<C, F> { /// Create an eight-channel Sample. #[allow(clippy::too_many_arguments)] pub fn new<H>( one: H, two: H, three: H, four: H, five: H, six: H, seven: H, eight: H, ) -> Self where C: From<H>, { let _config = PhantomData; let one = C::from(one); let two = C::from(two); let three = C::from(three); let four = C::from(four); let five = C::from(five); let six = C::from(six); let seven = C::from(seven); let eight = C::from(eight); let channels = [one, two, three, four, five, six, seven, eight]; Self { channels, _config } } } impl<C: Channel, F: Config> Sample for Sample8<C, F> { type Chan = C; type Conf = F; fn channels(&self) -> &[Self::Chan] { &self.channels } fn channels_mut(&mut self) -> &mut [Self::Chan] { &mut self.channels } fn from_channels(ch: &[Self::Chan]) -> Self { let one = ch[0]; let two = ch[1]; let three = ch[2]; let four = ch[3]; let five = ch[4]; let six = ch[5]; let seven = ch[6]; let eight = ch[7]; Self::new::<C>(one, two, three, four, five, six, seven, eight) } } /// Sample [channel], and [configuration]. /// /// [channel]: ../chan/trait.Channel.html /// [configuration]: ../config/trait.Config.html pub trait Sample: Clone + Copy + Debug + Default + PartialEq + Sealed { /// Channel type type Chan: Channel; /// Number of channels type Conf: Config; /// Get the channels. fn channels(&self) -> &[Self::Chan]; /// Get the channels mutably. fn channels_mut(&mut self) -> &mut [Self::Chan]; /// Make a pixel from a slice of channels. fn from_channels(ch: &[Self::Chan]) -> Self; /// Synthesis of a sample with a slice of samples. fn blend_sample<O>(dst: &mut [Self], sample: &Self, op: O) where O: Blend, { for d in dst.iter_mut() { d.blend(sample, op); } } /// Synthesis of two slices of samples. fn blend_slice<O>(dst: &mut [Self], src: &[Self], op: O) where O: Blend, { for (d, s) in dst.iter_mut().zip(src) { d.blend(s, op); } } /// Synthesize two samples together. fn blend<O>(&mut self, src: &Self, _op: O) where O: Blend, { for (d, s) in self.channels_mut().iter_mut().zip(src.channels().iter()) { O::synthesize(d, s) } } /// Convert a sample to another format. #[inline(always)] fn convert<D>(self) -> D where D: Sample, D::Chan: From<Self::Chan> + From<f64>, { // Convert channels match (Self::Conf::CHANNEL_COUNT, D::Conf::CHANNEL_COUNT) { // 1:1 sampling (no resample) (a, b) if a == b => { let mut chans = [D::Chan::MID; 8]; for (d, s) in chans.iter_mut().zip(self.channels().iter()) { *d = (*s).into(); } D::from_channels(&chans[..self.channels().len()]) } // Downsampling (2, 1) => { let mut sum = 0.0; for chan in self.channels() { sum += chan.to_f64() * 0.5; } D::from_channels(&[D::Chan::from(sum)]) } (6, 1) => { let mut sum = 0.0; for chan in self.channels()[0..5].iter() { sum += chan.to_f64() * 0.2; } sum += self.channels()[5].to_f64(); // LFE D::from_channels(&[D::Chan::from(sum)]) } (8, 1) => { let mut sum = 0.0; for chan in self.channels()[0..7].iter() { sum += chan.to_f64() * (1.0 / 7.0); } sum += self.channels()[7].to_f64(); // LFE D::from_channels(&[D::Chan::from(sum)]) } (6, 2) => { let mut left = self.channels()[0].to_f64() * (1.0 / 3.0); let mut right = self.channels()[1].to_f64() * (1.0 / 3.0); left += self.channels()[2].to_f64() * (1.0 / 3.0); right += self.channels()[2].to_f64() * (1.0 / 3.0); left += self.channels()[3].to_f64() * (1.0 / 3.0); right += self.channels()[4].to_f64() * (1.0 / 3.0); left += self.channels()[5].to_f64(); // left LFE right += self.channels()[5].to_f64(); // right LFE D::from_channels(&[D::Chan::from(left), D::Chan::from(right)]) } (8, 2) => { let mut left = self.channels()[0].to_f64() * 0.25; let mut right = self.channels()[1].to_f64() * 0.25; left += self.channels()[2].to_f64() * 0.25; right += self.channels()[2].to_f64() * 0.25; left += self.channels()[3].to_f64() * 0.25; right += self.channels()[4].to_f64() * 0.25; left += self.channels()[5].to_f64(); // left LFE right += self.channels()[5].to_f64(); // right LFE left += self.channels()[6].to_f64() * 0.25; right += self.channels()[7].to_f64() * 0.25; D::from_channels(&[D::Chan::from(left), D::Chan::from(right)]) } (8, 6) => { let mut left = self.channels()[0].to_f64() * (2.0 / 3.0); let mut right = self.channels()[1].to_f64() * (2.0 / 3.0); let center = self.channels()[2].to_f64(); let mut back_left = self.channels()[3].to_f64() * (2.0 / 3.0); let mut back_right = self.channels()[4].to_f64() * (2.0 / 3.0); let lfe = self.channels()[5].to_f64(); left += self.channels()[6].to_f64() * (1.0 / 3.0); right += self.channels()[7].to_f64() * (1.0 / 3.0); back_left += self.channels()[6].to_f64() * (1.0 / 3.0); back_right += self.channels()[7].to_f64() * (1.0 / 3.0); D::from_channels(&[ D::Chan::from(left), D::Chan::from(right), D::Chan::from(center), D::Chan::from(back_left), D::Chan::from(back_right), D::Chan::from(lfe), ]) } // Upsampling (1, 2) => { let mono = self.channels()[0]; let channels = [D::Chan::from(mono), D::Chan::from(mono)]; D::from_channels(&channels) } (1, 6) => { let mono = self.channels()[0]; D::from_channels(&[ D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), ]) } (1, 8) => { let mono = self.channels()[0]; D::from_channels(&[ D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), D::Chan::from(mono), ]) } (2, 6) => { let left = self.channels()[0].to_f64(); let right = self.channels()[1].to_f64(); let center = left * 0.5 + right * 0.5; let lfe = D::Chan::MID.to_f64(); D::from_channels(&[ D::Chan::from(left), D::Chan::from(right), D::Chan::from(center), D::Chan::from(left), D::Chan::from(right), D::Chan::from(lfe), ]) } (2, 8) => { let left = self.channels()[0].to_f64(); let right = self.channels()[1].to_f64(); let center = left * 0.5 + right * 0.5; let lfe = D::Chan::MID.to_f64(); D::from_channels(&[ D::Chan::from(left), D::Chan::from(right), D::Chan::from(center), D::Chan::from(left), D::Chan::from(right), D::Chan::from(lfe), D::Chan::from(left), D::Chan::from(right), ]) } (5, 8) => { let left = self.channels()[0].to_f64(); let right = self.channels()[1].to_f64(); let center = self.channels()[2].to_f64(); let back_left = self.channels()[3].to_f64(); let back_right = self.channels()[4].to_f64(); let lfe = self.channels()[5].to_f64(); let side_left = (left + back_left) * 0.5; let side_right = (right + back_right) * 0.5; D::from_channels(&[ D::Chan::from(left), D::Chan::from(right), D::Chan::from(center), D::Chan::from(left), D::Chan::from(right), D::Chan::from(lfe), D::Chan::from(side_left), D::Chan::from(side_right), ]) } // Unreachable because of sealed traits (_, _) => unreachable!(), } } }
#![allow(dead_code)] use std::ops::Add; use std::ops::Sub; use std::ops::Div; struct Calculator<T> { x: T, y: T } impl<T> Calculator<T> where T: Add<Output = T> + Copy + Sub<Output = T> + Div<Output = T> { pub fn add(&self) -> T { self.x + self.y } pub fn sub(&self) -> T { self.x - self.y } pub fn div(&self) -> T { self.x / self.y } } pub fn find_largest_in_vec<T: PartialOrd + Copy>(l: Vec<T>) -> T { let mut largest_value:T = l[0]; for &item in l.iter() { if largest_value < item { largest_value = item; } } largest_value } pub fn generics_test() { let l = vec![10,14,1,99,76]; println!("Largest value in int list -> {:?}", find_largest_in_vec(l)); let l = vec!['a','z','m','r','l']; println!("Largest value in char list -> {:?}", find_largest_in_vec(l)); let l = vec!["this", "is", "that", "zee"]; println!("Largest value in char list -> {:?}", find_largest_in_vec(l)); let op = Calculator { x: 1, y: 2 }; println!("Generic struct impl add -> {}", op.add()); println!("Generic struct impl sub -> {}", op.sub()); }
#[doc = r"Register block"] #[repr(C)] pub struct RegisterBlock { #[doc = "0x00 - Data Register"] pub data: DATA, #[doc = "0x04 - Data enable register"] pub data_en: DATA_EN, #[doc = "0x08 - Direction control register"] pub dir: DIR, #[doc = "0x0c - Up and down control register"] pub pull_en: PULL_EN, #[doc = "0x10 - Multiplex select register"] pub af_sel: AF_SEL, #[doc = "0x14 - Multiplex select register 1"] pub sf_s1: SF_S1, #[doc = "0x18 - Multiplex select register 0"] pub af_s0: AF_S0, _reserved7: [u8; 4usize], #[doc = "0x20 - Interrupt trigger mode configuration register"] pub is: IS, #[doc = "0x24 - Interrupt edge trigger mode configuration register"] pub ibe: IBE, #[doc = "0x28 - Interrupt upper and lower edge trigger configuration register"] pub iev: IEV, #[doc = "0x2c - Interrupt enable configuration register"] pub ie: IE, #[doc = "0x30 - Bare interrupt status register"] pub ris: RIS, _reserved12: [u8; 4usize], #[doc = "0x38 - Interrupt clear control register"] pub ic: IC, _reserved13: [u8; 784usize], #[doc = "0x34c - Interrupt status register after masking"] pub mis: MIS, } #[doc = "Data Register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [data](data) module"] pub type DATA = crate::Reg<u32, _DATA>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DATA; #[doc = "`read()` method returns [data::R](data::R) reader structure"] impl crate::Readable for DATA {} #[doc = "`write(|w| ..)` method takes [data::W](data::W) writer structure"] impl crate::Writable for DATA {} #[doc = "Data Register"] pub mod data; #[doc = "Data enable register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [data_en](data_en) module"] pub type DATA_EN = crate::Reg<u32, _DATA_EN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DATA_EN; #[doc = "`read()` method returns [data_en::R](data_en::R) reader structure"] impl crate::Readable for DATA_EN {} #[doc = "`write(|w| ..)` method takes [data_en::W](data_en::W) writer structure"] impl crate::Writable for DATA_EN {} #[doc = "Data enable register"] pub mod data_en; #[doc = "Direction control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [dir](dir) module"] pub type DIR = crate::Reg<u32, _DIR>; #[allow(missing_docs)] #[doc(hidden)] pub struct _DIR; #[doc = "`read()` method returns [dir::R](dir::R) reader structure"] impl crate::Readable for DIR {} #[doc = "`write(|w| ..)` method takes [dir::W](dir::W) writer structure"] impl crate::Writable for DIR {} #[doc = "Direction control register"] pub mod dir; #[doc = "Up and down control register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [pull_en](pull_en) module"] pub type PULL_EN = crate::Reg<u32, _PULL_EN>; #[allow(missing_docs)] #[doc(hidden)] pub struct _PULL_EN; #[doc = "`read()` method returns [pull_en::R](pull_en::R) reader structure"] impl crate::Readable for PULL_EN {} #[doc = "`write(|w| ..)` method takes [pull_en::W](pull_en::W) writer structure"] impl crate::Writable for PULL_EN {} #[doc = "Up and down control register"] pub mod pull_en; #[doc = "Multiplex select register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [af_sel](af_sel) module"] pub type AF_SEL = crate::Reg<u32, _AF_SEL>; #[allow(missing_docs)] #[doc(hidden)] pub struct _AF_SEL; #[doc = "`read()` method returns [af_sel::R](af_sel::R) reader structure"] impl crate::Readable for AF_SEL {} #[doc = "`write(|w| ..)` method takes [af_sel::W](af_sel::W) writer structure"] impl crate::Writable for AF_SEL {} #[doc = "Multiplex select register"] pub mod af_sel; #[doc = "Multiplex select register 1\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [sf_s1](sf_s1) module"] pub type SF_S1 = crate::Reg<u32, _SF_S1>; #[allow(missing_docs)] #[doc(hidden)] pub struct _SF_S1; #[doc = "`read()` method returns [sf_s1::R](sf_s1::R) reader structure"] impl crate::Readable for SF_S1 {} #[doc = "`write(|w| ..)` method takes [sf_s1::W](sf_s1::W) writer structure"] impl crate::Writable for SF_S1 {} #[doc = "Multiplex select register 1"] pub mod sf_s1; #[doc = "Multiplex select register 0\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [af_s0](af_s0) module"] pub type AF_S0 = crate::Reg<u32, _AF_S0>; #[allow(missing_docs)] #[doc(hidden)] pub struct _AF_S0; #[doc = "`read()` method returns [af_s0::R](af_s0::R) reader structure"] impl crate::Readable for AF_S0 {} #[doc = "`write(|w| ..)` method takes [af_s0::W](af_s0::W) writer structure"] impl crate::Writable for AF_S0 {} #[doc = "Multiplex select register 0"] pub mod af_s0; #[doc = "Interrupt trigger mode configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [is](is) module"] pub type IS = crate::Reg<u32, _IS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IS; #[doc = "`read()` method returns [is::R](is::R) reader structure"] impl crate::Readable for IS {} #[doc = "`write(|w| ..)` method takes [is::W](is::W) writer structure"] impl crate::Writable for IS {} #[doc = "Interrupt trigger mode configuration register"] pub mod is; #[doc = "Interrupt edge trigger mode configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ibe](ibe) module"] pub type IBE = crate::Reg<u32, _IBE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IBE; #[doc = "`read()` method returns [ibe::R](ibe::R) reader structure"] impl crate::Readable for IBE {} #[doc = "`write(|w| ..)` method takes [ibe::W](ibe::W) writer structure"] impl crate::Writable for IBE {} #[doc = "Interrupt edge trigger mode configuration register"] pub mod ibe; #[doc = "Interrupt upper and lower edge trigger configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [iev](iev) module"] pub type IEV = crate::Reg<u32, _IEV>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IEV; #[doc = "`read()` method returns [iev::R](iev::R) reader structure"] impl crate::Readable for IEV {} #[doc = "`write(|w| ..)` method takes [iev::W](iev::W) writer structure"] impl crate::Writable for IEV {} #[doc = "Interrupt upper and lower edge trigger configuration register"] pub mod iev; #[doc = "Interrupt enable configuration register\n\nThis register you can [`read`](crate::generic::Reg::read), [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero), [`modify`](crate::generic::Reg::modify). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ie](ie) module"] pub type IE = crate::Reg<u32, _IE>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IE; #[doc = "`read()` method returns [ie::R](ie::R) reader structure"] impl crate::Readable for IE {} #[doc = "`write(|w| ..)` method takes [ie::W](ie::W) writer structure"] impl crate::Writable for IE {} #[doc = "Interrupt enable configuration register"] pub mod ie; #[doc = "Bare interrupt status register\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ris](ris) module"] pub type RIS = crate::Reg<u32, _RIS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _RIS; #[doc = "`read()` method returns [ris::R](ris::R) reader structure"] impl crate::Readable for RIS {} #[doc = "Bare interrupt status register"] pub mod ris; #[doc = "Interrupt status register after masking\n\nThis register you can [`read`](crate::generic::Reg::read). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [mis](mis) module"] pub type MIS = crate::Reg<u32, _MIS>; #[allow(missing_docs)] #[doc(hidden)] pub struct _MIS; #[doc = "`read()` method returns [mis::R](mis::R) reader structure"] impl crate::Readable for MIS {} #[doc = "Interrupt status register after masking"] pub mod mis; #[doc = "Interrupt clear control register\n\nThis register you can [`reset`](crate::generic::Reg::reset), [`write`](crate::generic::Reg::write), [`write_with_zero`](crate::generic::Reg::write_with_zero). See [API](https://docs.rs/svd2rust/#read--modify--write-api).\n\nFor information about available fields see [ic](ic) module"] pub type IC = crate::Reg<u32, _IC>; #[allow(missing_docs)] #[doc(hidden)] pub struct _IC; #[doc = "`write(|w| ..)` method takes [ic::W](ic::W) writer structure"] impl crate::Writable for IC {} #[doc = "Interrupt clear control register"] pub mod ic;
//! Definition of `Handler`. use { crate::{ error::Error, future::TryFuture, util::Chain, // }, std::{rc::Rc, sync::Arc}, }; /// A trait representing the handler associated with the specified endpoint. pub trait Handler { type Output; type Error: Into<Error>; type Handle: TryFuture<Ok = Self::Output, Error = Self::Error>; /// Creates an instance of `Handle` to handle an incoming request. fn handle(&self) -> Self::Handle; } impl<H> Handler for Rc<H> where H: Handler, { type Output = H::Output; type Error = H::Error; type Handle = H::Handle; #[inline] fn handle(&self) -> Self::Handle { (**self).handle() } } impl<H> Handler for Arc<H> where H: Handler, { type Output = H::Output; type Error = H::Error; type Handle = H::Handle; #[inline] fn handle(&self) -> Self::Handle { (**self).handle() } } pub fn handler<T>( handle_fn: impl Fn() -> T, ) -> impl Handler< Output = T::Ok, // Error = T::Error, Handle = T, > where T: TryFuture, { #[allow(missing_debug_implementations)] struct HandlerFn<F> { handle_fn: F, } impl<F, T> Handler for HandlerFn<F> where F: Fn() -> T, T: TryFuture, { type Output = T::Ok; type Error = T::Error; type Handle = T; #[inline] fn handle(&self) -> Self::Handle { (self.handle_fn)() } } HandlerFn { handle_fn } } /// A trait representing a type for modifying the instance of `Handler`. pub trait ModifyHandler<H: Handler> { type Output; type Error: Into<Error>; type Handler: Handler<Output = Self::Output, Error = Self::Error>; fn modify(&self, input: H) -> Self::Handler; } impl<'a, M, H> ModifyHandler<H> for &'a M where M: ModifyHandler<H>, H: Handler, { type Output = M::Output; type Error = M::Error; type Handler = M::Handler; #[inline] fn modify(&self, input: H) -> Self::Handler { (**self).modify(input) } } impl<M, H> ModifyHandler<H> for std::rc::Rc<M> where M: ModifyHandler<H>, H: Handler, { type Output = M::Output; type Error = M::Error; type Handler = M::Handler; #[inline] fn modify(&self, input: H) -> Self::Handler { (**self).modify(input) } } impl<M, H> ModifyHandler<H> for std::sync::Arc<M> where M: ModifyHandler<H>, H: Handler, { type Output = M::Output; type Error = M::Error; type Handler = M::Handler; #[inline] fn modify(&self, input: H) -> Self::Handler { (**self).modify(input) } } impl<H> ModifyHandler<H> for () where H: Handler, { type Output = H::Output; type Error = H::Error; type Handler = H; #[inline] fn modify(&self, input: H) -> Self::Handler { input } } impl<I, O, H> ModifyHandler<H> for Chain<I, O> where H: Handler, I: ModifyHandler<H>, O: ModifyHandler<I::Handler>, { type Output = O::Output; type Error = O::Error; type Handler = O::Handler; #[inline] fn modify(&self, input: H) -> Self::Handler { self.right.modify(self.left.modify(input)) } }
use serde::{Deserialize, Serialize}; use crate::protocol::{LogStreamSource, ProcessInfo, ProcessSpec, ProcessStatus}; /// A response to list information and metrics about managed processes. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct ListResponse { pub name: String, pub pid: Option<usize>, pub status: ProcessStatus, pub cpu_usage: u32, pub mem_usage: u32, } /// A response to list information and metrics about managed processes. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct StartResponse { #[serde(flatten)] pub spec: ProcessSpec, } /// A response to stop managed processes. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct StopResponse { pub name: String, pub error: Option<String>, } /// A response to restart managed processes. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RestartResponse { pub name: String, pub error: Option<String>, } /// A response to get information about the current state of a managed process. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct InfoResponse { #[serde(flatten)] pub info: ProcessInfo, } /// A response to stop managing a process. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DeleteResponse { pub name: String, pub error: Option<String>, } /// A response to dump the current process specifications. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct DumpResponse { #[serde(flatten)] pub spec: ProcessSpec, } /// A response to restore a previously dumped process. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct RestoreResponse { pub name: String, pub error: Option<String>, } /// A response to get version information about the daemon. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct VersionResponse { pub version: String, } /// A log entry. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct LogEntry { /// Name of the originating process. pub name: String, /// Source stream of this log entry (stdout or stderr). pub source: LogStreamSource, /// The actual log message. pub msg: String, } /// A response for log entries (from the daemon to a client). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "type", content = "data", rename_all = "kebab-case")] pub enum LogsResponse { Subscribed, Entry(LogEntry), Unsubscribed, } /// A response to prune unused log files. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct PruneResponse { /// List of the names of all the successfully pruned files. pub pruned_files: Vec<String>, } /// A response (from the daemon to a client). #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "type", content = "data", rename_all = "kebab-case")] pub enum Response { List(Vec<ListResponse>), Start(StartResponse), Stop(Vec<StopResponse>), Restart(Vec<RestartResponse>), Info(InfoResponse), Delete(Vec<DeleteResponse>), Dump(Vec<DumpResponse>), Restore(Vec<RestoreResponse>), Version(VersionResponse), Logs(LogsResponse), Prune(PruneResponse), Error(String), }
// RGB Rust Library // Written in 2019 by // Dr. Maxim Orlovsky <dr.orlovsky@gmail.com> // basing on ideas from the original RGB rust library by // Alekos Filini <alekos.filini@gmail.com> // // To the extent possible under law, the author(s) have dedicated all // copyright and related and neighboring rights to this software to // the public domain worldwide. This software is distributed without // any warranty. // // You should have received a copy of the MIT License // along with this software. // If not, see <https://opensource.org/licenses/MIT>. use std::io::Write; use bitcoin::blockdata::{opcodes::all::*, script::Builder, script::Script}; use bitcoin::{OutPoint, Transaction}; use bitcoin_hashes::{sha256d, Hash}; use secp256k1::{PublicKey, Secp256k1}; use crate::*; use bitcoin::util::contracthash::tweak_key; use bitcoin::util::psbt::serialize::Serialize; pub enum TxQuery { TxId(sha256d::Hash), SpendingTxId(sha256d::Hash), SpendingVout(OutPoint), } pub type TxProvider<B> = fn(tx_type: TxQuery) -> Result<Transaction, RgbError<'static, B>>; /// Trait describing and implementing shared functionality for the on-chain parts of the /// RGB contracts and prootfs pub trait OnChain<B: ContractBody> { fn get_identity_hash(&self) -> IdentityHash; fn get_contract(&self) -> Result<&Contract<B>, RgbError<B>>; fn get_original_pk(&self) -> Option<PublicKey>; /// Generates Bitcoin script corresponding to the given RGB proof (taking into account /// commitment scheme of the source RGB contract) fn get_script(&self) -> Result<Script, RgbError<B>> { let commitment_scheme = self.get_contract()?.header.commitment_scheme.clone(); let builder = match commitment_scheme { CommitmentScheme::OpReturn => Builder::new() // Simple OP_RETURN with data corresponding to the hash of the current proof .push_opcode(OP_RETURN) .push_slice(&self.get_identity_hash().into_inner()), CommitmentScheme::PayToContract => Builder::new() // Pay to contract: standard P2PKH utilizing tweaked public key .push_opcode(OP_DUP) .push_opcode(OP_HASH160) // Pushing the hash of the tweaked public key .push_slice( &sha256d::Hash::from_engine({ let mut engine = sha256d::Hash::engine(); engine.write_all( // Tweaking public key &tweak_key( &Secp256k1::new(), bitcoin::PublicKey { compressed: true, key: self.get_original_pk().ok_or_else(|| { RgbError::NoOriginalPubKey(self.get_identity_hash()) })?, }, &[ // Adding "RGB" string according to // <https://github.com/rgb-org/spec/issues/61> "RGB".as_bytes(), // Adding contract hash &self.get_identity_hash()[..], ] .concat()[..], ) .serialize(), )?; engine })[..], ) .push_opcode(OP_EQUALVERIFY) .push_opcode(OP_CHECKSIG), _ => return Err(RgbError::UnsupportedCommitmentScheme(commitment_scheme)), }; Ok(builder.into_script()) } } /// Trait for verifiable entries pub trait Verify<B: ContractBody> { /// Function performing verification of the integrity for the RGB entity (contract or particular /// proof) for both on-chain and off-chain parts; including internal consistency, integrity, /// proper formation of commitment transactions etc. This is default implementation, /// it checks nothing /// /// # Arguments: /// * `tx_provider` - a specially-formed callback function provided by the callee (wallet app /// or bifrost server) that returns transaction for a given case (specified by `TxQuery`-typed /// argument given to the callback). Used during the verification process to check on-chain /// part of the proofs and contracts. Since rgblib has no direct access to a bitcoin node /// (it's rather a task for particular wallet or Bifrost implementation) it relies on this /// callback during the verification process. fn verify(&self, _: TxProvider<B>) -> Result<(), RgbError<B>> { Ok(()) } }
//! # 316. 去除重复字母 //! https://leetcode-cn.com/problems/remove-duplicate-letters/ /// 给你一个字符串 s ,请你去除字符串中重复的字母,使得每个字母只出现一次。需保证 返回结果的字典序最小(要求不能打乱其他字符的相对位置)。 ///! # 解题思路 ///! 计算每个字符出现的次数,利用递增栈 pub struct Solution; impl Solution { pub fn remove_duplicate_letters(s: String) -> String { let mut letters = [(0, false); 26]; for c in s.as_bytes() { letters[(*c - b'a') as usize].0 += 1; } let mut result: Vec<u8> = Vec::new(); for c in s.as_bytes() { let idx = (*c - b'a') as usize; if letters[idx].0 > 0 { //already exist if letters[idx].1 { letters[idx].0 -= 1; continue; } while !result.is_empty() { let last = result.last().unwrap(); // 确保当前字符是否小于栈内字符并去出栈的字符后面还会有出现 if last < c || letters[(last - b'a') as usize].0 < 1 { break; } // 满足条件,最后大的字符出栈 letters[(last - b'a') as usize].1 = false; result.pop(); } result.push(*c); letters[idx].0 -= 1; letters[idx].1 = true; } } String::from_utf8(result).unwrap() } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!( super::Solution::remove_duplicate_letters("bcabc".into()), String::from("abc") ); assert_eq!( super::Solution::remove_duplicate_letters("cbacdcbc".into()), String::from("acdb") ); assert_eq!( super::Solution::remove_duplicate_letters("".into()), String::from("") ); } }
use crate::compiler::Compiler; use crate::ast; use crate::parser; use std::fs; use std::path::PathBuf; #[derive(thiserror::Error)] #[derive(Debug)] pub enum Error { #[error("module {0}/{1} not found")] NotFound(String, String), #[error("I/O error")] Io(#[from] std::io::Error), #[error("parsing module")] Nom(#[from] nom::Err<nom::error::Error<String>>), #[error("compiling")] Compile(#[from] Box<crate::compiler::CompileError>), } pub fn load(compiler: &mut Compiler, module: &ast::ModuleId) -> Result<(), Error> { if compiler.have_module(module) { return Ok(()); } let mut parser_ctxt = parser::Context { strings: &mut compiler.strings, world: &mut compiler.world, }; let ast = read_ast(&mut parser_ctxt, module)?; let decls = ast.decls.clone(); compiler.add_module(module, ast); for decl in decls { match decl { ast::Declaration::Require(ast::Require { module }) => { // fixme recursion load(compiler, &module)?; } ast::Declaration::Import(ast::Import { module: from_module, item }) => { crate::compiler::import(compiler, module, &from_module, &item).map_err(Box::new)?; } ast::Declaration::ImportAll(ast::ImportAll { module: from_module }) => { crate::compiler::import_all(compiler, module, &from_module).map_err(Box::new)?; } _ => { /* pass */ } } } Ok(()) } fn read_ast(ctxt: &mut parser::Context, module: &ast::ModuleId) -> Result<ast::Module, Error> { let group = ctxt.strings.resolve(module.group.symbol).expect(""); let module = ctxt.strings.resolve(module.module.symbol).expect(""); let path = format!("./lib/{}/{}.piddle", group, module); let path = PathBuf::from(path); if !fs::metadata(&path).is_ok() { return Err(Error::NotFound(group.to_string(), module.to_string())); } let text = fs::read_to_string(&path)?; let (_, module) = parser::module(ctxt, &text) .map_err(|e| e.map(|e| nom::error::Error::new(e.input.to_string(), e.code)))?; Ok(module) }
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. */ //! This crate wraps raw `u64` syscall arguments in stronger Rust types. This //! has a number of useful side effects: //! 1. Syscalls and their arguments can be easily displayed for debugging //! purposes. //! 2. When intercepting syscalls, the Rust type can be accessed more safely. //! 3. When injecting syscalls, it is easier and clearer to set the arguments //! using the `with_*` builder methods. #![deny(missing_docs)] #![deny(rustdoc::broken_intra_doc_links)] #[macro_use] mod macros; mod args; mod display; mod memory; mod raw; mod syscalls; // Re-export the only things that might be needed from the syscalls crate pub use ::syscalls::Errno; pub use ::syscalls::SyscallArgs; pub use ::syscalls::Sysno; pub use crate::args::*; pub use crate::display::*; pub use crate::memory::*; pub use crate::raw::*; pub use crate::syscalls::*;
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::channel_transaction_info::ChannelTransactionInfo; use crate::proof::ChannelTransactionAccumulatorProof; use libra_types::proof::SparseMerkleProof; /// The complete proof used to authenticate the state of an account. This structure consists of the /// `AccumulatorProof` from `LedgerInfo` to `TransactionInfo`, the `TransactionInfo` object and the /// `SparseMerkleProof` from state root to the account. #[derive(Clone, Debug, Eq, PartialEq)] pub struct AccountStateProof { /// The accumulator proof from ledger info root to leaf that authenticates the hash of the /// `TransactionInfo` object. ledger_info_to_transaction_info_proof: ChannelTransactionAccumulatorProof, /// The `TransactionInfo` object at the leaf of the accumulator. transaction_info: ChannelTransactionInfo, /// The sparse merkle proof from state root to the account state. transaction_info_to_account_proof: SparseMerkleProof, } impl AccountStateProof { /// Constructs a new `AccountStateProof` using given `ledger_info_to_transaction_info_proof`, /// `transaction_info` and `transaction_info_to_account_proof`. pub fn new( ledger_info_to_transaction_info_proof: ChannelTransactionAccumulatorProof, transaction_info: ChannelTransactionInfo, transaction_info_to_account_proof: SparseMerkleProof, ) -> Self { AccountStateProof { ledger_info_to_transaction_info_proof, transaction_info, transaction_info_to_account_proof, } } /// Returns the `ledger_info_to_transaction_info_proof` object in this proof. pub fn ledger_info_to_transaction_info_proof(&self) -> &ChannelTransactionAccumulatorProof { &self.ledger_info_to_transaction_info_proof } /// Returns the `transaction_info` object in this proof. pub fn transaction_info(&self) -> &ChannelTransactionInfo { &self.transaction_info } /// Returns the `transaction_info_to_account_proof` object in this proof. pub fn transaction_info_to_account_proof(&self) -> &SparseMerkleProof { &self.transaction_info_to_account_proof } }
//! Names for punctuation characters. /// Returns the name of the given character, or None if it is unknown. pub fn get_opt(c: char) -> Option<&'static str> { let ret = match c { '_' => "Underscore", '-' => "Minus", ',' => "Comma", ';' => "Semicolon", ':' => "Colon", '!' => "Bang", '?' => "Question", '.' => "Dot", '(' => "LRound", ')' => "RRound", '[' => "LSquare", ']' => "RSquare", '{' => "LCurly", '}' => "RCurly", '*' => "Star", '/' => "Slash", '&' => "And", '#' => "Hash", '%' => "Percent", '^' => "Carat", '+' => "Plus", '<' => "Lt", '=' => "Eq", '>' => "Gt", '|' => "Bar", '~' => "Tilde", '`' => "Tick", _ => return None, }; Some(ret) } /// Returns the name of the given character, or panics if it is unknown. pub fn get(c: char) -> &'static str { match get_opt(c) { Some(s) => s, None => panic!("don't know the name for {c}"), } }
pub fn pretty_print(request: Vec<u8>) -> String { let vec: Vec<u8> = request; format!( r#" ######################################################## {} ######################################################## "#, String::from_utf8_lossy(&vec) ) }
use rodio::Sink; use std::env; mod note; use note::model::{Note, Playable}; use std::{fs}; /// /// The main function, called /// when we execute: /// /// `cargo run [song file]` /// /// ... in the command line. /// fn main() { // We get the arguments passed to the cargo run command... let args : Vec<String> = env::args().collect(); /* * Here we're trying to match some parameter ending with ".txt" * * If we find any, we get the (probably, haven't checked really) * first match. Else we inform that no .txt song was given and * end the program. */ let filename = match args.iter().find(|&txt_file| txt_file.ends_with(".txt")) { Some(name) => name, _ => { println!("\r\nWell, no file was given. Try to run it like this:\r\n\r\ncargo run [NAME OF THE FILE WITH THE SONG].txt\r\n\r\nAs you've seen, the file must end with the \"txt\" extension.\r\n"); return; } }; // Playing the file identified // by filename play_file(filename); // The song is over. Good bye! println!("fin"); } /// Plays the file identified by the given filename /// or file path or exits if no file was found or some /// inconsistency was found while executing the song /// in the file. /// /// ### Arguments /// /// * `filename : &str` - The name or full path of the song file /// /// ### Example /// /// `play_file("my_super_duper_awesome_song.txt");` /// fn play_file(filename : &str) { /* * We try to get the system default output * sound... We're only proceeding with the * execution if we have some device to play! */ let device = match rodio::default_output_device() { Some(d) => d, None => { println!("No default sound device was found. Wonder why... :_-("); return; } }; // Trying to read the file by the given file name. let content_string : String = match fs::read_to_string(filename) { Ok(val) => val, Err(_err) => { println!("\r\n\r\nHum... Couldn't read the given song file. What the hell? Have you typed it correctly?\r\n\r\n"); return; } }; /* * Let's split the music file by the new line * character (so we get a iterator over the * lines in the file) */ let mut iterator = content_string.split("\n"); loop { /* * Get the next line found in the music file. * If it is the first iteration in the loop, gets the * first line (and so on). */ let line = match iterator.next() { Some(line) => { if line.starts_with('#') { continue; } line }, None => break }; // The index of the comma character on the line (if any) let comma_index = match line.find(',') { Some(i) => i, None => { println!("Hum... An invalid line was found! We'll ignore it for now ;-)"); continue; } }; //Parsing the frequency let frequency = match line[0 .. comma_index].parse::<u32>() { Ok(value) => value, Err(_err) => { println!("Opsy! The frequency must be a positive integer... What the hell was that?"); continue; } }; //Parsing the duration let duration = match line[comma_index + 1 ..].parse::<u64>() { Ok(value) => value, Err(_err) => { println!("Oh my sweet baby... Ok. Got an invalid duration somewhere in the file. It must be an positive integer and it was not! >:-("); continue; } }; // Creating the musical note... let note = &mut Note { sink: Sink::new(&device), sound: frequency, duration: duration }; // ... and playing it! :-D note.play(); } }
use crate::grammar::ast::StringLit; use crate::grammar::testing::TestingContext; use crate::grammar::tracing::input::OptionallyTraceable; fn do_test(s: &'static str, r: &'static str, o: &'static str) { let tcx = TestingContext::with(&[s]); let fr = tcx.get_fragment(0); let (rem, out) = StringLit::parse(fr).unwrap(); rem.get_trace().unwrap().print(); assert_eq!(out.inner, o); assert_eq!(rem.source(), r); } #[test] fn test_simple() { do_test(r#""Hello, World""#, r"", r"Hello, World") } #[test] fn test_null_escape() { do_test(r#""Null\0 character""#, r"", "Null\0 character") } #[test] fn test_unterminated() { TestingContext::with(&[r#""simple"#, r#""escaped ending \""#]).test_all_fail(StringLit::parse) }
use crc32fast::Hasher; /* Outputed file data structure bytes 0..31 = bitmask of used bytes in the original file bytes 32..36 = crc32 hash of the original file bytes 37..end = crc32 hashed data in 4 byte segments */ pub fn compress(block_size: usize, input_vector: &mut Vec<u8>) -> Vec<u32> { //pad end with spaces to be divisible by block_size if input_vector.len() % block_size != 0 { for _ in 0..block_size - (input_vector.len() % block_size) { input_vector.push(0); } } //declare vairables let mut to_ret: Vec<u32> = Vec::with_capacity(100 + (input_vector.len() / block_size)); let mut hasher; { let mut checksum: Hasher = Hasher::new(); checksum.update(input_vector); //prepend byte bitmask let char_bitmask = generate_char_bitmask(&input_vector); for i in char_bitmask { to_ret.push(i); } //prepend file checksum after byte mask, this is calculated after padding is added to_ret.push(checksum.finalize()); } for i in 0..(input_vector.len() / block_size) { //initalize hasher every loop because hasher.finish() does not clear it hasher = Hasher::new(); //write block to hash to hasher hasher.update( input_vector .get(block_size * i..block_size * i + block_size) .unwrap(), ); //write hash as a new entry in the vector to_ret.push(hasher.finalize()); } to_ret } pub fn generate_char_bitmask(input: &Vec<u8>) -> Vec<u32> { let mut tracker: [usize; 256] = [0; 256]; for i in input.iter() { tracker[*i as usize] += 1; } let mut ret_vec: Vec<u32> = vec![0; 8]; for i in 0..256 { if tracker[i] != 0 { ret_vec[i / 32] += 1 << i % 32; } } ret_vec }
use std::io::{self, Cursor, Read, Write}; use super::common::SyncBackend; use super::error::{MogError, MogResult}; use time::{self, Tm}; use url::Url; pub use self::iron::StorageHandler; pub use self::range::RangeMiddleware; pub mod iron; pub mod range; #[derive(Clone, Debug)] pub struct Storage { pub base_url: Url, backend: SyncBackend, } impl Storage { pub fn new(backend: SyncBackend, base_url: Url) -> Storage { Storage { base_url: base_url, backend: backend, } } pub fn url_for_key(&self, domain: &str, key: &str) -> Url { let mut key_url = self.base_url.clone(); let mut new_path = Vec::from(key_url.path().unwrap()); new_path.extend([ "d", domain, "k" ].iter().map(|s| s.to_string())); new_path.extend(key.split("/").map(|s| s.to_string())); new_path = new_path.into_iter().skip_while(|p| p == "").collect(); *key_url.path_mut().unwrap() = new_path; key_url } pub fn file_metadata(&self, domain: &str, key: &str) -> MogResult<FileMetadata> { let mut rv = FileMetadata { size: 0, mtime: time::now_utc(), }; self.backend.with_file(domain, key, |file_info| { match (file_info.size, file_info.mtime) { (Some(size), Some(mtime)) => { rv.size = size; rv.mtime = mtime; Ok(()) }, _ => { Err(MogError::NoContent(key.to_string())) } } }).and(Ok(rv)) } pub fn store_content<R: Read>(&self, domain: &str, key: &str, reader: &mut R) -> MogResult<()> { // We don't need the lock to do this part... let mut content = vec![]; try!(io::copy(reader, &mut content)); self.backend.with_file_mut(domain, key, move|file_info| { file_info.size = Some(content.len()); file_info.content = Some(content); file_info.mtime = Some(time::now_utc()); Ok(()) }) } pub fn get_content<W: Write>(&self, domain: &str, key: &str, writer: &mut W) -> MogResult<()> { self.backend.with_file(domain, key, move|file_info| { match file_info.content { Some(ref reader) => { try!(io::copy(&mut Cursor::new(reader.as_ref()), writer)); Ok(()) }, None => { Err(MogError::NoContent(key.to_string())) } } }) } } #[derive(Debug)] pub struct FileMetadata { pub size: usize, pub mtime: Tm, } #[cfg(test)] mod tests { use std::io::Cursor; use super::super::error::MogError; use super::super::test_support::*; #[test] fn url_for_key() { let storage = storage_fixture(); assert_eq!( format!("http://{}/{}/d/{}/k/{}", TEST_HOST, TEST_BASE_PATH, TEST_DOMAIN, TEST_KEY_1), storage.url_for_key(TEST_DOMAIN, TEST_KEY_1).serialize()); } #[test] fn get_content() { let storage = storage_fixture(); let mut content = vec![]; storage.get_content(TEST_DOMAIN, TEST_KEY_1, &mut content).unwrap_or_else(|e| { panic!("Error retrieving content from {:?}: {}", TEST_KEY_1, e); }); let content_ref: &[u8] = &content; assert_eq!(TEST_CONTENT_1, content_ref); } #[test] fn get_content_unknown_key() { let storage = storage_fixture(); let mut content = vec![]; assert!( matches!(storage.get_content(TEST_DOMAIN, "test/key/3", &mut content).unwrap_err(), MogError::UnknownKey(ref k) if k == "test/key/3")); assert!(content.is_empty()); } #[test] fn get_content_no_content() { let storage = storage_fixture(); let mut content = vec![]; assert!(matches!(storage.get_content(TEST_DOMAIN, TEST_KEY_2, &mut content).unwrap_err(), MogError::NoContent(ref k) if k == TEST_KEY_2)); assert!(content.is_empty()); } #[test] fn store_replace_content() { let storage = storage_fixture(); let new_content = Vec::from("This is new test content"); storage.store_content(TEST_DOMAIN, TEST_KEY_1, &mut Cursor::new(new_content.clone())).unwrap_or_else(|e| { panic!("Error storing content to {:?}: {}", TEST_KEY_1, e); }); storage.backend.with_file(TEST_DOMAIN, TEST_KEY_1, move|file| { assert_eq!(&new_content, file.content.as_ref().unwrap()); Ok(()) }).unwrap(); } #[test] fn store_new_content() { let storage = storage_fixture(); let new_content = Vec::from("This is new test content"); storage.store_content(TEST_DOMAIN, TEST_KEY_2, &mut Cursor::new(new_content.clone())).unwrap_or_else(|e| { panic!("Error storing content to {:?}: {}", TEST_KEY_2, e); }); storage.backend.with_file(TEST_DOMAIN, TEST_KEY_2, move|file| { assert_eq!(&new_content, file.content.as_ref().unwrap()); Ok(()) }).unwrap(); } #[test] fn store_content_to_unknown_key() { let storage = storage_fixture(); let new_content: &'static [u8] = b"This is new test content"; assert!(matches!(storage.store_content(TEST_DOMAIN, "test/key/3", &mut Cursor::new(new_content)).unwrap_err(), MogError::UnknownKey(ref k) if k == "test/key/3")); } } #[cfg(test)] pub mod test_support { use super::*; use super::super::common::test_support::sync_backend_fixture; use url::Url; pub static TEST_HOST: &'static str = "test.host"; pub static TEST_BASE_PATH: &'static str = "base_path"; pub fn storage_fixture() -> Storage { let base_url = Url::parse(&format!("http://{}/{}", TEST_HOST, TEST_BASE_PATH)).unwrap(); Storage::new(sync_backend_fixture(), base_url) } }
/// Module that adds fasterxml annotations to generated classes. use backend::*; use codeviz::java::*; use super::models as m; use super::processor::*; pub struct Module { override_: ClassType, creator: ClassType, value: ClassType, property: ClassType, sub_types: ClassType, type_info: ClassType, serialize: ClassType, deserialize: ClassType, deserializer: ClassType, serializer: ClassType, generator: ClassType, serializer_provider: ClassType, parser: ClassType, deserialization_context: ClassType, token: ClassType, string: ClassType, io_exception: ClassType, } impl Module { pub fn new() -> Module { Module { override_: Type::class("java.lang", "Override"), creator: Type::class("com.fasterxml.jackson.annotation", "JsonCreator"), value: Type::class("com.fasterxml.jackson.annotation", "JsonValue"), property: Type::class("com.fasterxml.jackson.annotation", "JsonProperty"), sub_types: Type::class("com.fasterxml.jackson.annotation", "JsonSubTypes"), type_info: Type::class("com.fasterxml.jackson.annotation", "JsonTypeInfo"), serialize: Type::class("com.fasterxml.jackson.databind.annotation", "JsonSerialize"), deserialize: Type::class("com.fasterxml.jackson.databind.annotation", "JsonDeserialize"), serializer: Type::class("com.fasterxml.jackson.databind", "JsonSerializer"), deserializer: Type::class("com.fasterxml.jackson.databind", "JsonDeserializer"), generator: Type::class("com.fasterxml.jackson.core", "JsonGenerator"), serializer_provider: Type::class("com.fasterxml.jackson.databind", "SerializerProvider"), parser: Type::class("com.fasterxml.jackson.core", "JsonParser"), deserialization_context: Type::class("com.fasterxml.jackson.databind", "DeserializationContext"), token: Type::class("com.fasterxml.jackson.core", "JsonToken"), string: Type::class("java.lang", "String"), io_exception: Type::class("java.io", "IOException"), } } /// Custom serialize implementation for tuples. fn tuple_serializer(&self, fields: &Vec<m::JavaField>, class_type: &ClassType) -> Result<ClassSpec> { let mut serializer = ClassSpec::new(mods![Modifier::Public, Modifier::Static], "Serializer"); serializer.extends(self.serializer.with_arguments(vec![&class_type])); let value = ArgumentSpec::new(mods![Modifier::Final], &class_type, "value"); let jgen = ArgumentSpec::new(mods![Modifier::Final], &self.generator, "jgen"); let provider = ArgumentSpec::new(mods![Modifier::Final], &self.serializer_provider, "provider"); let mut serialize = MethodSpec::new(mods![Modifier::Public], "serialize"); serialize.throws(&self.io_exception); serialize.push_argument(&value); serialize.push_argument(&jgen); serialize.push_argument(&provider); serialize.push_annotation(&self.override_); let mut body = Elements::new(); body.push(stmt![&jgen, ".writeStartArray();"]); for field in fields { let field_stmt = stmt![&value, ".", &field.spec]; let write = match field.ty { Type::Primitive(ref primitive) => { match *primitive { SHORT | LONG | INTEGER | FLOAT | DOUBLE => { stmt!["writeNumber(", field_stmt, ")"] } _ => return Err("cannot serialize type".into()), } } Type::Class(ref class) => { if *class == self.string { stmt!["writeString(", field_stmt, ")"] } else { stmt!["writeObject(", field_stmt, ")"] } } _ => stmt!["writeObject(", field_stmt, ")"], }; body.push(stmt![&jgen, ".", write, ";"]); } body.push(stmt![&jgen, ".writeEndArray();"]); serialize.push(body); serializer.push(serialize); Ok(serializer) } fn deserialize_method_for_type(&self, ty: &Type, parser: &ArgumentSpec) -> Result<(Option<(Statement, &str)>, Statement)> { match *ty { Type::Primitive(ref primitive) => { let test = stmt!["!", parser, ".nextToken().isNumeric()"]; match *primitive { SHORT => { Ok((Some((test, "VALUE_NUMBER_INT")), stmt![parser, ".getShortValue()"])) } LONG => { Ok((Some((test, "VALUE_NUMBER_INT")), stmt![parser, ".getLongValue()"])) } INTEGER => { Ok((Some((test, "VALUE_NUMBER_INT")), stmt![parser, ".getIntegerValue()"])) } FLOAT => { Ok((Some((test, "VALUE_NUMBER_FLOAT")), stmt![parser, ".getFloatValue()"])) } DOUBLE => { Ok((Some((test, "VALUE_NUMBER_FLOAT")), stmt![parser, ".getDoubleValue()"])) } _ => return Err("cannot deserialize type".into()), } } Type::Class(ref class) => { if *class == self.string { let test = stmt![&parser, ".nextToken() != ", &self.token, ".VALUE_STRING"]; let token = Some((test, "VALUE_STRING")); return Ok((token, stmt![parser, ".getText()"])); } if class.arguments.is_empty() { return Ok((None, stmt![parser, ".readValueAs(", class, ".class)"])); } // TODO: support generics return Err("cannot deserialize type".into()); } Type::Local(ref local) => { return Ok((None, stmt![parser, ".readValueAs(", &local.name, ")"])); } } } fn wrong_token_exception(&self, ctxt: &ArgumentSpec, parser: &ArgumentSpec, token: &str) -> Statement { let mut arguments = Statement::new(); arguments.push(parser); arguments.push(stmt![&self.token, ".", token]); arguments.push("null"); stmt!["throw ", ctxt, ".wrongTokenException(", arguments.join(", "), ");"] } /// Custom deserialize implementation for tuples. fn tuple_deserializer(&self, fields: &Vec<m::JavaField>, class_type: &ClassType) -> Result<ClassSpec> { let mut deserializer = ClassSpec::new(mods![Modifier::Public, Modifier::Static], "Deserializer"); deserializer.extends(self.deserializer.with_arguments(vec![&class_type])); let parser = ArgumentSpec::new(mods![Modifier::Final], &self.parser, "parser"); let ctxt = ArgumentSpec::new(mods![Modifier::Final], &self.deserialization_context, "ctxt"); let mut deserialize = MethodSpec::new(mods![Modifier::Public], "deserialize"); deserialize.throws(&self.io_exception); deserialize.push_argument(&parser); deserialize.push_argument(&ctxt); deserialize.push_annotation(&self.override_); deserialize.returns(&class_type); let current_token = stmt![&parser, ".getCurrentToken()"]; let mut start_array = Elements::new(); start_array.push(stmt!["if (", &current_token, " != ", &self.token, ".START_ARRAY) {"]); start_array.push_nested(self.wrong_token_exception(&ctxt, &parser, "START_ARRAY")); start_array.push("}"); deserialize.push(start_array); let mut arguments = Statement::new(); for field in fields { let (token, reader) = self.deserialize_method_for_type(&field.ty, &parser)?; if let Some((test, expected)) = token { let mut field_check = Elements::new(); field_check.push(stmt!["if (", &test, ") {"]); field_check.push_nested(self.wrong_token_exception(&ctxt, &parser, expected)); field_check.push("}"); deserialize.push(field_check); } let variable = stmt!["v_", &field.spec.name]; let assign = stmt!["final ", &field.spec.ty, " ", &variable, " = ", reader, ";"]; deserialize.push(assign); arguments.push(variable); } let next_token = stmt![&parser, ".nextToken()"]; let mut end_array = Elements::new(); end_array.push(stmt!["if (", &next_token, " != ", &self.token, ".END_ARRAY) {"]); end_array.push_nested(self.wrong_token_exception(&ctxt, &parser, "END_ARRAY")); end_array.push("}"); deserialize.push(end_array); deserialize.push(stmt!["return new ", &class_type, "(", arguments.join(", "), ");"]); deserializer.push(deserialize); Ok(deserializer) } } impl Listeners for Module { fn class_added(&self, event: &mut ClassAdded) -> Result<()> { if event.spec.constructors.len() != 1 { return Err("Expected exactly one constructor".into()); } let constructor = &mut event.spec.constructors[0]; if constructor.arguments.len() != event.fields.len() { return Err(format!("{:?}: the number of constructor arguments ({}) did not match \ the number of fields ({})", event.class_type, constructor.arguments.len(), event.fields.len()) .into()); } let creator_annotation = AnnotationSpec::new(&self.creator); constructor.push_annotation(&creator_annotation); let zipped = constructor.arguments.iter_mut().zip(event.fields.iter()); for (argument, field) in zipped { let mut property = AnnotationSpec::new(&self.property); property.push_argument(stmt![Variable::String(field.name.clone())]); argument.push_annotation(&property); } Ok(()) } fn tuple_added(&self, event: &mut TupleAdded) -> Result<()> { let serializer = self.tuple_serializer(&event.fields, &event.class_type)?; let serializer_type = Type::class(&event.class_type.package, &format!("{}.{}", event.class_type.name, serializer.name)); let mut serialize_annotation: AnnotationSpec = self.serialize.clone().into(); serialize_annotation.push_argument(stmt!["using = ", serializer_type, ".class"]); event.spec.push_annotation(serialize_annotation); event.spec.push(serializer); let deserializer = self.tuple_deserializer(&event.fields, &event.class_type)?; let deserializer_type = Type::class(&event.class_type.package, &format!("{}.{}", &event.class_type.name, deserializer.name)); let mut deserialize_annotation: AnnotationSpec = self.deserialize.clone().into(); deserialize_annotation.push_argument(stmt!["using = ", deserializer_type, ".class"]); event.spec.push_annotation(deserialize_annotation); event.spec.push(deserializer); Ok(()) } fn enum_added(&self, event: &mut EnumAdded) -> Result<()> { if let Some(ref mut from_value) = *event.from_value { from_value.push_annotation(&self.creator); } if let Some(ref mut to_value) = *event.to_value { to_value.push_annotation(&self.value); } Ok(()) } fn interface_added(&self, event: &mut InterfaceAdded) -> Result<()> { { let mut arguments = Statement::new(); arguments.push(stmt!["use=", &self.type_info, ".Id.NAME"]); arguments.push(stmt!["include=", &self.type_info, ".As.PROPERTY"]); arguments.push(stmt!["property=", Variable::String("type".to_owned())]); let mut type_info = AnnotationSpec::new(&self.type_info); type_info.push_argument(arguments.join(", ")); event.spec.push_annotation(&type_info); } { let mut arguments = Statement::new(); for (key, sub_type) in &event.interface.sub_types { for name in &sub_type.names { let name: String = name.inner.to_owned(); let mut type_args = Statement::new(); type_args.push(stmt!["name=", Variable::String(name)]); type_args.push(stmt!["value=", &event.spec.name, ".", key, ".class"]); let a = stmt!["@", &self.sub_types, ".Type(", type_args.join(", "), ")"]; arguments.push(a); } } let mut sub_types = AnnotationSpec::new(&self.sub_types); sub_types.push_argument(stmt!["{", arguments.join(", "), "}"]); event.spec.push_annotation(&sub_types); } Ok(()) } }
//! Provides utility functions for generating data sequences use euclid::Modulus; use std::f64::consts; use std::iter::Take; /// Generates a base 10 log spaced vector of the given length between the /// specified decade exponents (inclusive). Equivalent to MATLAB logspace /// /// # Examples /// /// ``` /// use statrs::generate; /// /// let x = generate::log_spaced(5, 0.0, 4.0); /// assert_eq!(x, [1.0, 10.0, 100.0, 1000.0, 10000.0]); /// ``` pub fn log_spaced(length: usize, start_exp: f64, stop_exp: f64) -> Vec<f64> { match length { 0 => Vec::new(), 1 => vec![10f64.powf(stop_exp)], _ => { let step = (stop_exp - start_exp) / (length - 1) as f64; let mut vec = (0..length) .map(|x| 10f64.powf(start_exp + (x as f64) * step)) .collect::<Vec<f64>>(); vec[length - 1] = 10f64.powf(stop_exp); vec } } } /// Infinite iterator returning floats that form a periodic wave pub struct InfinitePeriodic { amplitude: f64, step: f64, phase: f64, k: f64, } impl InfinitePeriodic { /// Constructs a new infinite periodic wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfinitePeriodic; /// /// let x = InfinitePeriodic::new(8.0, 2.0, 10.0, 1.0, /// 2).take(10).collect::<Vec<f64>>(); /// assert_eq!(x, [6.0, 8.5, 1.0, 3.5, 6.0, 8.5, 1.0, 3.5, 6.0, 8.5]); /// ``` pub fn new( sampling_rate: f64, frequency: f64, amplitude: f64, phase: f64, delay: i64, ) -> InfinitePeriodic { let step = frequency / sampling_rate * amplitude; InfinitePeriodic { amplitude: amplitude, step: step, phase: (phase - delay as f64 * step).modulus(amplitude), k: 0.0, } } /// Constructs a default infinite periodic wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfinitePeriodic; /// /// let x = InfinitePeriodic::default(8.0, /// 2.0).take(10).collect::<Vec<f64>>(); /// assert_eq!(x, [0.0, 0.25, 0.5, 0.75, 0.0, 0.25, 0.5, 0.75, 0.0, 0.25]); /// ``` pub fn default(sampling_rate: f64, frequency: f64) -> InfinitePeriodic { Self::new(sampling_rate, frequency, 1.0, 0.0, 0) } } impl Iterator for InfinitePeriodic { type Item = f64; fn next(&mut self) -> Option<f64> { let mut x = self.phase + self.k * self.step; if x >= self.amplitude { x %= self.amplitude; self.phase = x; self.k = 0.0; } self.k += 1.0; Some(x) } } /// Finite iterator returning floats that form a periodic wave pub struct Periodic { internal: Take<InfinitePeriodic>, } impl Periodic { /// Constructs a new periodic wave generator /// /// # Examples /// /// ``` /// use statrs::generate::Periodic; /// /// let x = Periodic::new(10, 8.0, 2.0, 10.0, 1.0, 2).collect::<Vec<f64>>(); /// assert_eq!(x, [6.0, 8.5, 1.0, 3.5, 6.0, 8.5, 1.0, 3.5, 6.0, 8.5]); /// ``` #[deprecated( since = "0.9.0", note = "please use `InfinitePeriodic::new` and `take` instead" )] pub fn new( length: usize, sampling_rate: f64, frequency: f64, amplitude: f64, phase: f64, delay: i64, ) -> Periodic { Periodic { internal: InfinitePeriodic::new(sampling_rate, frequency, amplitude, phase, delay) .take(length), } } /// Constructs a default periodic wave generator /// /// # Examples /// /// ``` /// use statrs::generate::Periodic; /// /// let x = Periodic::default(10, 8.0, 2.0).collect::<Vec<f64>>(); /// assert_eq!(x, [0.0, 0.25, 0.5, 0.75, 0.0, 0.25, 0.5, 0.75, 0.0, 0.25]); /// ``` #[deprecated( since = "0.9.0", note = "please use `InfinitePeriodic::default` and `take` instead" )] pub fn default(length: usize, sampling_rate: f64, frequency: f64) -> Periodic { Periodic { internal: InfinitePeriodic::default(sampling_rate, frequency).take(length), } } } impl Iterator for Periodic { type Item = f64; fn next(&mut self) -> Option<f64> { self.internal.next() } } /// Infinite iterator returning floats that form a sinusoidal wave pub struct InfiniteSinusoidal { amplitude: f64, mean: f64, step: f64, phase: f64, i: usize, } impl InfiniteSinusoidal { /// Constructs a new infinite sinusoidal wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfiniteSinusoidal; /// /// let x = InfiniteSinusoidal::new(8.0, 2.0, 1.0, 5.0, 2.0, /// 1).take(10).collect::<Vec<f64>>(); /// assert_eq!(x, /// [5.416146836547142, 5.909297426825682, 4.583853163452858, /// 4.090702573174318, 5.416146836547142, 5.909297426825682, /// 4.583853163452858, 4.090702573174318, 5.416146836547142, /// 5.909297426825682]); /// ``` pub fn new( sampling_rate: f64, frequency: f64, amplitude: f64, mean: f64, phase: f64, delay: i64, ) -> InfiniteSinusoidal { let pi2 = consts::PI * 2.0; let step = frequency / sampling_rate * pi2; InfiniteSinusoidal { amplitude: amplitude, mean: mean, step: step, phase: (phase - delay as f64 * step) % pi2, i: 0, } } /// Constructs a default infinite sinusoidal wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfiniteSinusoidal; /// /// let x = InfiniteSinusoidal::default(8.0, 2.0, /// 1.0).take(10).collect::<Vec<f64>>(); /// assert_eq!(x, /// [0.0, 1.0, 0.00000000000000012246467991473532, /// -1.0, -0.00000000000000024492935982947064, 1.0, /// 0.00000000000000036739403974420594, -1.0, /// -0.0000000000000004898587196589413, 1.0]); /// ``` pub fn default(sampling_rate: f64, frequency: f64, amplitude: f64) -> InfiniteSinusoidal { Self::new(sampling_rate, frequency, amplitude, 0.0, 0.0, 0) } } impl Iterator for InfiniteSinusoidal { type Item = f64; fn next(&mut self) -> Option<f64> { let x = self.mean + self.amplitude * (self.phase + self.i as f64 * self.step).sin(); self.i += 1; if self.i == 1000 { self.i = 0; self.phase = (self.phase + 1000.0 * self.step) % (consts::PI * 2.0); } Some(x) } } /// Finite iterator returning floats that form a sinusoidal wave pub struct Sinusoidal { internal: Take<InfiniteSinusoidal>, } impl Sinusoidal { /// Constructs a new sinusoidal wave generator /// /// # Examples /// /// ``` /// use statrs::generate::Sinusoidal; /// /// let x = Sinusoidal::new(10, 8.0, 2.0, 1.0, 5.0, 2.0, /// 1).collect::<Vec<f64>>(); /// assert_eq!(x, /// [5.416146836547142, 5.909297426825682, 4.583853163452858, /// 4.090702573174318, 5.416146836547142, 5.909297426825682, /// 4.583853163452858, 4.090702573174318, 5.416146836547142, /// 5.909297426825682]); /// ``` #[deprecated( since = "0.9.0", note = "please use `InfiniteSinusoidal::new` and `take` instead" )] pub fn new( length: usize, sampling_rate: f64, frequency: f64, amplitude: f64, mean: f64, phase: f64, delay: i64, ) -> Sinusoidal { Sinusoidal { internal: InfiniteSinusoidal::new( sampling_rate, frequency, amplitude, mean, phase, delay, ).take(length), } } /// Constructs a default sinusoidal wave generator /// /// # Examples /// /// ``` /// use statrs::generate::Sinusoidal; /// /// let x = Sinusoidal::default(10, 8.0, 2.0, 1.0).collect::<Vec<f64>>(); /// assert_eq!(x, /// [0.0, 1.0, 0.00000000000000012246467991473532, /// -1.0, -0.00000000000000024492935982947064, 1.0, /// 0.00000000000000036739403974420594, -1.0, /// -0.0000000000000004898587196589413, 1.0]); /// ``` #[deprecated( since = "0.9.0", note = "please use `InfiniteSinusoidal::default` and `take` instead" )] pub fn default( length: usize, sampling_rate: f64, frequency: f64, amplitude: f64, ) -> Sinusoidal { Sinusoidal { internal: InfiniteSinusoidal::default(sampling_rate, frequency, amplitude).take(length), } } } impl Iterator for Sinusoidal { type Item = f64; fn next(&mut self) -> Option<f64> { self.internal.next() } } /// Infinite iterator returning floats forming a square wave starting /// with the high phase pub struct InfiniteSquare { periodic: InfinitePeriodic, high_duration: f64, high_value: f64, low_value: f64, } impl InfiniteSquare { /// Constructs a new infinite square wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfiniteSquare; /// /// let x = InfiniteSquare::new(3, 7, 1.0, -1.0, /// 1).take(12).collect::<Vec<f64>>(); /// assert_eq!(x, [-1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, /// -1.0, 1.0]) /// ``` pub fn new( high_duration: i64, low_duration: i64, high_value: f64, low_value: f64, delay: i64, ) -> InfiniteSquare { let duration = (high_duration + low_duration) as f64; InfiniteSquare { periodic: InfinitePeriodic::new(1.0, 1.0 / duration, duration, 0.0, delay), high_duration: high_duration as f64, high_value: high_value, low_value: low_value, } } } impl Iterator for InfiniteSquare { type Item = f64; fn next(&mut self) -> Option<f64> { self.periodic.next().and_then(|x| { if x < self.high_duration { Some(self.high_value) } else { Some(self.low_value) } }) } } /// Finite iterator returning floats forming a square wave starting /// with the high phase pub struct Square { internal: Take<InfiniteSquare>, } impl Square { /// Constructs a new square wave generator /// /// # Examples /// /// ``` /// use statrs::generate::Square; /// /// let x = Square::new(12, 3, 7, 1.0, -1.0, 1).collect::<Vec<f64>>(); /// assert_eq!(x, [-1.0, 1.0, 1.0, 1.0, -1.0, -1.0, -1.0, -1.0, -1.0, -1.0, /// -1.0, 1.0]) /// ``` #[deprecated( since = "0.9.0", note = "please use `InfiniteSquare::new` and `take` instead" )] pub fn new( length: usize, high_duration: i64, low_duration: i64, high_value: f64, low_value: f64, delay: i64, ) -> Square { Square { internal: InfiniteSquare::new( high_duration, low_duration, high_value, low_value, delay, ).take(length), } } } impl Iterator for Square { type Item = f64; fn next(&mut self) -> Option<f64> { self.internal.next() } } /// Infinite iterator returning floats forming a triangle wave starting with /// the raise phase from the lowest sample pub struct InfiniteTriangle { periodic: InfinitePeriodic, raise_duration: f64, raise: f64, fall: f64, high_value: f64, low_value: f64, } impl InfiniteTriangle { /// Constructs a new infinite triangle wave generator /// /// # Examples /// /// ``` /// #[macro_use] /// extern crate statrs; /// /// use statrs::generate::InfiniteTriangle; /// /// # fn main() { /// let x = InfiniteTriangle::new(4, 7, 1.0, -1.0, /// 1).take(12).collect::<Vec<f64>>(); /// let expected: [f64; 12] = [-0.714, -1.0, -0.5, 0.0, 0.5, 1.0, 0.714, /// 0.429, 0.143, -0.143, -0.429, -0.714]; /// for (&left, &right) in x.iter().zip(expected.iter()) { /// assert_almost_eq!(left, right, 1e-3); /// } /// # } /// ``` pub fn new( raise_duration: i64, fall_duration: i64, high_value: f64, low_value: f64, delay: i64, ) -> InfiniteTriangle { let duration = (raise_duration + fall_duration) as f64; let height = high_value - low_value; InfiniteTriangle { periodic: InfinitePeriodic::new(1.0, 1.0 / duration, duration, 0.0, delay), raise_duration: raise_duration as f64, raise: height / raise_duration as f64, fall: height / fall_duration as f64, high_value: high_value, low_value: low_value, } } } impl Iterator for InfiniteTriangle { type Item = f64; fn next(&mut self) -> Option<f64> { self.periodic.next().and_then(|x| { if x < self.raise_duration { Some(self.low_value + x * self.raise) } else { Some(self.high_value - (x - self.raise_duration) * self.fall) } }) } } /// Finite iterator returning floats forming a triangle wave /// starting with the raise phase from the lowest sample pub struct Triangle { internal: Take<InfiniteTriangle>, } impl Triangle { /// Constructs a new triangle wave generator /// /// # Examples /// /// ``` /// #[macro_use] /// extern crate statrs; /// /// use statrs::generate::Triangle; /// /// # fn main() { /// let x = Triangle::new(12, 4, 7, 1.0, -1.0, 1).collect::<Vec<f64>>(); /// let expected: [f64; 12] = [-0.714, -1.0, -0.5, 0.0, 0.5, 1.0, 0.714, /// 0.429, 0.143, -0.143, -0.429, -0.714]; /// for (&left, &right) in x.iter().zip(expected.iter()) { /// assert_almost_eq!(left, right, 1e-3); /// } /// # } /// ``` #[deprecated( since = "0.9.0", note = "please use `InfiniteTriangle::new` and `take` instead" )] pub fn new( length: usize, raise_duration: i64, fall_duration: i64, high_value: f64, low_value: f64, delay: i64, ) -> Triangle { Triangle { internal: InfiniteTriangle::new( raise_duration, fall_duration, high_value, low_value, delay, ).take(length), } } } impl Iterator for Triangle { type Item = f64; fn next(&mut self) -> Option<f64> { self.internal.next() } } /// Infinite iterator returning floats forming a sawtooth wave /// starting with the lowest sample pub struct InfiniteSawtooth { periodic: InfinitePeriodic, low_value: f64, } impl InfiniteSawtooth { /// Constructs a new infinite sawtooth wave generator /// /// # Examples /// /// ``` /// use statrs::generate::InfiniteSawtooth; /// /// let x = InfiniteSawtooth::new(5, 1.0, -1.0, /// 1).take(12).collect::<Vec<f64>>(); /// assert_eq!(x, [1.0, -1.0, -0.5, 0.0, 0.5, 1.0, -1.0, -0.5, 0.0, 0.5, /// 1.0, -1.0]); /// ``` pub fn new(period: i64, high_value: f64, low_value: f64, delay: i64) -> InfiniteSawtooth { let height = high_value - low_value; let period = period as f64; InfiniteSawtooth { periodic: InfinitePeriodic::new( 1.0, 1.0 / period, height * period / (period - 1.0), 0.0, delay, ), low_value: low_value as f64, } } } impl Iterator for InfiniteSawtooth { type Item = f64; fn next(&mut self) -> Option<f64> { self.periodic.next().and_then(|x| Some(x + self.low_value)) } } /// Finite iterator returning floats forming a sawtooth wave /// starting with the lowest sample pub struct Sawtooth { internal: Take<InfiniteSawtooth>, } impl Sawtooth { /// Constructs a new sawtooth wave generator /// /// # Examples /// /// ``` /// use statrs::generate::Sawtooth; /// /// let x = Sawtooth::new(12, 5, 1.0, -1.0, 1).collect::<Vec<f64>>(); /// assert_eq!(x, [1.0, -1.0, -0.5, 0.0, 0.5, 1.0, -1.0, -0.5, 0.0, 0.5, /// 1.0, -1.0]); /// ``` #[deprecated( since = "0.9.0", note = "please use `InfiniteSawtooth::new` and `take` instead" )] pub fn new( length: usize, period: i64, high_value: f64, low_value: f64, delay: i64, ) -> Sawtooth { Sawtooth { internal: InfiniteSawtooth::new(period, high_value, low_value, delay).take(length), } } } impl Iterator for Sawtooth { type Item = f64; fn next(&mut self) -> Option<f64> { self.internal.next() } }
use std::{collections::HashMap, io, num::ParseIntError, str::FromStr}; use problem::{solve, Problem, ProblemInput}; #[derive(Clone)] enum Rule { Literal(char), Sequence(Vec<usize>), Alternate(Vec<usize>, Vec<usize>), } impl Rule { fn matches<'a>(&self, rules: &HashMap<usize, Rule>, s: &'a str) -> Vec<&'a str> { let mut results = Vec::new(); match self { &Rule::Literal(c) => { if s.chars().next() == Some(c) { results.push(&s[1..]); } }, Rule::Sequence(seq) => { let mut current_matches = vec![s]; for rule in seq.iter() { let mut next_matches = Vec::new(); for s in current_matches { next_matches.append(&mut rules[rule].matches(rules, s)); } current_matches = next_matches; } results.append(&mut current_matches); }, Rule::Alternate(seq_a, seq_b) => { for &seq in [seq_a, seq_b].iter() { let mut current_matches = vec![s]; for rule in seq.iter() { let mut next_matches = Vec::new(); for s in current_matches { next_matches.append(&mut rules[rule].matches(rules, s)); } current_matches = next_matches; } results.append(&mut current_matches); } } } results } } impl FromStr for Rule { type Err = ParseIntError; fn from_str(s: &str) -> Result<Self, Self::Err> { if s.len() == 3 && s.chars().nth(0).unwrap() == '"' && s.chars().nth(2).unwrap() == '"' { Ok(Rule::Literal(s.chars().nth(1).unwrap())) } else if let Some(bar_pos) = s.find(" | ") { Ok(Rule::Alternate( s[..bar_pos].split(' ').map(|p| p.parse()).collect::<Result<_, _>>()?, s[bar_pos + 3..].split(' ').map(|p| p.parse()).collect::<Result<_, _>>()?, )) } else { Ok(Rule::Sequence( s.split(' ').map(|p| p.parse()).collect::<Result<_, _>>()? )) } } } struct Input { rules: HashMap<usize, Rule>, strings: Vec<String>, } #[derive(Debug)] enum ParseInputError { IoError(io::Error), ParseIntError(ParseIntError), MissingRuleId, MissingRuleDef, } impl From<io::Error> for ParseInputError { fn from(e: io::Error) -> Self { Self::IoError(e) } } impl From<ParseIntError> for ParseInputError { fn from(e: ParseIntError) -> Self { Self::ParseIntError(e) } } impl ProblemInput for Input { type Error = ParseInputError; fn parse<R: io::BufRead>(reader: R) -> Result<Self, Self::Error> { let mut lines = reader.lines(); let mut rules = HashMap::new(); while let Some(line) = lines.next() { let line = line?; if line.len() == 0 { break; } let mut pieces = line.split(": "); let index = pieces.next().ok_or(ParseInputError::MissingRuleId)?.parse()?; let rule = pieces.next().ok_or(ParseInputError::MissingRuleDef)?.parse()?; rules.insert(index, rule); } let mut strings = Vec::new(); while let Some(line) = lines.next() { strings.push(line?.to_string()); } Ok(Self { rules, strings, }) } } struct Day19; impl Problem for Day19 { type Input = Input; type Part1Output = usize; type Part2Output = usize; type Error = (); fn part_1(input: &Self::Input) -> Result<Self::Part1Output, Self::Error> { Ok(input.strings.iter().map(|s| input.rules[&0].matches(&input.rules, s.as_str())).filter(|matches| matches.contains(&"")).count()) } fn part_2(input: &Self::Input) -> Result<Self::Part2Output, Self::Error> { let mut rules = input.rules.clone(); rules.insert(8, Rule::Alternate(vec![42], vec![42, 8])); rules.insert(11, Rule::Alternate(vec![42, 31], vec![42, 11, 31])); Ok(input.strings.iter().map(|s| rules[&0].matches(&rules, s.as_str())).filter(|matches| matches.contains(&"")).count()) } } fn main() { solve::<Day19>("input").unwrap(); }
mod lib; pub use lib::*;
/// Converts the borrowed value of `Boo` to owned. See `Boo::into_owned_with` for details. pub trait BooToOwned<TBorrowed: ?Sized, TOwned> { /// Converts the borrowed value of `Boo` to owned. fn convert_to_owned(borrowed: &TBorrowed) -> TOwned; }
use std::io; use std::str::FromStr; #[allow(dead_code)] fn read_line() -> String { let mut buffer = String::new(); io::stdin() .read_line(&mut buffer) .expect("failed to read line"); buffer } #[allow(dead_code)] fn read<T : FromStr>() -> Result<T, T::Err>{ read_line().trim().parse::<T>() } #[allow(dead_code)] fn read_vec<T : FromStr>() -> Result< Vec<T>, T::Err>{ read_line().split_whitespace().map(|x| x.parse::<T>()).collect() } fn solve(){ let l = read_line().trim().to_lowercase(); match l.as_ref() { "yes" => println!("YES"), "10" => (), _ => println!("NO"), } } fn main() { let t = read::<i32>().unwrap(); for _ in 0..t { solve(); } }
mod common; pub use common::*; use crate::{qjs, Map}; #[derive(qjs::FromJs)] pub struct ExecArg { pub cmd: String, #[quickjs(default)] pub args: Option<Vec<String>>, #[quickjs(default)] pub envs: Option<Map<String, String>>, #[quickjs(default)] pub cwd: Option<String>, #[quickjs(default)] pub input: Option<String>, } #[derive(qjs::IntoJs)] pub struct ExecRes { pub status: Option<i32>, pub output: String, pub error: String, } #[qjs::bind(module, public)] #[quickjs(bare)] mod js { use super::*; pub async fn sleep(msec: u64) { async_std::task::sleep(std::time::Duration::from_millis(msec)).await; } pub async fn is_file(path: String) -> bool { let path = Path::new(&path); path.is_file().await } pub async fn is_dir(path: String) -> bool { let path = Path::new(&path); path.is_dir().await } pub async fn exists(path: String) -> bool { let path = Path::new(&path); path.exists().await } pub async fn remove(path: String) -> qjs::Result<bool> { let path = Path::new(&path); Ok( if let Some(meta) = path.metadata().await.map(Some).or_else(|error| { if matches!(error.kind(), std::io::ErrorKind::NotFound) { Ok(None) } else { Err(error) } })? { if meta.is_file() { async_std::fs::remove_file(path).await? } else { async_std::fs::remove_dir_all(path).await? } true } else { false }, ) } pub async fn exec(input: ExecArg) -> qjs::Result<ExecRes> { let mut cmd = Command::new(input.cmd); if let Some(args) = input.args { cmd.args(args); } if let Some(envs) = input.envs { cmd.envs(envs); } if let Some(cwd) = input.cwd { cmd.current_dir(cwd); } if input.input.is_some() { cmd.stdin(Stdio::piped()); } cmd.stdout(Stdio::piped()); cmd.stderr(Stdio::piped()); let mut handle = cmd.spawn()?; if let Some(input) = input.input { if let Some(stdin) = &mut handle.stdin { stdin.write_all(input.as_bytes()).await?; } else { return Err(qjs::Error::Unknown); } } let result = handle.output().await?; let status = result.status.code(); let output = String::from_utf8(result.stdout)?; let error = String::from_utf8(result.stderr)?; Ok(ExecRes { status, output, error, }) } }
#[doc = "Register `BDMUPR` reader"] pub type R = crate::R<BDMUPR_SPEC>; #[doc = "Register `BDMUPR` writer"] pub type W = crate::W<BDMUPR_SPEC>; #[doc = "Field `MCR` reader - MCR"] pub type MCR_R = crate::BitReader<MCR_A>; #[doc = "MCR\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum MCR_A { #[doc = "0: Register not updated by burst DMA access"] NotUpdated = 0, #[doc = "1: Register updated by burst DMA access"] Updated = 1, } impl From<MCR_A> for bool { #[inline(always)] fn from(variant: MCR_A) -> Self { variant as u8 != 0 } } impl MCR_R { #[doc = "Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> MCR_A { match self.bits { false => MCR_A::NotUpdated, true => MCR_A::Updated, } } #[doc = "Register not updated by burst DMA access"] #[inline(always)] pub fn is_not_updated(&self) -> bool { *self == MCR_A::NotUpdated } #[doc = "Register updated by burst DMA access"] #[inline(always)] pub fn is_updated(&self) -> bool { *self == MCR_A::Updated } } #[doc = "Field `MCR` writer - MCR"] pub type MCR_W<'a, REG, const O: u8> = crate::BitWriter<'a, REG, O, MCR_A>; impl<'a, REG, const O: u8> MCR_W<'a, REG, O> where REG: crate::Writable + crate::RegisterSpec, { #[doc = "Register not updated by burst DMA access"] #[inline(always)] pub fn not_updated(self) -> &'a mut crate::W<REG> { self.variant(MCR_A::NotUpdated) } #[doc = "Register updated by burst DMA access"] #[inline(always)] pub fn updated(self) -> &'a mut crate::W<REG> { self.variant(MCR_A::Updated) } } #[doc = "Field `MICR` reader - MICR"] pub use MCR_R as MICR_R; #[doc = "Field `MDIER` reader - MDIER"] pub use MCR_R as MDIER_R; #[doc = "Field `MCNT` reader - MCNT"] pub use MCR_R as MCNT_R; #[doc = "Field `MPER` reader - MPER"] pub use MCR_R as MPER_R; #[doc = "Field `MREP` reader - MREP"] pub use MCR_R as MREP_R; #[doc = "Field `MCMP1` reader - MCMP1"] pub use MCR_R as MCMP1_R; #[doc = "Field `MCMP2` reader - MCMP2"] pub use MCR_R as MCMP2_R; #[doc = "Field `MCMP3` reader - MCMP3"] pub use MCR_R as MCMP3_R; #[doc = "Field `MCMP4` reader - MCMP4"] pub use MCR_R as MCMP4_R; #[doc = "Field `MICR` writer - MICR"] pub use MCR_W as MICR_W; #[doc = "Field `MDIER` writer - MDIER"] pub use MCR_W as MDIER_W; #[doc = "Field `MCNT` writer - MCNT"] pub use MCR_W as MCNT_W; #[doc = "Field `MPER` writer - MPER"] pub use MCR_W as MPER_W; #[doc = "Field `MREP` writer - MREP"] pub use MCR_W as MREP_W; #[doc = "Field `MCMP1` writer - MCMP1"] pub use MCR_W as MCMP1_W; #[doc = "Field `MCMP2` writer - MCMP2"] pub use MCR_W as MCMP2_W; #[doc = "Field `MCMP3` writer - MCMP3"] pub use MCR_W as MCMP3_W; #[doc = "Field `MCMP4` writer - MCMP4"] pub use MCR_W as MCMP4_W; impl R { #[doc = "Bit 0 - MCR"] #[inline(always)] pub fn mcr(&self) -> MCR_R { MCR_R::new((self.bits & 1) != 0) } #[doc = "Bit 1 - MICR"] #[inline(always)] pub fn micr(&self) -> MICR_R { MICR_R::new(((self.bits >> 1) & 1) != 0) } #[doc = "Bit 2 - MDIER"] #[inline(always)] pub fn mdier(&self) -> MDIER_R { MDIER_R::new(((self.bits >> 2) & 1) != 0) } #[doc = "Bit 3 - MCNT"] #[inline(always)] pub fn mcnt(&self) -> MCNT_R { MCNT_R::new(((self.bits >> 3) & 1) != 0) } #[doc = "Bit 4 - MPER"] #[inline(always)] pub fn mper(&self) -> MPER_R { MPER_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 5 - MREP"] #[inline(always)] pub fn mrep(&self) -> MREP_R { MREP_R::new(((self.bits >> 5) & 1) != 0) } #[doc = "Bit 6 - MCMP1"] #[inline(always)] pub fn mcmp1(&self) -> MCMP1_R { MCMP1_R::new(((self.bits >> 6) & 1) != 0) } #[doc = "Bit 7 - MCMP2"] #[inline(always)] pub fn mcmp2(&self) -> MCMP2_R { MCMP2_R::new(((self.bits >> 7) & 1) != 0) } #[doc = "Bit 8 - MCMP3"] #[inline(always)] pub fn mcmp3(&self) -> MCMP3_R { MCMP3_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bit 9 - MCMP4"] #[inline(always)] pub fn mcmp4(&self) -> MCMP4_R { MCMP4_R::new(((self.bits >> 9) & 1) != 0) } } impl W { #[doc = "Bit 0 - MCR"] #[inline(always)] #[must_use] pub fn mcr(&mut self) -> MCR_W<BDMUPR_SPEC, 0> { MCR_W::new(self) } #[doc = "Bit 1 - MICR"] #[inline(always)] #[must_use] pub fn micr(&mut self) -> MICR_W<BDMUPR_SPEC, 1> { MICR_W::new(self) } #[doc = "Bit 2 - MDIER"] #[inline(always)] #[must_use] pub fn mdier(&mut self) -> MDIER_W<BDMUPR_SPEC, 2> { MDIER_W::new(self) } #[doc = "Bit 3 - MCNT"] #[inline(always)] #[must_use] pub fn mcnt(&mut self) -> MCNT_W<BDMUPR_SPEC, 3> { MCNT_W::new(self) } #[doc = "Bit 4 - MPER"] #[inline(always)] #[must_use] pub fn mper(&mut self) -> MPER_W<BDMUPR_SPEC, 4> { MPER_W::new(self) } #[doc = "Bit 5 - MREP"] #[inline(always)] #[must_use] pub fn mrep(&mut self) -> MREP_W<BDMUPR_SPEC, 5> { MREP_W::new(self) } #[doc = "Bit 6 - MCMP1"] #[inline(always)] #[must_use] pub fn mcmp1(&mut self) -> MCMP1_W<BDMUPR_SPEC, 6> { MCMP1_W::new(self) } #[doc = "Bit 7 - MCMP2"] #[inline(always)] #[must_use] pub fn mcmp2(&mut self) -> MCMP2_W<BDMUPR_SPEC, 7> { MCMP2_W::new(self) } #[doc = "Bit 8 - MCMP3"] #[inline(always)] #[must_use] pub fn mcmp3(&mut self) -> MCMP3_W<BDMUPR_SPEC, 8> { MCMP3_W::new(self) } #[doc = "Bit 9 - MCMP4"] #[inline(always)] #[must_use] pub fn mcmp4(&mut self) -> MCMP4_W<BDMUPR_SPEC, 9> { MCMP4_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 = "BDMUPDR\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`bdmupr::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 [`bdmupr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct BDMUPR_SPEC; impl crate::RegisterSpec for BDMUPR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`bdmupr::R`](R) reader structure"] impl crate::Readable for BDMUPR_SPEC {} #[doc = "`write(|w| ..)` method takes [`bdmupr::W`](W) writer structure"] impl crate::Writable for BDMUPR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets BDMUPR to value 0"] impl crate::Resettable for BDMUPR_SPEC { const RESET_VALUE: Self::Ux = 0; }
use crate::{PingResult, Target}; use core::cmp; use std::collections::HashMap; fn print_columns(indent: usize, header: Vec<String>, columns: Vec<Vec<String>>) { let mut lens: Vec<usize> = columns.clone() .into_iter() .map(|c| c.into_iter() .map(|s| s.len()) .max() .unwrap()) .collect(); print!("{}", " ".to_string().repeat(indent)); for i in 0..header.len() { lens[i] = cmp::max(lens[i], header[i].len()); let s = &header[i]; print!("{}{} ", s, " ".to_string().repeat(lens[i] - s.len())); } println!(""); let width: usize = lens.clone().into_iter().sum(); println!("{}{}", " ".to_string().repeat(indent), "-".to_string().repeat(width + lens.len() - 1)); for i in 0..columns[0].len() { // Indent print!("{}", " ".to_string().repeat(indent)); for j in 0..columns.len() { let s = &columns[j][i]; print!("{}{} ", s, " ".to_string().repeat(lens[j] - s.len())); } println!(""); } } fn format_field<F, G>(ips: &Vec<Target>, res: &HashMap<String, PingResult>, f: F) -> Vec<String> where F: FnMut(&PingResult) -> G, G: std::fmt::Debug { ips.into_iter() .map(|t| res.get(&t.target).unwrap()) .map(f) .map(|t| format!("{:?}", t).replace("µ", "u")) .collect() } pub fn print_summary(ips: &Vec<Target>, res: &HashMap<String, PingResult>) { if ips.len() < 1 { return } print_columns(4, vec![ "Target".to_string(), "IP".to_string(), "RTT".to_string(), "Loss".to_string() ], vec![ ips.into_iter().map(|t| format!("{}", t.name)).collect(), ips.into_iter().map(|t| format!("{}", t.target)).collect(), format_field(&ips, &res, |r| r.rtt()), format_field(&ips, &res, |r| r.loss()) ]); }
#![allow(unused)] use std::cell::RefCell; use std::time::Duration; use std::collections::HashMap; use std::cmp::Ordering; use std::thread; use priority_queue::PriorityQueue; use rand::IsaacRng; use rand::prelude::RngCore; use xcg::model::*; use xcg::bot::KillerBot; use xcg::utils::Trim; use xcg::bot::common::{P, a_star_find}; use xcg::bot::common::distance; use xcg::bot::common::Weight; fn main() { let random = RefCell::new(IsaacRng::new_from_u64(234)); let m = 32; let n = 54; // let m = 32; // let n = 54; let timeout = 40; let a = KillerBot::new(0); let b = KillerBot::new(1); let c = KillerBot::new(2); let d = KillerBot::new(3); // let mut bots: [Box<dyn Bot>; 2] = [Box::new(a), Box::new(b)]; let mut bots: [Box<dyn Bot>; 4] = [Box::new(a), Box::new(b), Box::new(c), Box::new(d)]; let names: Vec<String> = bots.iter().enumerate() .map(|(k, _)| ((('A' as u8) + (k as u8)) as char).to_string()) .collect(); let logger = |gs: &GameState| { if gs.stats.iteration > 0 { println!("{}", prettify_game_state(gs, true, true)); thread::sleep(Duration::from_millis(timeout)); } }; let count = 100_000; let random = RefCell::new(IsaacRng::new_from_u64(234)); let mut seeds = Vec::with_capacity(count); for it in 0..count { let match_k_seed = random.borrow_mut().next_u64(); seeds.push(match_k_seed); } for it in 0..1 { // let seed = random.borrow_mut().next_u64(); let seed = 10591930711989851205; // let seed = seeds[it]; let mut match_k = create_match(m, n, &names, 1024, 0.95, Some(seed)); let _replay_k = run_match(&mut match_k, &mut bots, &logger); // println!("{} {:?}", "\n".repeat(m + names.len()), match_k.game_state.stats); let stats = match_k.game_state.stats.clone(); let i = stats.iteration; let o = stats.ouroboros_count; let b = stats.bite_count; let h = stats.head_to_head_count; let s = stats.scores; println!("{:06}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}", it, i, o, b, h, seed, s[0], s[1], s[2], s[3]); // println!("{:06}\t{}\t{}\t{}\t{}\t{}\t{}\t{}", it, i, o, b, h, seed, s[0], s[1]); println!("{}", prettify_game_state(&match_k.game_state, false, true)); } }
extern crate curl; use std::fs::{self, File}; use std::io::Write; use std::path::Path; use std::str; use self::curl::easy::Easy; use utils::errors::LeanpubResult; pub trait HttpClient { fn get(&self, uri: &str) -> LeanpubResult<String>; fn download(&self, uri: &str, path: &Path) -> LeanpubResult<()>; } pub struct DefaultHttpClient { } impl HttpClient for DefaultHttpClient { fn get(&self, uri: &str) -> LeanpubResult<String> { let mut handle = Easy::new(); handle.follow_location(true)?; // Follow redirects. handle.url(uri)?; // Set the URL. let mut content: String = String::new(); { let mut transfer = handle.transfer(); transfer.write_function(|data| { content.push_str(str::from_utf8(data).unwrap()); Ok(data.len()) })?; transfer.perform()?; } return Ok(content); } fn download(&self, uri: &str, path: &Path) -> LeanpubResult<()> { let mut handle = Easy::new(); handle.follow_location(true)?; // Follow redirects. handle.url(uri)?; // Set the URL. // Download the file. let mut file = File::create(path)?; handle.write_function(move |data| { return Ok(file.write(data).unwrap()); })?; handle.perform()?; // Check the response code. let response = handle.response_code()?; if response != 200 { fs::remove_file(path)?; // Delete the file. return Err(format_err!( "Expected status code 200 but received {}.", response )); } return Ok(()); } } // ------------------------------------------------------------------------------ // Test utilities // ------------------------------------------------------------------------------ #[cfg(test)] pub struct FakeHttpClient { content: String, } #[cfg(test)] #[macro_export] macro_rules! create_fake_client { ($api_key:expr, $content:expr) => { Client { api_key: $api_key, client: Box::new(utils::http::FakeHttpClient::new($content)), }; }; } #[cfg(test)] impl FakeHttpClient { #[cfg(test)] pub fn new(content: &str) -> FakeHttpClient { return FakeHttpClient { content: content.to_string(), }; } } #[cfg(test)] impl HttpClient for FakeHttpClient { fn get(&self, _uri: &str) -> LeanpubResult<String> { return Ok(self.content.clone()); } fn download(&self, _uri: &str, _path: &Path) -> LeanpubResult<()> { return Ok(()); } }
fn main() { let mut txt = String::from("first"); converter(txt); } fn converter(mut s: String) { let vowels = ['a', 'i', 'u', 'e', 'o']; let mut hay = String::from("-hay"); let head = &s.chars().nth(0).unwrap(); if vowels.contains(&head) == false { hay = format!("-{}ay", head); } s.push_str(&hay); s.remove(0); println!("{}", s); }
use std::net::TcpListener; pub fn server() { let listener = TcpListener::bind("0.0.0.0:8080").unwrap(); for stream in listener.incoming() { println!("coonection",); let _stream = stream.unwrap(); } }
#[doc = "Register `PUPDR` reader"] pub type R = crate::R<PUPDR_SPEC>; #[doc = "Register `PUPDR` writer"] pub type W = crate::W<PUPDR_SPEC>; #[doc = "Field `PUPDR0` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR0_R = crate::FieldReader; #[doc = "Field `PUPDR0` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR0_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR1` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR1_R = crate::FieldReader; #[doc = "Field `PUPDR1` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR1_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR2` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR2_R = crate::FieldReader; #[doc = "Field `PUPDR2` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR2_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR3` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR3_R = crate::FieldReader; #[doc = "Field `PUPDR3` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR3_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR4` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR4_R = crate::FieldReader; #[doc = "Field `PUPDR4` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR4_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR5` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR5_R = crate::FieldReader; #[doc = "Field `PUPDR5` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR5_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR6` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR6_R = crate::FieldReader; #[doc = "Field `PUPDR6` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR6_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR7` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR7_R = crate::FieldReader; #[doc = "Field `PUPDR7` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR7_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR8` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR8_R = crate::FieldReader; #[doc = "Field `PUPDR8` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR8_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR9` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR9_R = crate::FieldReader; #[doc = "Field `PUPDR9` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR9_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR10` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR10_R = crate::FieldReader; #[doc = "Field `PUPDR10` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR10_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR11` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR11_R = crate::FieldReader; #[doc = "Field `PUPDR11` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR11_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR12` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR12_R = crate::FieldReader; #[doc = "Field `PUPDR12` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR12_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR13` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR13_R = crate::FieldReader; #[doc = "Field `PUPDR13` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR13_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR14` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR14_R = crate::FieldReader; #[doc = "Field `PUPDR14` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR14_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; #[doc = "Field `PUPDR15` reader - Port x configuration bits (y = 0..15)"] pub type PUPDR15_R = crate::FieldReader; #[doc = "Field `PUPDR15` writer - Port x configuration bits (y = 0..15)"] pub type PUPDR15_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 2, O>; impl R { #[doc = "Bits 0:1 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr0(&self) -> PUPDR0_R { PUPDR0_R::new((self.bits & 3) as u8) } #[doc = "Bits 2:3 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr1(&self) -> PUPDR1_R { PUPDR1_R::new(((self.bits >> 2) & 3) as u8) } #[doc = "Bits 4:5 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr2(&self) -> PUPDR2_R { PUPDR2_R::new(((self.bits >> 4) & 3) as u8) } #[doc = "Bits 6:7 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr3(&self) -> PUPDR3_R { PUPDR3_R::new(((self.bits >> 6) & 3) as u8) } #[doc = "Bits 8:9 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr4(&self) -> PUPDR4_R { PUPDR4_R::new(((self.bits >> 8) & 3) as u8) } #[doc = "Bits 10:11 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr5(&self) -> PUPDR5_R { PUPDR5_R::new(((self.bits >> 10) & 3) as u8) } #[doc = "Bits 12:13 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr6(&self) -> PUPDR6_R { PUPDR6_R::new(((self.bits >> 12) & 3) as u8) } #[doc = "Bits 14:15 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr7(&self) -> PUPDR7_R { PUPDR7_R::new(((self.bits >> 14) & 3) as u8) } #[doc = "Bits 16:17 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr8(&self) -> PUPDR8_R { PUPDR8_R::new(((self.bits >> 16) & 3) as u8) } #[doc = "Bits 18:19 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr9(&self) -> PUPDR9_R { PUPDR9_R::new(((self.bits >> 18) & 3) as u8) } #[doc = "Bits 20:21 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr10(&self) -> PUPDR10_R { PUPDR10_R::new(((self.bits >> 20) & 3) as u8) } #[doc = "Bits 22:23 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr11(&self) -> PUPDR11_R { PUPDR11_R::new(((self.bits >> 22) & 3) as u8) } #[doc = "Bits 24:25 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr12(&self) -> PUPDR12_R { PUPDR12_R::new(((self.bits >> 24) & 3) as u8) } #[doc = "Bits 26:27 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr13(&self) -> PUPDR13_R { PUPDR13_R::new(((self.bits >> 26) & 3) as u8) } #[doc = "Bits 28:29 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr14(&self) -> PUPDR14_R { PUPDR14_R::new(((self.bits >> 28) & 3) as u8) } #[doc = "Bits 30:31 - Port x configuration bits (y = 0..15)"] #[inline(always)] pub fn pupdr15(&self) -> PUPDR15_R { PUPDR15_R::new(((self.bits >> 30) & 3) as u8) } } impl W { #[doc = "Bits 0:1 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr0(&mut self) -> PUPDR0_W<PUPDR_SPEC, 0> { PUPDR0_W::new(self) } #[doc = "Bits 2:3 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr1(&mut self) -> PUPDR1_W<PUPDR_SPEC, 2> { PUPDR1_W::new(self) } #[doc = "Bits 4:5 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr2(&mut self) -> PUPDR2_W<PUPDR_SPEC, 4> { PUPDR2_W::new(self) } #[doc = "Bits 6:7 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr3(&mut self) -> PUPDR3_W<PUPDR_SPEC, 6> { PUPDR3_W::new(self) } #[doc = "Bits 8:9 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr4(&mut self) -> PUPDR4_W<PUPDR_SPEC, 8> { PUPDR4_W::new(self) } #[doc = "Bits 10:11 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr5(&mut self) -> PUPDR5_W<PUPDR_SPEC, 10> { PUPDR5_W::new(self) } #[doc = "Bits 12:13 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr6(&mut self) -> PUPDR6_W<PUPDR_SPEC, 12> { PUPDR6_W::new(self) } #[doc = "Bits 14:15 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr7(&mut self) -> PUPDR7_W<PUPDR_SPEC, 14> { PUPDR7_W::new(self) } #[doc = "Bits 16:17 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr8(&mut self) -> PUPDR8_W<PUPDR_SPEC, 16> { PUPDR8_W::new(self) } #[doc = "Bits 18:19 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr9(&mut self) -> PUPDR9_W<PUPDR_SPEC, 18> { PUPDR9_W::new(self) } #[doc = "Bits 20:21 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr10(&mut self) -> PUPDR10_W<PUPDR_SPEC, 20> { PUPDR10_W::new(self) } #[doc = "Bits 22:23 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr11(&mut self) -> PUPDR11_W<PUPDR_SPEC, 22> { PUPDR11_W::new(self) } #[doc = "Bits 24:25 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr12(&mut self) -> PUPDR12_W<PUPDR_SPEC, 24> { PUPDR12_W::new(self) } #[doc = "Bits 26:27 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr13(&mut self) -> PUPDR13_W<PUPDR_SPEC, 26> { PUPDR13_W::new(self) } #[doc = "Bits 28:29 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr14(&mut self) -> PUPDR14_W<PUPDR_SPEC, 28> { PUPDR14_W::new(self) } #[doc = "Bits 30:31 - Port x configuration bits (y = 0..15)"] #[inline(always)] #[must_use] pub fn pupdr15(&mut self) -> PUPDR15_W<PUPDR_SPEC, 30> { PUPDR15_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 = "GPIO port pull-up/pull-down register\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`pupdr::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 [`pupdr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct PUPDR_SPEC; impl crate::RegisterSpec for PUPDR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`pupdr::R`](R) reader structure"] impl crate::Readable for PUPDR_SPEC {} #[doc = "`write(|w| ..)` method takes [`pupdr::W`](W) writer structure"] impl crate::Writable for PUPDR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets PUPDR to value 0x6400_0000"] impl crate::Resettable for PUPDR_SPEC { const RESET_VALUE: Self::Ux = 0x6400_0000; }
fn main() { let t = (12, "eggs"); let b = Box::new(t); println!("{:?} is tuple\n{:?} is boxed struct now", t, b) }
use gl::types::{GLint, GLuint}; use glm::Vec3; pub struct Vertex { pos: Vec3, } impl Vertex { pub fn new(pos: Vec3) -> Self { Self { pos } } } const NUM_BUFFERS: usize = 1; // number of variants on enum below, it should be a macro enum VertexArrayBuffer { PositionVB = 0, } pub struct Mesh { vertex_array_object: GLuint, vertex_array_buffers: [GLuint; NUM_BUFFERS], draw_count: usize, } impl Mesh { pub fn new(vertices: &[Vertex]) -> Self { let mut vertex_array_object_ptr: GLuint = 0; unsafe { gl::GenVertexArrays(1, &mut vertex_array_object_ptr); gl::BindVertexArray(vertex_array_object_ptr); } let mut vertex_array_buffers: [GLuint; NUM_BUFFERS] = unsafe { std::mem::MaybeUninit::uninit().assume_init() }; unsafe { gl::GenBuffers(NUM_BUFFERS as GLint, vertex_array_buffers.as_mut_ptr()); gl::BindBuffer( gl::ARRAY_BUFFER, vertex_array_buffers[VertexArrayBuffer::PositionVB as usize], ); gl::BufferData( gl::ARRAY_BUFFER, (vertices.len() * std::mem::size_of::<Vertex>()) as isize, vertices.as_ptr() as *const std::ffi::c_void, gl::STATIC_DRAW, ); gl::EnableVertexAttribArray(0); // 0 -> all of the data is one attribute gl::VertexAttribPointer(0, 3, gl::FLOAT, gl::FALSE, 0, std::ptr::null()); gl::BindVertexArray(0); } Self { vertex_array_object: vertex_array_object_ptr, vertex_array_buffers, draw_count: vertices.len(), } } pub fn draw(&self) { unsafe { gl::BindVertexArray(self.vertex_array_object); gl::DrawArrays(gl::TRIANGLES, 0, self.draw_count as i32); gl::BindVertexArray(0); } } } impl Drop for Mesh { fn drop(&mut self) { unsafe { gl::DeleteVertexArrays(1, &self.vertex_array_object); } } }
use super::Register; use crate::util::*; mod branch; mod condition; mod data; mod multiply; mod shifter; mod swap; pub use condition::ConditionCode; pub use shifter::{ShiftOperand, ShiftOperation, ShifterOperand}; #[derive(Copy, Clone, Eq, PartialEq, Debug)] pub enum DecodeError { InvalidShifterOperand(u16), } type Result<T> = std::result::Result<T, DecodeError>;
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 use crate::metadata::Metadata; use crate::module::pubsub::event_subscription_actor::ChainNotifyHandlerActor; use crate::module::pubsub::notify::SubscriberNotifyActor; use actix::Addr; use futures::channel::mpsc; use jsonrpc_core::Result; use jsonrpc_pubsub::typed::Subscriber; use jsonrpc_pubsub::SubscriptionId; use parking_lot::RwLock; use starcoin_bus::BusActor; use starcoin_rpc_api::types::pubsub::EventFilter; use starcoin_rpc_api::{errors, pubsub::StarcoinPubSub, types::pubsub}; use starcoin_storage::Store; use starcoin_txpool_api::TxnStatusFullEvent; use starcoin_types::filter::Filter; use std::convert::TryInto; use std::sync::{atomic, Arc}; use subscribers::Subscribers; use txn_subscription_actor::TransactionSubscriptionActor; mod event_subscription_actor; mod notify; mod subscribers; #[cfg(test)] pub mod tests; mod txn_subscription_actor; pub struct PubSubImpl { service: PubSubService, } impl PubSubImpl { pub fn new(s: PubSubService) -> Self { Self { service: s } } } impl StarcoinPubSub for PubSubImpl { type Metadata = Metadata; fn subscribe( &self, _meta: Metadata, subscriber: Subscriber<pubsub::Result>, kind: pubsub::Kind, params: Option<pubsub::Params>, ) { let error = match (kind, params) { (pubsub::Kind::NewHeads, None) => { self.service.add_new_header_subscription(subscriber); return; } (pubsub::Kind::NewHeads, _) => { errors::invalid_params("newHeads", "Expected no parameters.") } (pubsub::Kind::NewPendingTransactions, None) => { self.service.add_new_txn_subscription(subscriber); return; } (pubsub::Kind::NewPendingTransactions, _) => { errors::invalid_params("newPendingTransactions", "Expected no parameters.") } (pubsub::Kind::Events, Some(pubsub::Params::Events(filter))) => { self.service.add_event_subscription(subscriber, filter); return; } (pubsub::Kind::Events, _) => { errors::invalid_params("events", "Expected a filter object.") } // _ => errors::unimplemented(None), }; let _ = subscriber.reject(error); } fn unsubscribe(&self, _: Option<Self::Metadata>, id: SubscriptionId) -> Result<bool> { self.service.unsubscribe(id) } } type ClientNotifier = Addr<SubscriberNotifyActor<pubsub::Result>>; type TxnSubscribers = Arc<RwLock<Subscribers<ClientNotifier>>>; type EventSubscribers = Arc<RwLock<Subscribers<(ClientNotifier, Filter)>>>; type NewHeaderSubscribers = Arc<RwLock<Subscribers<ClientNotifier>>>; pub struct PubSubService { subscriber_id: Arc<atomic::AtomicU64>, spawner: actix_rt::Arbiter, transactions_subscribers: TxnSubscribers, events_subscribers: EventSubscribers, new_header_subscribers: NewHeaderSubscribers, } impl Default for PubSubService { fn default() -> Self { Self::new() } } impl PubSubService { pub fn new() -> Self { let subscriber_id = Arc::new(atomic::AtomicU64::new(0)); let transactions_subscribers = Arc::new(RwLock::new(Subscribers::new(subscriber_id.clone()))); let events_subscribers = Arc::new(RwLock::new(Subscribers::new(subscriber_id.clone()))); let new_header_subscribers = Arc::new(RwLock::new(Subscribers::new(subscriber_id.clone()))); Self { spawner: actix_rt::Arbiter::new(), subscriber_id, transactions_subscribers, events_subscribers, new_header_subscribers, } } pub fn start_chain_notify_handler(&self, bus: Addr<BusActor>, store: Arc<dyn Store>) { let actor = ChainNotifyHandlerActor::new( self.events_subscribers.clone(), self.new_header_subscribers.clone(), bus, store, ); actix::Actor::start_in_arbiter(&self.spawner, |_ctx| actor); } pub fn start_transaction_subscription_handler( &self, txn_receiver: mpsc::UnboundedReceiver<TxnStatusFullEvent>, ) { let actor = TransactionSubscriptionActor::new(self.transactions_subscribers.clone(), txn_receiver); actix::Actor::start_in_arbiter(&self.spawner, |_ctx| actor); } pub fn add_new_txn_subscription(&self, subscriber: Subscriber<pubsub::Result>) { self.transactions_subscribers .write() .add(&self.spawner, subscriber); } pub fn add_new_header_subscription(&self, subscriber: Subscriber<pubsub::Result>) { self.new_header_subscribers .write() .add(&self.spawner, subscriber); } pub fn add_event_subscription( &self, subscriber: Subscriber<pubsub::Result>, filter: EventFilter, ) { match filter.try_into() { Ok(f) => { self.events_subscribers .write() .add(&self.spawner, subscriber, f); } Err(e) => { let _ = subscriber.reject(e); } }; } pub fn unsubscribe(&self, id: SubscriptionId) -> Result<bool> { let res1 = self.events_subscribers.write().remove(&id).is_some(); let res2 = self.transactions_subscribers.write().remove(&id).is_some(); let res3 = self.new_header_subscribers.write().remove(&id).is_some(); Ok(res1 || res2 || res3) } }
use super::lexer::{tokens, Lexer}; const DEBUG: bool = false; #[derive(Debug)] pub enum Result { Ok, Error(String), } #[derive(Debug)] pub struct Parser { /// Lexer lexer: Lexer, /// Active token lookahead_token: Option<tokens::Token>, } impl Parser { pub fn new(input: String) -> Parser { Parser { lexer: Lexer::new(input), lookahead_token: None, } } pub fn peek(&mut self) -> Option<&tokens::Token> { let result = if let Some(ref token) = self.lookahead_token { Some(token) } else if let Some(token) = self.lexer.next() { self.lookahead_token = Some(token); self.lookahead_token.as_ref() } else { None }; debug_parser!("Parser peek {:?}", result); result } /// Function to shift parset. Must be called only by functions, which consume token pub fn shift(&mut self) { debug_parser!("Parser shift {:?}", self.lookahead_token); self.lookahead_token = None } }
use serde::{Serialize, Deserialize}; #[derive(Copy, Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)] pub struct Point { pub x: i32, pub y: i32, } impl Point { pub fn new(x: i32, y: i32) -> Point { Point { x, y } } pub fn nearest(x: f32, y: f32) -> Point { Point { x: x.round() as i32, y: y.round() as i32, } } pub fn origin() -> Point { Self::default() } pub fn offset_from(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y } } pub fn relative_to(self, other: Point) -> Point { Point { x: self.x - other.x, y: self.y - other.y } } pub fn normalize_components(self, area_size: Size) -> [f32; 2] { [ self.x as f32 / area_size.width as f32, self.y as f32 / area_size.height as f32, ] } } impl From<Point> for [f32; 2] { fn from(point: Point) -> [f32; 2] { [point.x as f32, point.y as f32] } } #[derive(Copy, Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)] pub struct Size { pub width: u32, pub height: u32, } impl Size { pub fn new(width: u32, height: u32) -> Size { Size { width, height } } pub fn zero() -> Size { Self::default() } pub fn aspect(&self) -> f32 { self.width as f32 / self.height as f32 } } impl From<[u32; 2]> for Size { fn from(size: [u32; 2]) -> Size { Size { width: size[0], height: size[1] } } } impl From<Size> for [f32; 2] { fn from(size: Size) -> [f32; 2] { [size.width as f32, size.height as f32] } } #[derive(Copy, Clone, Eq, PartialEq, Default, Debug)] pub struct Rect { pub position: Point, pub size: Size, } impl Rect { pub fn zero() -> Rect { Self::default() } pub fn new(position: Point, size: Size) -> Rect { Rect { position, size } } pub fn from_size(size: Size) -> Rect { Rect { position: Point::origin(), size } } pub fn top_left(&self) -> Point { self.position } pub fn top_right(&self) -> Point { Point { x: self.position.x + self.size.width as i32, y: self.position.y } } pub fn bottom_left(&self) -> Point { Point { x: self.position.x, y: self.position.y + self.size.height as i32 } } pub fn bottom_right(&self) -> Point { Point { x: self.position.x + self.size.width as i32, y: self.position.y + self.size.height as i32 } } pub fn contains(&self, point: Point) -> bool { self.position.x <= point.x && self.position.y <= point.y && self.position.x + self.size.width as i32 > point.x && self.position.y + self.size.height as i32 > point.y } pub fn inset(&self, insets: EdgeRect) -> Rect { let width = self.size.width as i32; let height = self.size.height as i32; let inset_width = insets.left + insets.right; let inset_height = insets.top + insets.bottom; Rect { position: Point { x: self.position.x + insets.left, y: self.position.y + insets.right }, size: Size { width: if inset_width >= width { 0 } else { (width - inset_width) as u32 }, height: if inset_height >= height { 0 } else { (height - inset_height) as u32 }, } } } } impl From<Rect> for [f32; 4] { fn from(rect: Rect) -> [f32; 4] { [ rect.position.x as f32, rect.position.y as f32, rect.size.width as f32, rect.size.height as f32, ] } } #[derive(Copy, Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)] pub struct EdgeRect { pub left: i32, pub top: i32, pub right: i32, pub bottom: i32, } #[derive(Copy, Clone, Eq, PartialEq, Default, Debug, Serialize, Deserialize)] pub struct Index2D { pub col: usize, pub row: usize, }
//! A crate containing my practice implementation of a variable size thread pool //! for executing functions in parallel. Spawns a specified number of worker //! threads, but will panic if any of them panic. //! //! After creating the [`ThreadPool`], give it work by passing boxed closures to //! [`schedule()`]. If your closures return a value, you can access the returned //! values through the [`results`] channel on the [`ThreadPool`]. //! //! # Examples //! //! ``` //! use cjp_threadpool::ThreadPool; //! //! let pool = ThreadPool::new_with_default_size(); //! let job = Box::new(move || 1 + 1); //! for _ in 0..24 { pool.schedule(job.clone()); } //! //! for _ in 0..24 { assert_eq!(Ok(2), pool.results.recv()); } //! ``` //! //! [`ThreadPool`]: ./struct.ThreadPool.html //! [`schedule()`]: ./struct.ThreadPool.html#method.schedule //! [`results`]: ./struct.ThreadPool.html#structfield.results #![crate_name = "cjp_threadpool"] #![crate_type = "lib"] extern crate num_cpus; use std::thread::{self, JoinHandle}; use std::sync::{Arc, Mutex, mpsc::{self, Sender, Receiver}}; type Job<T> = Box<dyn FnOnce() -> T + Send + 'static>; /// A thread pool that owns a number of worker threads and can schedule work across /// them. pub struct ThreadPool<T> { threads: Vec<Worker>, inbound_work_sender: Sender<Job<T>>, inbound_work_receiver: Arc<Mutex<Receiver<Job<T>>>>, /// The receive half of a channel on which the return values of scheduled jobs /// will be sent. pub results: Receiver<T>, } impl<T: Send + 'static> ThreadPool<T> { /// Creates a new thread pool capable of executing `num_threads` number of jobs /// concurrently. /// /// # Panics /// /// This function will panic if `num_threads` is 0. /// /// # Examples /// /// Create a new thread pool capable of executing four jobs concurrently, where /// the jobs return `()`: /// /// ``` /// use cjp_threadpool::ThreadPool; /// /// let pool = ThreadPool::<()>::new(4); /// ``` #[must_use] pub fn new(num_threads: usize) -> Self { let (inbound_work_sender, inbound_work_receiver) = mpsc::channel(); let (result_sender, results) = mpsc::channel(); let receiver = Arc::new(Mutex::new(inbound_work_receiver)); let mut pool = Self { threads: Vec::with_capacity(num_threads), inbound_work_sender, inbound_work_receiver: Arc::clone(&receiver), results, }; for _ in 0..num_threads { pool.threads.push(Worker::new(Arc::clone(&receiver), result_sender.clone())); } pool } /// Creates a new thread pool with capacity equal to the number of logical /// CPUs on the machine it's running on. /// /// # Examples /// /// Create a new thread pool capable of executing one concurrent job per logical /// CPU: /// /// ``` /// use cjp_threadpool::ThreadPool; /// /// let pool = ThreadPool::<()>::new_with_default_size(); /// ``` #[must_use] pub fn new_with_default_size() -> Self { Self::new(num_cpus::get()) } /// Queues the function `job` for execution on a thread in the pool. /// /// # Examples /// /// Execute four jobs on a thread pool that can run two jobs concurrently: /// /// ``` /// use cjp_threadpool::ThreadPool; /// /// let pool = ThreadPool::new(2); /// let job = Box::new(move || 1 + 1); /// for _ in 0..4 { pool.schedule(job.clone()); } /// pool.join(); /// ``` pub fn schedule(&self, job: Job<T>) { self.inbound_work_sender.send(job).unwrap(); } /// Block the current thread until all jobs in the pool have been executed. pub fn join(self) { drop(self.inbound_work_sender); // Join all worker threads. for worker in self.threads { worker.thread.join().unwrap(); } } /// Like [`join()`], but drops any pending jobs that aren't already mid-execution. /// /// [`join()`]: #method.join pub fn terminate(self) { drop(self.inbound_work_sender); { // Consume all the remaining scheduled work. let receiver = self.inbound_work_receiver.lock().unwrap(); while let Ok(job) = receiver.recv() { drop(job); } } // Join all worker threads. for worker in self.threads { worker.thread.join().unwrap(); } } } struct Worker { thread: JoinHandle<()>, } impl Worker { fn new<T: Send + 'static>(receiver: Arc<Mutex<Receiver<Job<T>>>>, result_sender: Sender<T>) -> Self { Self { thread: thread::spawn(move || { #[allow(clippy::while_let_loop)] loop { let job = match receiver.lock().unwrap().recv() { Ok(job) => job, Err(_) => break, }; let result = job(); result_sender.send(result).unwrap(); } }) } } } #[cfg(test)] mod tests { use super::*; use std::time::{Duration, Instant}; use std::sync::{Arc, Mutex}; #[test] fn two_sequential_jobs() { let pool = ThreadPool::new(1); let job = Box::new(move || 1 + 1); pool.schedule(job.clone()); pool.schedule(job); assert_eq!(Ok(2), pool.results.recv()); assert_eq!(Ok(2), pool.results.recv()); assert!(pool.results.try_recv().is_err()); pool.join(); } #[test] fn highly_parallel() { let pool = ThreadPool::new(8); let job = Box::new(move || { thread::sleep(Duration::from_millis(100)); 1 + 1 }); let now = Instant::now(); for _ in 0..24 { pool.schedule(job.clone()); } for _ in 0..24 { assert_eq!(Ok(2), pool.results.recv()); } assert!(now.elapsed().as_millis() < 350); pool.join(); } #[test] fn terminate_early() { let pool = ThreadPool::new(8); let value = Arc::new(Mutex::new(0)); for _ in 0..24 { let value_clone = Arc::clone(&value); let job = Box::new(move || { thread::sleep(Duration::from_millis(100)); let mut data = value_clone.lock().unwrap(); *data += 1; *data }); pool.schedule(job); } thread::sleep(Duration::from_millis(50)); pool.terminate(); thread::sleep(Duration::from_secs(1)); let data = value.lock().unwrap(); assert_eq!(*data, 8); } }
//! [`Router`](crate::Router) is a lightweight high performance HTTP request router. //! //! This router supports variables in the routing pattern and matches against //! the request method. It also scales better. //! //! The router is optimized for high performance and a small memory footprint. //! It scales well even with very long paths and a large number of routes. //! A compressing dynamic trie (radix tree) structure is used for efficient matching. //! //! With the `hyper-server` feature enabled, the `Router` can be used as a router for a hyper server: //! //! ```rust,no_run //! use httprouter::{Router, Params, handler_fn}; //! use std::convert::Infallible; //! use hyper::{Request, Response, Body, Error}; //! //! async fn index(_: Request<Body>) -> Result<Response<Body>, Error> { //! Ok(Response::new("Hello, World!".into())) //! } //! //! async fn hello(req: Request<Body>) -> Result<Response<Body>, Error> { //! let params = req.extensions().get::<Params>().unwrap(); //! Ok(Response::new(format!("Hello, {}", params.get("user").unwrap()).into())) //! } //! //! #[tokio::main] //! async fn main() { //! let router = Router::default() //! .get("/", handler_fn(index)) //! .get("/hello/:user", handler_fn(hello)); //! //! hyper::Server::bind(&([127, 0, 0, 1], 3000).into()) //! .serve(router.into_service()) //! .await; //! } //!``` //! //! The registered path, against which the router matches incoming requests, can //! contain two types of parameters: //! ```ignore //! Syntax Type //! :name named parameter //! *name catch-all parameter //! ``` //! //! Named parameters are dynamic path segments. They match anything until the //! next '/' or the path end: //! ```ignore //! Path: /blog/:category/:post //! ``` //! //! Requests: //! ```ignore //! /blog/rust/request-routers match: category="rust", post="request-routers" //! /blog/rust/request-routers/ no match, but the router would redirect //! /blog/rust/ no match //! /blog/rust/request-routers/comments no match //! ``` //! //! Catch-all parameters match anything until the path end, including the //! directory index (the '/' before the catch-all). Since they match anything //! until the end, catch-all parameters must always be the final path element. //! Path: /files/*filepath //! //! Requests: //! ```ignore //! /files/ match: filepath="/" //! /files/LICENSE match: filepath="/LICENSE" //! /files/templates/article.html match: filepath="/templates/article.html" //! /files no match, but the router would redirect //! ``` //! The value of parameters is saved as a `Vec` of the `Param` struct, consisting //! each of a key and a value. //! ```ignore //! # use httprouter::tree::Params; //! # let params = Params::default(); //! //! let user = params.get("user") // defined by :user or *user //! //! // alternatively, you can iterate through every matched parameter //! for (k, v) in params.iter() { //! println!("{}: {}", k, v") //! } //! ``` use crate::path::clean; use std::collections::HashMap; use std::error::Error as StdError; use std::fmt; use std::future::Future; use std::pin::Pin; use std::sync::Arc; use std::task::{Context, Poll}; use futures_util::{future, ready}; use hyper::service::Service; use hyper::{header, Body, Method, Request, Response, StatusCode}; use matchit::Node; #[derive(Default)] pub struct Params { vec: Vec<(String, String)>, } impl Params { /// Returns the value of the first parameter registered matched for the given key. pub fn get(&self, key: impl AsRef<str>) -> Option<&str> { self.vec .iter() .find(|(k, _)| k == key.as_ref()) .map(|(_, v)| v.as_str()) } /// Returns an iterator over the parameters in the list. pub fn iter(&self) -> std::slice::Iter<'_, (String, String)> { self.vec.iter() } /// Returns a mutable iterator over the parameters in the list. pub fn iter_mut(&mut self) -> std::slice::IterMut<'_, (String, String)> { self.vec.iter_mut() } /// Returns an owned iterator over the parameters in the list. pub fn into_iter(self) -> std::vec::IntoIter<(String, String)> { self.vec.into_iter() } } pub trait HandlerService<F, E>: Service<Request<Body>, Response = Response<Body>, Error = E, Future = F> + Send + Sync + Clone + 'static { } impl<S, F, E> HandlerService<F, E> for S where S: Service<Request<Body>, Response = Response<Body>, Error = E, Future = F> + Send + Sync + Clone + 'static { } pub trait HandlerFuture<E>: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static { } impl<F, E> HandlerFuture<E> for F where F: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static { } pub trait HandlerError: StdError + Send + Sync + 'static {} impl<E> HandlerError for E where E: StdError + Send + Sync + 'static {} #[derive(Clone)] struct HandlerServiceImpl<S> { service: S, } impl<S> HandlerServiceImpl<S> { fn new(service: S) -> Self { Self { service } } } impl<S, R> Service<R> for HandlerServiceImpl<S> where S: Service<R>, S::Future: Send + Sync + 'static, S::Error: HandlerError, { type Future = Pin<Box<dyn Future<Output = Result<S::Response, BoxError>> + Send + Sync>>; type Error = BoxError; type Response = S::Response; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, req: R) -> Self::Future { use futures_util::future::TryFutureExt; Box::pin(self.service.call(req).map_err(|e| BoxError(Box::new(e)))) } } pub fn handler_fn<F, O, E>(f: F) -> HandlerFnService<F> where F: FnMut(Request<Body>) -> O + Send + Sync + Clone + 'static, O: HandlerFuture<E>, E: HandlerError, { fn assert_handler<H, O, E>(h: H) -> H where H: HandlerService<O, E>, O: HandlerFuture<E>, E: HandlerError, { h } assert_handler(HandlerFnService { f }) } #[doc(hidden)] #[derive(Clone)] pub struct HandlerFnService<F> { f: F, } impl<F, O, E> Service<Request<Body>> for HandlerFnService<F> where F: FnMut(Request<Body>) -> O, O: Future<Output = Result<Response<Body>, E>> + Send + Sync + 'static, E: HandlerError, { type Response = Response<Body>; type Error = E; type Future = O; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, req: Request<Body>) -> Self::Future { (self.f)(req) } } trait StoredService: Service< Request<Body>, Error = BoxError, Response = Response<Body>, Future = Pin<Box<dyn Future<Output = Result<Response<Body>, BoxError>> + Send + Sync>>, > + Send + Sync + 'static { fn box_clone(&self) -> Box<dyn StoredService>; } impl<S> StoredService for S where S: Service< Request<Body>, Error = BoxError, Response = Response<Body>, Future = Pin<Box<dyn Future<Output = Result<Response<Body>, BoxError>> + Send + Sync>>, > + Send + Sync + Clone + 'static, { fn box_clone(&self) -> Box<dyn StoredService> { Box::new(self.clone()) } } impl Clone for Box<dyn StoredService> { fn clone(&self) -> Self { self.box_clone() } } pub struct Router { trees: HashMap<Method, Node<Box<dyn StoredService>>>, redirect_trailing_slash: bool, redirect_fixed_path: bool, handle_method_not_allowed: bool, handle_options: bool, global_options: Option<Box<dyn StoredService>>, not_found: Option<Box<dyn StoredService>>, method_not_allowed: Option<Box<dyn StoredService>>, } impl Router { /// Register a handler for the given path and method. /// ```rust /// use httprouter::{Router, handler_fn}; /// use hyper::{Response, Body, Method}; /// use std::convert::Infallible; /// /// let router = Router::default() /// .handle("/teapot", Method::GET, handler_fn(|_| async { /// Ok::<_, Infallible>(Response::new(Body::from("I am a teapot!"))) /// })); /// ``` pub fn handle<H, F, E>(mut self, path: impl Into<String>, method: Method, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { let path = path.into(); if !path.starts_with('/') { panic!("expect path beginning with '/', found: '{}'", path); } self.trees .entry(method) .or_insert_with(Node::default) .insert(path, Box::new(HandlerServiceImpl::new(handler))) .unwrap(); self } /// TODO pub fn serve_files() { unimplemented!() } /// Register a handler for `GET` requests pub fn get<H, F, E>(self, path: impl Into<String>, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.handle(path, Method::GET, handler) } /// Register a handler for `HEAD` requests pub fn head<H, F, E>(self, path: impl Into<String>, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.handle(path, Method::HEAD, handler) } /// Register a handler for `OPTIONS` requests pub fn options<H, F, E>(self, path: impl Into<String>, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.handle(path, Method::OPTIONS, handler) } /// Register a handler for `POST` requests pub fn post<H, F, E>(self, path: impl Into<String>, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.handle(path, Method::POST, handler) } /// Register a handler for `PUT` requests pub fn put<H, F, E>(self, path: impl Into<String>, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.handle(path, Method::PUT, handler) } /// Register a handler for `PATCH` requests pub fn patch<H, F, E>(self, path: impl Into<String>, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.handle(path, Method::PATCH, handler) } /// Register a handler for `DELETE` requests pub fn delete<H, F, E>(self, path: impl Into<String>, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.handle(path, Method::DELETE, handler) } /// Enables automatic redirection if the current route can't be matched but a /// handler for the path with (without) the trailing slash exists. /// For example if `/foo/` is requested but a route only exists for `/foo`, the /// client is redirected to `/foo` with HTTP status code 301 for `GET` requests /// and 307 for all other request methods. pub fn redirect_trailing_slash(mut self) -> Self { self.redirect_trailing_slash = true; self } /// If enabled, the router tries to fix the current request path, if no /// handle is registered for it. /// First superfluous path elements like `../` or `//` are removed. /// Afterwards the router does a case-insensitive lookup of the cleaned path. /// If a handle can be found for this route, the router makes a redirection /// to the corrected path with status code 301 for `GET` requests and 307 for /// all other request methods. /// For example `/FOO` and `/..//Foo` could be redirected to `/foo`. /// `redirect_trailing_slash` is independent of this option. pub fn redirect_fixed_path(mut self) -> Self { self.redirect_fixed_path = true; self } /// If enabled, the router checks if another method is allowed for the /// current route, if the current request can not be routed. /// If this is the case, the request is answered with `MethodNotAllowed` /// and HTTP status code 405. /// If no other Method is allowed, the request is delegated to the `NotFound` /// handler. pub fn handle_method_not_allowed(mut self) -> Self { self.handle_method_not_allowed = true; self } /// If enabled, the router automatically replies to `OPTIONS` requests. /// Custom `OPTIONS` handlers take priority over automatic replies. pub fn handle_options(mut self) -> Self { self.handle_options = true; self } /// An optional handler that is called on automatic `OPTIONS` requests. /// The handler is only called if `handle_options` is true and no `OPTIONS` /// handler for the specific path was set. /// The `Allowed` header is set before calling the handler. pub fn global_options<H, F, E>(mut self, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.global_options = Some(Box::new(HandlerServiceImpl::new(handler))); self } /// Configurable handler which is called when no matching route is /// found. pub fn not_found<H, F, E>(mut self, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.not_found = Some(Box::new(HandlerServiceImpl::new(handler))); self } /// A configurable handler which is called when a request /// cannot be routed and `handle_method_not_allowed` is true. /// The `Allow` header with allowed request methods is set before the handler /// is called. pub fn method_not_allowed<H, F, E>(mut self, handler: H) -> Self where H: HandlerService<F, E>, F: HandlerFuture<E>, E: HandlerError, { self.method_not_allowed = Some(Box::new(HandlerServiceImpl::new(handler))); self } /// Returns a list of the allowed methods for a specific path /// ```rust /// use httprouter::{Router, handler_fn}; /// use hyper::{Response, Body, Method}; /// use std::convert::Infallible; /// /// let router = Router::default() /// .get("/home", handler_fn(|_| async { /// Ok::<_, Infallible>(Response::new(Body::from("Welcome!"))) /// })) /// .post("/home", handler_fn(|_| async { /// Ok::<_, Infallible>(Response::new(Body::from("{{ message: \"Welcome!\" }}"))) /// })); /// /// let allowed = router.allowed("/home"); /// assert!(allowed.contains(&"GET")); /// assert!(allowed.contains(&"POST")); /// assert!(allowed.contains(&"OPTIONS")); /// # assert_eq!(allowed.len(), 3); /// ``` pub fn allowed(&self, path: impl Into<String>) -> Vec<&str> { let path = path.into(); let mut allowed = match path.as_ref() { "*" => { let mut allowed = Vec::with_capacity(self.trees.len()); for method in self .trees .keys() .filter(|&method| method != Method::OPTIONS) { allowed.push(method.as_ref()); } allowed } _ => self .trees .keys() .filter(|&method| method != Method::OPTIONS) .filter(|&method| { self.trees .get(method) .map(|node| node.at(&path).is_ok()) .unwrap_or(false) }) .map(AsRef::as_ref) .collect::<Vec<_>>(), }; if !allowed.is_empty() { allowed.push(Method::OPTIONS.as_ref()) } allowed } } impl Default for Router { fn default() -> Self { Self { trees: HashMap::new(), redirect_trailing_slash: true, redirect_fixed_path: true, handle_method_not_allowed: true, handle_options: true, global_options: None, method_not_allowed: None, not_found: Some(Box::new(HandlerServiceImpl::new(handler_fn(|_| async { Ok::<_, hyper::Error>(Response::builder().status(400).body(Body::empty()).unwrap()) })))), } } } #[doc(hidden)] pub struct MakeRouterService(RouterService); impl<T> Service<T> for MakeRouterService { type Response = RouterService; type Error = hyper::Error; type Future = future::Ready<Result<Self::Response, Self::Error>>; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, _: T) -> Self::Future { let service = self.0.clone(); future::ok(service) } } #[doc(hidden)] #[derive(Clone)] pub struct RouterService(Arc<Router>); impl RouterService { fn new(router: Router) -> Self { RouterService(Arc::new(router)) } } impl Service<Request<Body>> for RouterService { type Response = Response<Body>; type Error = BoxError; type Future = ResponseFut; fn poll_ready(&mut self, _: &mut Context<'_>) -> Poll<Result<(), Self::Error>> { Poll::Ready(Ok(())) } fn call(&mut self, req: Request<Body>) -> Self::Future { self.0.clone().serve(req) } } impl Router { /// Converts the `Router` into a `Service` which you can serve directly with `Hyper`. /// If you have an existing `Service` that you want to incorporate a `Router` into, see /// [`Router::serve`](crate::Router::serve). /// ```rust,no_run /// # use httprouter::Router; /// # use std::convert::Infallible; /// # async fn run() -> Result<(), Box<dyn std::error::Error>> { /// // Our router... /// let router = Router::default(); /// /// // Convert it into a service... /// let service = router.into_service(); /// /// // Serve with hyper /// hyper::Server::bind(&([127, 0, 0, 1], 3030).into()) /// .serve(service) /// .await?; /// # Ok(()) /// # } /// ``` pub fn into_service(self) -> MakeRouterService { MakeRouterService(RouterService::new(self)) } /// An asynchronous function from a `Request` to a `Response`. You will generally not need to use /// this function directly, and instead use /// [`Router::into_service`](crate::Router::into_service). However, it may be useful when /// incorporating the router into a larger service. /// ```rust,no_run /// # use httprouter::Router; /// # use hyper::service::{make_service_fn, service_fn}; /// # use hyper::{Request, Body, Server}; /// # use std::convert::Infallible; /// # use std::sync::Arc; /// /// # async fn run() { /// let router = Arc::new(Router::default()); /// /// let make_svc = make_service_fn(move |_| { /// let router = router.clone(); /// async move { /// Ok::<_, Infallible>(service_fn(move |req: Request<Body>| { /// let router = router.clone(); /// async move { router.serve(req).await } /// })) /// } /// }); /// /// let server = Server::bind(&([127, 0, 0, 1], 3000).into()) /// .serve(make_svc) /// .await; /// # } /// ``` pub fn serve(&self, mut req: Request<Body>) -> ResponseFut { let root = self.trees.get(req.method()); let path = req.uri().path(); if let Some(root) = root { match root.at(path) { Ok(lookup) => { let mut value = lookup.value.clone(); let vec = lookup .params .iter() .map(|(key, value)| (key.to_owned(), value.to_owned())) .collect(); req.extensions_mut().insert(Params { vec }); return ResponseFutKind::Boxed(value.call(req)).into(); } Err(err) => { if req.method() != Method::CONNECT && path != "/" { let code = match *req.method() { // Moved Permanently, request with GET method Method::GET => StatusCode::MOVED_PERMANENTLY, // Permanent Redirect, request with same method _ => StatusCode::PERMANENT_REDIRECT, }; if err.tsr() && self.redirect_trailing_slash { let path = if path.len() > 1 && path.ends_with('/') { path[..path.len() - 1].to_owned() } else { [path, "/"].join("") }; return ResponseFutKind::Redirect(path, code).into(); } if self.redirect_fixed_path { if let Some(fixed_path) = root.path_ignore_case(clean(path), self.redirect_trailing_slash) { return ResponseFutKind::Redirect(fixed_path, code).into(); } } } } } } if req.method() == Method::OPTIONS && self.handle_options { let allow = self.allowed(path); if !allow.is_empty() { return match self.global_options { Some(ref handler) => ResponseFutKind::Boxed(handler.clone().call(req)).into(), None => ResponseFutKind::Options(allow.join(", ")).into(), }; } } else if self.handle_method_not_allowed { let allow = self.allowed(path); if !allow.is_empty() { return match self.method_not_allowed { Some(ref handler) => ResponseFutKind::Boxed(handler.clone().call(req)).into(), None => ResponseFutKind::MethodNotAllowed(allow.join(", ")).into(), }; } } match self.not_found { Some(ref handler) => ResponseFutKind::Boxed(handler.clone().call(req)).into(), None => ResponseFutKind::NotFound.into(), } } } pub struct ResponseFut { kind: ResponseFutKind, } impl From<ResponseFutKind> for ResponseFut { fn from(kind: ResponseFutKind) -> Self { Self { kind } } } enum ResponseFutKind { Boxed(Pin<Box<dyn Future<Output = Result<Response<Body>, BoxError>> + Send + Sync>>), Redirect(String, StatusCode), MethodNotAllowed(String), Options(String), NotFound, } impl Future for ResponseFut { type Output = Result<Response<Body>, BoxError>; fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> { let ready = match self.kind { ResponseFutKind::Boxed(ref mut fut) => ready!(fut.as_mut().poll(cx)), ResponseFutKind::Redirect(ref path, code) => Ok(Response::builder() .header(header::LOCATION, path.as_str()) .status(code) .body(Body::empty()) .unwrap()), ResponseFutKind::NotFound => Ok(Response::builder() .status(StatusCode::NOT_FOUND) .body(Body::empty()) .unwrap()), ResponseFutKind::Options(ref allowed) => Ok(Response::builder() .header(header::ALLOW, allowed) .body(Body::empty()) .unwrap()), ResponseFutKind::MethodNotAllowed(ref allowed) => Ok(Response::builder() .header(header::ALLOW, allowed) .status(StatusCode::METHOD_NOT_ALLOWED) .body(Body::empty()) .unwrap()), }; Poll::Ready(ready) } } pub struct BoxError(Box<dyn StdError + Send + Sync>); impl fmt::Display for BoxError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Display::fmt(&self.0, f) } } impl fmt::Debug for BoxError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> std::fmt::Result { std::fmt::Debug::fmt(&self.0, f) } } impl StdError for BoxError { fn source(&self) -> Option<&(dyn StdError + 'static)> { Some(&*self.0) } }
// Copyright (C) 2019-2021 Parity Technologies (UK) Ltd. // Copyright (C) 2021 Subspace Labs, Inc. // 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. //! Common traits and types that are useful for describing offences for usage in environments //! that use subspace consensus. //! //! ## Comparison with [sp_staking::offence] //! //! Unlike [sp_staking::offence] that handles both the offline and equivocation offences, there is //! only equivocation attack in subspace as it's a permissionless consensus based on PoC holding to //! Nakamoto's vision and does not have a known validator set for the block production. //! //! [sp_staking::offence]: https://docs.substrate.io/rustdocs/latest/sp_staking/offence/index.html use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_std::vec::Vec; /// The kind of an offence, is a byte string representing some kind identifier /// e.g. `b"sub:equivocation"` pub type Kind = [u8; 16]; /// A trait implemented by an offence report. /// /// This trait assumes that the offence is legitimate and was validated already. /// /// Examples of offences include: a BABE equivocation or a GRANDPA unjustified vote. pub trait Offence<Offender> { /// Identifier which is unique for this kind of an offence. const ID: Kind; /// A type that represents a point in time on an abstract timescale. /// /// See `Offence::time_slot` for details. The only requirement is that such timescale could be /// represented by a single `u128` value. type TimeSlot: Clone + codec::Codec + Ord; /// The list of all offenders involved in this incident. /// /// The list has no duplicates, so it is rather a set. fn offenders(&self) -> Vec<Offender>; /// A point in time when this offence happened. /// /// This is used for looking up offences that happened at the "same time". /// /// The timescale is abstract and doesn't have to be the same across different implementations /// of this trait. The value doesn't represent absolute timescale though since it is interpreted /// along with the `session_index`. Two offences are considered to happen at the same time if /// `time_slot` is the same. fn time_slot(&self) -> Self::TimeSlot; } /// Errors that may happen on offence reports. #[derive(Debug, Eq, PartialEq)] pub enum OffenceError { /// The report has already been submitted. DuplicateReport, /// Other error has happened. Other(u8), } /// A trait for decoupling offence reporters from the actual handling of offence reports. pub trait ReportOffence<Offender, O: Offence<Offender>> { /// Report an `offence` and reward given `reporters`. fn report_offence(offence: O) -> Result<(), OffenceError>; /// Returns true iff all of the given offenders have been previously reported /// at the given time slot. This function is useful to prevent the sending of /// duplicate offence reports. fn is_known_offence(offenders: &[Offender], time_slot: &O::TimeSlot) -> bool; } impl<Offender, O: Offence<Offender>> ReportOffence<Offender, O> for () { fn report_offence(_offence: O) -> Result<(), OffenceError> { Ok(()) } fn is_known_offence(_offenders: &[Offender], _time_slot: &O::TimeSlot) -> bool { true } } /// A trait to take action on an offence. /// /// Used to decouple the module that handles offences and /// the one that should punish for those offences. pub trait OnOffenceHandler<Offender> { /// A handler for an offence of a particular kind. /// /// Note that this contains a list of all previous offenders /// as well. The implementer should cater for a case, where /// the same farmers were reported for the same offence /// in the past (see `OffenceCount`). fn on_offence(offenders: &[OffenceDetails<Offender>]); } impl<Offender> OnOffenceHandler<Offender> for () { fn on_offence(_offenders: &[OffenceDetails<Offender>]) {} } /// A details about an offending authority for a particular kind of offence. #[derive(Debug, Clone, PartialEq, Eq, Encode, Decode, TypeInfo)] pub struct OffenceDetails<Offender> { /// The offending authority id pub offender: Offender, }
use std::fs; use crate::prelude::*; use crate::{ git::GitClient, poc::{Metadata, PeerMetadata, PocMap, TargetMetadata}, }; use anyhow::bail; use askama::Template; use duct::cmd; use semver::Version; use structopt::StructOpt; use tempdir::TempDir; use toml::value::Datetime; #[derive(Debug, StructOpt)] pub enum GenerateArgs { #[structopt(about = "Generates templates for bug reporting to the crate repository")] Issue { #[structopt(parse(try_from_str), help = "PoC ID (4 digits)")] poc_id: PocId, }, #[structopt(about = "Generates templates for requesting a RustSec advisory")] Rustsec { #[structopt(parse(try_from_str), help = "PoC ID (4 digits)")] poc_id: PocId, }, #[structopt(about = "Generates templates for direct bug reporting to RustSec advisory-db")] RustsecDirect { #[structopt(parse(try_from_str), help = "PoC ID (4 digits)")] poc_id: PocId, }, } #[derive(Debug)] struct IssueTemplateData { krate: String, version: Version, peer_dependencies: Vec<PeerMetadata>, os_version: String, rustc_version: String, cargo_flags: Vec<String>, poc_code: String, poc_output: String, } #[derive(Template)] #[template(path = "generate/issue.md", escape = "none")] struct IssueTemplate { data: IssueTemplateData, } #[derive(Template)] #[template(path = "generate/rustsec-direct-issue.md", escape = "none")] struct RustsecDirectIssueTemplate { data: IssueTemplateData, } #[derive(Template)] #[template(path = "generate/rustsec-issue.md", escape = "none")] struct RustsecIssueTemplate { krate: String, original_issue_title: String, original_issue_url: String, } #[derive(Template)] #[template(path = "generate/advisory.md", escape = "none")] struct AdvisoryTemplate { krate: String, original_issue_title: String, original_issue_url: Option<String>, original_issue_date: Datetime, } fn issue_data_from_id(poc_map: &PocMap, poc_id: PocId) -> Result<IssueTemplateData> { println!("Generating the issue template from PoC..."); let temp_dir = TempDir::new("rudra-poc").context("Failed to create a temp directory")?; poc_map.prepare_poc_workspace(poc_id, temp_dir.path())?; let (metadata, poc_code) = poc_map.read_metadata_and_code(poc_id)?; let Metadata { target: TargetMetadata { krate, version, peer_dependencies, }, test: mut test_metadata, report: _, bugs: _, } = metadata; let cargo_flags = test_metadata.cargo_flags.clone(); let os_version = cmd!("lsb_release", "-sd") .read() .context("Failed to read OS version from `lsb_release` command")?; let rustc_version = util::cmd_remove_cargo_envs(cmd!("rustc", "--version")) .dir(temp_dir.path()) .read() .context("Failed to read rustc version")?; let poc_build_command = util::cargo_command("build", &test_metadata, temp_dir.path()); poc_build_command.run()?; test_metadata.cargo_flags.insert(0, String::from("--quiet")); let poc_run_command = util::cargo_command("run", &test_metadata, temp_dir.path()) .stderr_to_stdout() .stdout_capture() .unchecked(); let poc_run_output = poc_run_command.run()?; let poc_output = format!( "{}\n{}", String::from_utf8_lossy(&poc_run_output.stdout), util::exit_status_string(&poc_run_output.status) ); Ok(IssueTemplateData { krate, version, peer_dependencies, os_version, rustc_version, cargo_flags, poc_code, poc_output, }) } pub fn cmd_generate(args: GenerateArgs) -> Result<()> { if !promptly::prompt( "This command will overwrite `issue_report.md` and `advisory.md` in the project directory. Is it okay?", )? { println!("No files were generated"); return Ok(()) } static WARNING_ISSUE_EXISTS: &str = "Warning: This PoC was already reported to the crate repository"; static WARNING_RUSTSEC_EXISTS: &str = "Warning: This PoC was already reported to RustSec advisory DB"; let (issue_report_content, mut advisory_content) = match args { GenerateArgs::Issue { poc_id } => { let poc_map = PocMap::new()?; let metadata = poc_map.read_metadata(poc_id)?; if metadata.report.issue_url.is_some() { println!("{}", WARNING_ISSUE_EXISTS); } let issue_data = issue_data_from_id(&poc_map, poc_id)?; ( IssueTemplate { data: issue_data }.render()?, String::from("Issue report does not use `advisory.md`."), ) } GenerateArgs::Rustsec { poc_id } => { let poc_map = PocMap::new()?; let metadata = poc_map.read_metadata(poc_id)?; match (metadata.report.issue_url, metadata.report.issue_date) { (None, _) => bail!( "Issue URL not found in PoC {}. \ Create an issue report first with `rust-poc generate issue <PoC ID>`, \ or use `rust-poc generate rustsec-direct <PoC ID>` \ if there is no issue tracker for the crate.", poc_id, ), (Some(_), None) => bail!( "Issue date was not found in PoC {}. \ Please fill in the issue_date field and try again.", poc_id ), (Some(issue_url), Some(issue_date)) => { if metadata.report.rustsec_url.is_some() { println!("{}", WARNING_RUSTSEC_EXISTS); } let git_client = GitClient::new_with_config_file()?; let issue_status = git_client.issue_status(&issue_url)?; let issue_title = issue_status .as_ref() .map(|issue| issue.title()) .unwrap_or("(( Title of the original issue ))") .to_owned(); let issue_report_content = RustsecIssueTemplate { krate: metadata.target.krate.clone(), original_issue_title: issue_title.clone(), original_issue_url: issue_url.clone(), } .render()?; let advisory_content = AdvisoryTemplate { krate: metadata.target.krate, original_issue_title: issue_title, original_issue_url: Some(issue_url), original_issue_date: issue_date, } .render()?; (issue_report_content, advisory_content) } } } GenerateArgs::RustsecDirect { poc_id } => { let poc_map = PocMap::new()?; let metadata = poc_map.read_metadata(poc_id)?; if metadata.report.issue_url.is_some() { println!("{}", WARNING_ISSUE_EXISTS); } else if metadata.report.rustsec_url.is_some() { println!("{}", WARNING_RUSTSEC_EXISTS); } let issue_data = issue_data_from_id(&poc_map, poc_id)?; let issue_report_content = RustsecDirectIssueTemplate { data: issue_data }.render()?; let advisory_content = AdvisoryTemplate { krate: metadata.target.krate, original_issue_title: String::from("((Issue Title))"), original_issue_url: None, original_issue_date: util::today_toml_date(), } .render()?; (issue_report_content, advisory_content) } }; advisory_content.push('\n'); fs::write(PROJECT_PATH.join("issue_report.md"), issue_report_content) .context("Failed to write to `issue_report.md`")?; fs::write(PROJECT_PATH.join("advisory.md"), advisory_content) .context("Failed to write to `advisory.md`")?; println!("Generated `issue_report.md` and `advisory.md`"); Ok(()) }
use dioxus::prelude::*; pub(crate) fn home(cx: Scope) -> Element { cx.render(rsx! ( h1 { "Home" } p { "These are all the strange things made with Dioxus." } )) }
use rusqlite::Connection; use bincode::SizeLimit; use bincode::rustc_serialize::{encode, decode}; use rustc_serialize::{Encodable}; #[derive(RustcEncodable, RustcDecodable, PartialEq, Debug, Clone)] pub struct Log { pub hash: String, // Log Hash pub state: String, // Hash of the state pub account: String, // Origin account address pub nonce: i64, // Nonce of log pub max_fuel: i64, // Maximum fuel to use pub code: String, // Code of Log pub signature: Vec<u8>, // Modify with Electrum style signatures } // Retreives an log. // Input hash Hash of log to retrieve. // Input conn Database connection. // Output log Retrieved log struct. pub fn get_log (hash : &str, conn: &Connection) -> Log{ let maybe_stmt = conn.prepare("SELECT * FROM log WHERE hash = $1"); let mut stmt = match maybe_stmt{ Ok(stmt) => stmt, Err(err) => panic!("Error preparing statement: {:?}", err) }; let i: String = hash.to_string(); let mut rows = stmt.query(&[&i]).unwrap(); let row = rows.next().unwrap().unwrap(); Log { hash : row.get(0), state : row.get(1), account : row.get(2), nonce : row.get(3), max_fuel : row.get(4), code : row.get(5), signature : row.get(6), } } // Saves log struct // Input l Log struct to save. // Input conn Database connection. pub fn save_log (save_l : &Log, conn: &Connection){ let l = save_l.clone(); conn.execute("INSERT INTO log \ (hash, state, account, nonce, maximum_fuel, code, signature) \ VALUES ($1, $2, $3, $4, $5, $6, $7)", &[&l.hash, &l.state, &l.account, &l.nonce, &l.max_fuel, &l.code, &l.signature]).unwrap(); } // Drops specified log // Input hash Hash of log to retrieve. // Input conn Database connection. pub fn remove_log (hash : &str, conn: &Connection){ conn.execute("DELETE FROM log WHERE hash = $1", &[&(hash.to_string())]).unwrap(); } // Creates an log table. // Input conn Database connection. pub fn create_log_table(conn: &Connection){ conn.execute("CREATE TABLE IF NOT EXISTS log ( hash text, state text, account text, nonce bigint, max_fuel bigint, code text, signature bytea )", &[]).unwrap(); } // Drops an account table. // Input conn Database connection. pub fn drop_log_table(conn: &Connection){ conn.execute("DROP TABLE IF EXISTS log", &[]).unwrap(); } // Converts log struct to byte vector. // Input l Log struct to convert. // Output Vec<u8> Converted byte vector. pub fn log_to_vec(l: &Log)-> Vec<u8>{ encode(l, SizeLimit::Infinite).unwrap() } // Converts byte vector to account log. // Input raw_l Byte vector to convert. // Output log Converted log. pub fn vec_to_log(raw_l: &Vec<u8>) -> Log{ decode(&raw_l[..]).unwrap() }
use bevy::prelude::*; pub struct CreditsEvent {} pub struct CreditsDelay(pub Timer); pub fn setup_credits( mut commands: Commands, mut windows: ResMut<Windows>, asset_server: Res<AssetServer>, ) { commands.spawn_bundle(UiCameraBundle::default()); commands.insert_resource(ClearColor(Color::hex(crate::COLOR_BLACK).unwrap())); let window = windows.get_primary_mut().unwrap(); let width = window.width(); let height = window.height(); commands .spawn_bundle(TextBundle { style: Style { align_self: AlignSelf::FlexEnd, position_type: PositionType::Absolute, position: Rect { top: Val::Px(height * 0.35), left: Val::Px(width * 0.25), ..Default::default() }, max_size: Size { width: Val::Px(width / 2.0), height: Val::Undefined, ..Default::default() }, ..Default::default() }, // Use the `Text::with_section` constructor text: Text::with_section( format!(" "), TextStyle { font: asset_server.load("fonts/FiraSans-Bold.ttf"), font_size: 60.0, color: Color::WHITE, }, TextAlignment { horizontal: HorizontalAlign::Center, vertical: VerticalAlign::Center, }, ), ..Default::default() }) .insert(EndCredits(60.0)); } pub struct EndCredits(f32); pub fn update_credits( mut commands: Commands, mut end_credits: Query<(Entity, &mut EndCredits, &mut Style)>, time: Res<Time>, mut state: ResMut<State<crate::AppState>>, mut windows: ResMut<Windows>, ) { let window = windows.get_primary_mut().unwrap(); let height = window.height(); let mut end_credits_have_ended = false; for (_, mut end_credit, mut style) in end_credits.iter_mut() { end_credit.0 = end_credit.0 - (time.delta_seconds() * (8592.0 / height)); style.position.top = Val::Percent(end_credit.0); println!("End Credit: {}",end_credit.0); if end_credit.0 < -60.0 * (8592.0 / height) { end_credits_have_ended = true; } } if end_credits_have_ended { for (entity, _, _) in end_credits.iter_mut() { commands.entity(entity).despawn(); } state.set(crate::AppState::MainMenu).unwrap(); } } pub fn show_credits( mut credit_event: EventReader<CreditsEvent>, mut app_state: ResMut<State<crate::AppState>> ) { if credit_event.iter().count() > 0 { app_state.set(crate::AppState::Credits).unwrap(); } }
pub use crate::error::{Error, ErrorExt, ResultExt}; pub use crate::ext::{EventHandlerExt, JSObjectExt, JsonStreamReadExt, JsonStreamWriteExt}; pub use neon::prelude::*; pub use tokio::prelude::*; pub use tokio::stream::StreamExt;
use std::env; use std::fs; fn main(){ let args : Vec<String> = env::args().collect(); if args.len() < 2 { return; } let lines = fs::read_to_string(&args[1]).unwrap(); let mut disks = Vec::<(i32, i32)>::new(); for line in lines.split('\n') { if line == "" { continue; } let words = line.split(' ').collect::<Vec<&str>>(); let disksize = words.get(3).unwrap().parse::<i32>().unwrap(); let startpos = words.get(11).unwrap().to_string().strip_suffix('.').unwrap().parse::<i32>().unwrap(); disks.push((disksize, startpos)); } // Part 2 disks.push((11, 0)); // <- Part 2 let mut start : i32 = 0; let mut period : i32 = 1; let mut offset : i32 = 1; for (dperiod, dstart) in disks { while (start+offset+dstart + dperiod) % dperiod != 0 { start += period; } period *= dperiod; offset += 1; } println!("{}", start); }
#[derive(derive_more::From, collections_fromstr::FromStr, PartialEq)] #[item_separator = ","] struct NewVec(std::vec::Vec<std::string::String>); fn main(){ use assert2::assert; use std::str::FromStr; static VALUES: &str = "Apple🍎,Banana🍌,Carrot🥕"; assert!(NewVec::from_str(VALUES).unwrap() == NewVec(vec!["Apple🍎", "Banana🍌", "Carrot🥕"].into_iter().map(String::from).collect())); }
#[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_end_to_end_length(number_of_links: u8, link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64 { super::end_to_end_length(&number_of_links, &link_length, &link_stiffness, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_end_to_end_length_per_link(link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64 { super::end_to_end_length_per_link(&link_length, &link_stiffness, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_nondimensional_end_to_end_length(number_of_links: u8, nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64 { super::nondimensional_end_to_end_length(&number_of_links, &nondimensional_link_stiffness, &nondimensional_force) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_nondimensional_end_to_end_length_per_link(nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64 { super::nondimensional_end_to_end_length_per_link(&nondimensional_link_stiffness, &nondimensional_force) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_gibbs_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64 { super::gibbs_free_energy(&number_of_links, &link_length, &hinge_mass, &link_stiffness, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_gibbs_free_energy_per_link(link_length: f64, hinge_mass: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64 { super::gibbs_free_energy_per_link(&link_length, &hinge_mass, &link_stiffness, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_relative_gibbs_free_energy(number_of_links: u8, link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64 { super::relative_gibbs_free_energy(&number_of_links, &link_length, &link_stiffness, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_relative_gibbs_free_energy_per_link(link_length: f64, link_stiffness: f64, force: f64, temperature: f64) -> f64 { super::relative_gibbs_free_energy_per_link(&link_length, &link_stiffness, &force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_nondimensional_gibbs_free_energy(number_of_links: u8, link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_force: f64, temperature: f64) -> f64 { super::nondimensional_gibbs_free_energy(&number_of_links, &link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_nondimensional_gibbs_free_energy_per_link(link_length: f64, hinge_mass: f64, nondimensional_link_stiffness: f64, nondimensional_force: f64, temperature: f64) -> f64 { super::nondimensional_gibbs_free_energy_per_link(&link_length, &hinge_mass, &nondimensional_link_stiffness, &nondimensional_force, &temperature) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_nondimensional_relative_gibbs_free_energy(number_of_links: u8, nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64 { super::nondimensional_relative_gibbs_free_energy(&number_of_links, &nondimensional_link_stiffness, &nondimensional_force) } #[no_mangle] pub extern fn physics_single_chain_ufjc_lennard_jones_thermodynamics_isotensional_asymptotic_nondimensional_relative_gibbs_free_energy_per_link(nondimensional_link_stiffness: f64, nondimensional_force: f64) -> f64 { super::nondimensional_relative_gibbs_free_energy_per_link(&nondimensional_link_stiffness, &nondimensional_force) }
/// A Telegram chat. #[derive(Debug,Deserialize)] pub struct Chat { /// Unique identifier for this chat. pub id: i64, /// Type of chat, can be either "private", "group", "supergroup" or /// "channel". #[serde(rename = "type")] pub kind: String, /// Title for supergroups, channels and group chats. pub title: Option<String>, /// Username for private chats, supergroups and channels if available. pub username: Option<String>, /// First name of the other party in a private chat. pub first_name: Option<String>, /// Last name of the other party in a private chat pub last_name: Option<String>, /// True if a group as 'All Members Are Admins' enabled. pub all_members_are_administrators: Option<bool>, }
use crate::{ fold::{HirFoldable, HirFolder, HirVisitor}, ids::{ AscriptionExpr, Assignment, BlockExpr, CallExpr, Expression, FieldExpr, Identifier, IfExpr, Literal, MatchExpr, Pattern, RecordExpr, Statement, Type, }, }; use either::Either; use valis_ds::{Intern, Untern}; use valis_ds_macros::DebugWith; use valis_syntax::Symbol; #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub enum ExpressionData { If(IfExpr), Call(CallExpr), Field(FieldExpr), Variable(Identifier), Record(RecordExpr), Literal(Literal), Block(BlockExpr), Match(MatchExpr), Ascription(AscriptionExpr), } impl HirFoldable for Expression { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { use ExpressionData::*; let expr_data = self.untern(folder.tables()); let new_expr_data = match expr_data { If(inner) => If(inner.fold_with(folder)), Call(inner) => Call(inner.fold_with(folder)), Field(inner) => Field(inner.fold_with(folder)), Variable(inner) => Variable(inner.fold_with(folder)), Record(inner) => Record(inner.fold_with(folder)), Literal(inner) => Literal(inner.fold_with(folder)), Block(inner) => Block(inner.fold_with(folder)), Match(inner) => Match(inner.fold_with(folder)), Ascription(inner) => Ascription(inner.fold_with(folder)), }; if expr_data == new_expr_data { *self } else { new_expr_data.intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { use ExpressionData::*; match self.untern(visitor.tables()) { If(inner) => inner.visit_with(visitor), Call(inner) => inner.visit_with(visitor), Field(inner) => inner.visit_with(visitor), Variable(inner) => inner.visit_with(visitor), Record(inner) => inner.visit_with(visitor), Literal(inner) => inner.visit_with(visitor), Block(inner) => inner.visit_with(visitor), Match(inner) => inner.visit_with(visitor), Ascription(inner) => inner.visit_with(visitor), } } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_expression(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_expression(*self) } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub struct IfExprData { pub condition: Expression, pub then_block: BlockExpr, pub else_block: Option<Either<BlockExpr, IfExpr>>, } impl HirFoldable for IfExpr { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { let IfExprData { condition, then_block, else_block, } = self.untern(folder.tables()); let new_condition = condition.fold_with(folder); let new_then_block = then_block.fold_with(folder); let new_else_block = else_block.fold_with(folder); if condition == new_condition && new_then_block == then_block && new_else_block == else_block { *self } else { IfExprData { condition: new_condition, then_block: new_then_block, else_block: new_else_block, } .intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { let IfExprData { condition, then_block, else_block, } = self.untern(visitor.tables()); let o1 = condition.visit_with(visitor); let o2 = then_block.visit_with(visitor); let o3 = else_block.visit_with(visitor); visitor.combine_output(visitor.combine_output(o1, o2), o3) } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_if_expr(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_if_expr(*self) } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub struct CallExprData { pub callable: Expression, pub arguments: Vec<Expression>, } impl HirFoldable for CallExpr { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { let CallExprData { callable, arguments, } = self.untern(folder.tables()); let new_callable = callable.fold_with(folder); let new_arguments = arguments.fold_with(folder); if new_callable == callable && new_arguments == arguments { *self } else { CallExprData { callable: new_callable, arguments: new_arguments, } .intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { let CallExprData { callable, arguments, } = self.untern(visitor.tables()); let o1 = callable.visit_with(visitor); let o2 = arguments.visit_with(visitor); visitor.combine_output(o1, o2) } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_call_expr(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_call_expr(*self) } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub struct FieldExprData { pub record: Expression, pub field: Identifier, } impl HirFoldable for FieldExpr { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { let FieldExprData { record, field } = self.untern(folder.tables()); let new_record = record.fold_with(folder); let new_field = field.fold_with(folder); if new_record == record && new_field == field { *self } else { FieldExprData { record: new_record, field: new_field, } .intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { let FieldExprData { record, field } = self.untern(visitor.tables()); let o1 = record.visit_with(visitor); let o2 = field.visit_with(visitor); visitor.combine_output(o1, o2) } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_field_expr(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_field_expr(*self) } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub struct RecordExprData { pub labels: Vec<Identifier>, pub values: Vec<Expression>, } impl HirFoldable for RecordExpr { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { let RecordExprData { labels, values } = self.untern(folder.tables()); let new_labels = labels.fold_with(folder); let new_values = values.fold_with(folder); if new_labels == labels && new_values == values { *self } else { RecordExprData { labels: new_labels, values: new_values, } .intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { let RecordExprData { labels, values } = self.untern(visitor.tables()); let o1 = labels.visit_with(visitor); let o2 = values.visit_with(visitor); visitor.combine_output(o1, o2) } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_record_expr(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_record_expr(*self) } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub struct BlockExprData { pub statements: Vec<Statement>, pub return_expr: Option<Expression>, } impl HirFoldable for BlockExpr { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { let BlockExprData { statements, return_expr, } = self.untern(folder.tables()); let new_statements = statements.fold_with(folder); let new_return_expr = return_expr.fold_with(folder); if new_statements == statements && new_return_expr == return_expr { *self } else { BlockExprData { statements: new_statements, return_expr: new_return_expr, } .intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { let BlockExprData { statements, return_expr, } = self.untern(visitor.tables()); let o1 = statements.visit_with(visitor); let o2 = return_expr.visit_with(visitor); visitor.combine_output(o1, o2) } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_block_expr(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_block_expr(*self) } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub struct MatchExprData { pub condition: Expression, pub arms: Vec<(Pattern, Expression)>, } impl HirFoldable for MatchExpr { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { let MatchExprData { condition, arms } = self.untern(folder.tables()); let new_condition = condition.fold_with(folder); let new_arms = arms.fold_with(folder); if new_condition == condition && new_arms == arms { *self } else { MatchExprData { condition: new_condition, arms: new_arms, } .intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { let MatchExprData { condition, arms } = self.untern(visitor.tables()); let o1 = condition.visit_with(visitor); let o2 = arms.visit_with(visitor); visitor.combine_output(o1, o2) } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_match_expr(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_match_expr(*self) } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub struct AscriptionExprData { pub typed_expr: Expression, pub ascribed_type: Type, } impl HirFoldable for AscriptionExpr { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { let AscriptionExprData { typed_expr, ascribed_type, } = self.untern(folder.tables()); let new_typed_expr = typed_expr.fold_with(folder); let new_ascribed_type = ascribed_type.fold_with(folder); if new_typed_expr == typed_expr && new_ascribed_type == ascribed_type { *self } else { AscriptionExprData { typed_expr: new_typed_expr, ascribed_type: new_ascribed_type, } .intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { let AscriptionExprData { typed_expr, ascribed_type, } = self.untern(visitor.tables()); let o1 = typed_expr.visit_with(visitor); let o2 = ascribed_type.visit_with(visitor); visitor.combine_output(o1, o2) } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_ascription_expr(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_ascription_expr(*self) } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub struct LiteralData { pub kind: LiteralKind, pub text: Symbol, } impl HirFoldable for Literal { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { let LiteralData { kind, text } = self.untern(folder.tables()); let new_kind = kind.fold_with(folder); // the `text` field is not processed because it is a RawText struct and should // be handled in a custom manner by any folder if new_kind == kind { *self } else { LiteralData { kind: new_kind, text, } .intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { let LiteralData { kind, .. } = self.untern(visitor.tables()); // the `text` field is not processed because it is a RawText struct and should // be handled in a custom manner by any visitor kind.visit_with(visitor) } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_literal(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_literal(*self) } } #[derive(Debug, DebugWith, Copy, Clone, PartialEq, Eq, Hash)] pub enum LiteralKind { Symbol, Integer, Float, True, False, } impl HirFoldable for LiteralKind { fn super_fold_with<F: HirFolder>(&self, _folder: &mut F) -> Self { Clone::clone(self) } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.default_output() } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub enum StatementData { Assignment(Assignment), Expression(Expression), } impl HirFoldable for Statement { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { use StatementData::*; let statement_data = self.untern(folder.tables()); let new_statement_data = match statement_data { Assignment(inner) => Assignment(inner.fold_with(folder)), Expression(inner) => Expression(inner.fold_with(folder)), }; if new_statement_data == statement_data { *self } else { new_statement_data.intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { use StatementData::*; match self.untern(visitor.tables()) { Assignment(inner) => inner.visit_with(visitor), Expression(inner) => inner.visit_with(visitor), } } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_statement(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_statement(*self) } } #[derive(Debug, DebugWith, Clone, PartialEq, Eq, Hash)] pub struct AssignmentData { pub destination: Pattern, pub value: Expression, } impl HirFoldable for Assignment { fn super_fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { let AssignmentData { destination, value } = self.untern(folder.tables()); let new_destination = destination.fold_with(folder); let new_value = value.fold_with(folder); if new_destination == destination && new_value == value { *self } else { AssignmentData { destination: new_destination, value: new_value, } .intern(folder.tables()) } } fn super_visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { let AssignmentData { destination, value } = self.untern(visitor.tables()); let o1 = destination.visit_with(visitor); let o2 = value.visit_with(visitor); visitor.combine_output(o1, o2) } fn fold_with<F: HirFolder>(&self, folder: &mut F) -> Self { folder.fold_assignment(*self) } fn visit_with<V: HirVisitor>(&self, visitor: &mut V) -> V::Output { visitor.visit_assignment(*self) } }
use crate::grammar::model::Fragment; use crate::grammar::parsers::whitespace; use crate::grammar::parsers::whitespace::{multiline_comment, token_delimiter}; use crate::grammar::testing::TestingContext; use crate::grammar::tracing::input::OptionallyTraceable; use codespan::{FileId, Files}; fn setup(src: &str) -> (Files<String>, FileId) { let mut f: Files<String> = Files::new(); let id = f.add("test", src.to_string()); (f, id) } #[test] pub fn single_comment() { let (f, h) = setup("// line comment"); let frag = Fragment::new(&f, h); let res = whitespace::line_comment(frag); if let Ok((rem, val)) = res { assert_eq!(rem.len(), 0); assert_eq!(val.source(), " line comment"); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn empty_single_comment() { let (f, h) = setup("//"); let frag = Fragment::new(&f, h); let res = whitespace::line_comment(frag); if let Ok((rem, val)) = res { assert_eq!(rem.len(), 0); assert_eq!(val.source(), ""); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn comment_with_tail() { let (f, h) = setup("// line comment\nnot a comment"); let frag = Fragment::new(&f, h); let res = whitespace::line_comment(frag); if let Ok((rem, val)) = res { assert_eq!(rem.len(), 14); assert_eq!(val.source(), " line comment"); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn multi_comment_single() { let (f, h) = setup("/* single line multi comment */"); let frag = Fragment::new(&f, h); let res = whitespace::multiline_comment(frag); if let Ok((rem, val)) = res { assert_eq!(rem.len(), 0); assert_eq!(val.source(), " single line multi comment "); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn multi_comment_multi() { TestingContext::with(&["/* mutli line\n * multi comment */"]).test_output( multiline_comment, 0, |(rem, prod)| { rem.get_trace().unwrap().print().unwrap(); assert_eq!(rem.len(), 0); assert_eq!(prod.source(), " mutli line\n * multi comment "); }, ); } #[test] fn multi_comment_empty() { let (f, h) = setup("/**/"); let frag = Fragment::new(&f, h); let res = whitespace::multiline_comment(frag); if let Ok((rem, val)) = res { assert_eq!(rem.len(), 0); assert_eq!(val.source(), ""); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn comments_and_whitespace() { let (f, h) = setup("// line comment\n// this is another comment\n // third comment\n"); let frag = Fragment::new(&f, h); let res = whitespace::token_delimiter(frag); if let Ok((rem, _)) = res { assert_eq!(rem.len(), 0); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] pub fn empty() { let (f, h) = setup(""); let frag = Fragment::new(&f, h); let res = whitespace::token_delimiter(frag); if let Ok((rem, _)) = res { assert_eq!(rem.len(), 0); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn line_comment_only() { let (f, h) = setup("// comment"); let frag = Fragment::new(&f, h); let res = whitespace::token_delimiter(frag); if let Ok((rem, _)) = res { assert_eq!(rem.len(), 0); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] pub fn whitespace_only() { let (f, h) = setup("\t \n\n \t "); let frag = Fragment::new(&f, h); let res = whitespace::token_delimiter(frag); if let Ok((rem, _)) = res { assert_eq!(rem.len(), 0); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn multiline_comment_only() { let (f, h) = setup("/* comment */"); let frag = Fragment::new(&f, h); let res = whitespace::token_delimiter(frag); if let Ok((rem, _)) = res { assert_eq!(rem.len(), 0); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn multiline_comments_and_whitespace() { let (f, h) = setup("/* these are many */\n /* multiline comments */"); let frag = Fragment::new(&f, h); let res = whitespace::token_delimiter(frag); if let Ok((rem, _)) = res { assert_eq!(rem.len(), 0); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn everything() { TestingContext::with(&[ " // single\n /* these are many */\n /* multiline comments */ // another", ]) .test_output(token_delimiter, 0, |(rem, _)| { rem.get_trace().unwrap().print().unwrap(); assert_eq!(rem.len(), 0); }); } #[test] fn multi_in_single() { let (f, h) = setup("// comment /* not nested */ comment"); let frag = Fragment::new(&f, h); let res = whitespace::token_delimiter(frag); if let Ok((rem, _)) = res { assert_eq!(rem.len(), 0); } else { eprintln!("{:#?}", res); assert!(false); } } #[test] fn single_in_multi() { TestingContext::with(&["/* comment // not nested */"]).test_output( token_delimiter, 0, |(rem, _)| { rem.get_trace().unwrap().print().unwrap(); assert_eq!(rem.len(), 0); }, ); }
use super::*; #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] #[repr(transparent)] pub struct KeyInterruptControl(u16); impl KeyInterruptControl { const_new!(); bitfield_bool!(u16; 0, a, with_a, set_a); bitfield_bool!(u16; 1, b, with_b, set_b); bitfield_bool!(u16; 2, select, with_select, set_select); bitfield_bool!(u16; 3, start, with_start, set_start); bitfield_bool!(u16; 4, right, with_right, set_right); bitfield_bool!(u16; 5, left, with_left, set_left); bitfield_bool!(u16; 6, up, with_up, set_up); bitfield_bool!(u16; 7, down, with_down, set_down); bitfield_bool!(u16; 8, r, with_r, set_r); bitfield_bool!(u16; 9, l, with_l, set_l); // bitfield_bool!(u16; 14, enabled, with_enabled, set_enabled); bitfield_bool!(u16; 15, require_all, with_require_all, set_require_all); }
//! Defines definitions for a [`Symlink`]. use serde::{Deserialize, Serialize}; use std::path::PathBuf; /// A symlink to be created during the deployment. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] pub struct Symlink { /// Absolute path of the link source. pub source_path: PathBuf, /// Absolute path of the link target. pub target_path: PathBuf, /// Indicates if any existing symlink at the [`Symlink::target_path`] should /// be replaced by this item. /// /// # NOTE /// It will only replace existing symlink. #[serde(default = "default_replace_value")] pub replace: bool, } /// Provides the default value for [`Symlink::replace`]. const fn default_replace_value() -> bool { true }
use super::DateTime; use crate::utils::f64_from_string; use serde::{Deserialize, Serialize}; use uuid::Uuid; // Public #[derive(Serialize, Deserialize, Debug)] pub struct Time { pub iso: String, pub epoch: f64, } #[derive(Serialize, Deserialize, Debug)] pub struct CurrencyDetails { #[serde(rename = "type")] pub _type: Option<CurrencyDetailsType>, pub symbol: Option<String>, pub network_confirmations: Option<u32>, pub sort_order: Option<u32>, pub crypto_address_link: Option<String>, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "camelCase")] pub enum CurrencyDetailsType { Crypto, Fiat, } #[derive(Serialize, Deserialize, Debug)] pub struct Currency { pub id: String, pub name: String, #[serde(deserialize_with = "f64_from_string")] pub min_size: f64, pub status: String, pub message: Option<String>, #[serde(deserialize_with = "f64_from_string")] pub max_precision: f64, pub convertible_to: Option<Vec<String>>, pub details: CurrencyDetails, } #[derive(Serialize, Deserialize, Debug)] pub struct Product { pub id: String, pub display_name: String, pub base_currency: String, pub quote_currency: String, #[serde(deserialize_with = "f64_from_string")] pub quote_increment: f64, #[serde(deserialize_with = "f64_from_string")] pub base_increment: f64, #[serde(deserialize_with = "f64_from_string")] pub min_market_funds: f64, pub margin_enabled: bool, pub status: ProductStatus, pub status_message: String, pub cancel_only: bool, pub limit_only: bool, pub post_only: bool, pub trading_disabled: bool, pub fx_stablecoin: bool, #[serde(deserialize_with = "f64_from_string")] pub max_slippage_percentage: f64, pub auction_mode: bool, } #[derive(Serialize, Deserialize, Debug, Clone, Copy)] #[serde(rename_all = "camelCase")] pub enum ProductStatus { Online, Offline, Internal, Delisted, } #[derive(Serialize, Deserialize, Debug)] pub struct Book<T> { pub sequence: usize, pub bids: Vec<T>, pub asks: Vec<T>, } pub trait BookLevel { fn level() -> u8; } #[derive(Serialize, Deserialize, Debug)] pub struct BookRecordL1 { #[serde(deserialize_with = "f64_from_string")] pub price: f64, #[serde(deserialize_with = "f64_from_string")] pub size: f64, pub num_orders: usize, } impl BookLevel for BookRecordL1 { fn level() -> u8 { 1 } } #[derive(Serialize, Deserialize, Debug)] pub struct BookRecordL2 { #[serde(deserialize_with = "f64_from_string")] pub price: f64, #[serde(deserialize_with = "f64_from_string")] pub size: f64, pub num_orders: usize, } impl BookLevel for BookRecordL2 { fn level() -> u8 { 2 } } #[derive(Serialize, Deserialize, Debug)] pub struct BookRecordL3 { #[serde(deserialize_with = "f64_from_string")] pub price: f64, #[serde(deserialize_with = "f64_from_string")] pub size: f64, pub order_id: Uuid, } impl BookLevel for BookRecordL3 { fn level() -> u8 { 3 } } #[derive(Serialize, Deserialize, Debug)] pub struct Ticker { pub trade_id: usize, #[serde(deserialize_with = "f64_from_string")] pub price: f64, #[serde(deserialize_with = "f64_from_string")] pub size: f64, #[serde(deserialize_with = "f64_from_string")] pub bid: f64, #[serde(deserialize_with = "f64_from_string")] pub ask: f64, #[serde(deserialize_with = "f64_from_string")] pub volume: f64, pub time: DateTime, } #[derive(Serialize, Deserialize, Debug)] pub struct Trade { pub time: DateTime, pub trade_id: usize, #[serde(deserialize_with = "f64_from_string")] pub price: f64, #[serde(deserialize_with = "f64_from_string")] pub size: f64, pub side: super::reqs::OrderSide, } #[derive(Serialize, Deserialize, Debug)] pub struct Candle( pub usize, // time pub f64, // low pub f64, // high pub f64, // open pub f64, // close pub f64, // volume ); #[derive(Serialize, Deserialize, Debug)] pub struct Stats24H { #[serde(deserialize_with = "f64_from_string")] pub open: f64, #[serde(deserialize_with = "f64_from_string")] pub high: f64, #[serde(deserialize_with = "f64_from_string")] pub low: f64, #[serde(deserialize_with = "f64_from_string")] pub volume: f64, } pub enum Granularity { M1 = 60, M5 = 300, M15 = 900, H1 = 3600, H4 = 14400, H6 = 21600, D1 = 86400, }
use futures::try_ready; use tokio::net::tcp::{self, TcpStream}; #[cfg(unix)] use tokio::net::unix::{self, UnixStream}; use tokio::prelude::*; use tower_grpc::codegen::server::tower::Service; use std::{io, net::SocketAddr}; #[cfg(unix)] use std::path::{Path, PathBuf}; /// Specifies the connection details of a remote TCP/IP peer. #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct TcpPeer { addr: SocketAddr, } impl TcpPeer { pub fn new(addr: SocketAddr) -> Self { TcpPeer { addr } } pub fn addr(&self) -> &SocketAddr { &self.addr } } /// Specifies the connection details of a local Unix socket peer. /// /// This type is only available on Unix. #[cfg(unix)] #[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct UnixPeer { path: PathBuf, } #[cfg(unix)] impl UnixPeer { pub fn new<P: Into<PathBuf>>(path: P) -> Self { UnixPeer { path: path.into() } } pub fn path(&self) -> &Path { &self.path } } impl Service<()> for TcpPeer { type Response = TcpStream; type Error = io::Error; type Future = TcpConnectFuture; fn poll_ready(&mut self) -> Poll<(), Self::Error> { Ok(().into()) } fn call(&mut self, _: ()) -> Self::Future { TcpStream::connect(self.addr()).into() } } /// A future adapter that resolves to a `TcpStream` optimized for /// the HTTP/2 protocol. /// It attempts to set the socket option `TCP_NODELAY` to true before /// resolving with the connection. Failure to set the option is silently /// ignored, which may result in degraded latency. pub struct TcpConnectFuture { inner: tcp::ConnectFuture, } impl From<tcp::ConnectFuture> for TcpConnectFuture { #[inline] fn from(src: tcp::ConnectFuture) -> Self { TcpConnectFuture { inner: src } } } impl Future for TcpConnectFuture { type Item = TcpStream; type Error = io::Error; fn poll(&mut self) -> Result<Async<TcpStream>, io::Error> { let stream = try_ready!(self.inner.poll()); stream.set_nodelay(true).unwrap_or(()); Ok(Async::Ready(stream)) } } #[cfg(unix)] impl Service<()> for UnixPeer { type Response = UnixStream; type Error = io::Error; type Future = unix::ConnectFuture; fn poll_ready(&mut self) -> Poll<(), Self::Error> { Ok(().into()) } fn call(&mut self, _: ()) -> Self::Future { UnixStream::connect(self.path()) } }
#[doc = "Register `I2C_TIMINGR` reader"] pub type R = crate::R<I2C_TIMINGR_SPEC>; #[doc = "Register `I2C_TIMINGR` writer"] pub type W = crate::W<I2C_TIMINGR_SPEC>; #[doc = "Field `SCLL` reader - SCLL"] pub type SCLL_R = crate::FieldReader; #[doc = "Field `SCLL` writer - SCLL"] pub type SCLL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `SCLH` reader - SCLH"] pub type SCLH_R = crate::FieldReader; #[doc = "Field `SCLH` writer - SCLH"] pub type SCLH_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 8, O>; #[doc = "Field `SDADEL` reader - SDADEL"] pub type SDADEL_R = crate::FieldReader; #[doc = "Field `SDADEL` writer - SDADEL"] pub type SDADEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `SCLDEL` reader - SCLDEL"] pub type SCLDEL_R = crate::FieldReader; #[doc = "Field `SCLDEL` writer - SCLDEL"] pub type SCLDEL_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; #[doc = "Field `PRESC` reader - PRESC"] pub type PRESC_R = crate::FieldReader; #[doc = "Field `PRESC` writer - PRESC"] pub type PRESC_W<'a, REG, const O: u8> = crate::FieldWriter<'a, REG, 4, O>; impl R { #[doc = "Bits 0:7 - SCLL"] #[inline(always)] pub fn scll(&self) -> SCLL_R { SCLL_R::new((self.bits & 0xff) as u8) } #[doc = "Bits 8:15 - SCLH"] #[inline(always)] pub fn sclh(&self) -> SCLH_R { SCLH_R::new(((self.bits >> 8) & 0xff) as u8) } #[doc = "Bits 16:19 - SDADEL"] #[inline(always)] pub fn sdadel(&self) -> SDADEL_R { SDADEL_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:23 - SCLDEL"] #[inline(always)] pub fn scldel(&self) -> SCLDEL_R { SCLDEL_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 28:31 - PRESC"] #[inline(always)] pub fn presc(&self) -> PRESC_R { PRESC_R::new(((self.bits >> 28) & 0x0f) as u8) } } impl W { #[doc = "Bits 0:7 - SCLL"] #[inline(always)] #[must_use] pub fn scll(&mut self) -> SCLL_W<I2C_TIMINGR_SPEC, 0> { SCLL_W::new(self) } #[doc = "Bits 8:15 - SCLH"] #[inline(always)] #[must_use] pub fn sclh(&mut self) -> SCLH_W<I2C_TIMINGR_SPEC, 8> { SCLH_W::new(self) } #[doc = "Bits 16:19 - SDADEL"] #[inline(always)] #[must_use] pub fn sdadel(&mut self) -> SDADEL_W<I2C_TIMINGR_SPEC, 16> { SDADEL_W::new(self) } #[doc = "Bits 20:23 - SCLDEL"] #[inline(always)] #[must_use] pub fn scldel(&mut self) -> SCLDEL_W<I2C_TIMINGR_SPEC, 20> { SCLDEL_W::new(self) } #[doc = "Bits 28:31 - PRESC"] #[inline(always)] #[must_use] pub fn presc(&mut self) -> PRESC_W<I2C_TIMINGR_SPEC, 28> { PRESC_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 = "Access: No wait states\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`i2c_timingr::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 [`i2c_timingr::W`](W). You can also [`modify`](crate::generic::Reg::modify) this register. See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct I2C_TIMINGR_SPEC; impl crate::RegisterSpec for I2C_TIMINGR_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`i2c_timingr::R`](R) reader structure"] impl crate::Readable for I2C_TIMINGR_SPEC {} #[doc = "`write(|w| ..)` method takes [`i2c_timingr::W`](W) writer structure"] impl crate::Writable for I2C_TIMINGR_SPEC { const ZERO_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; const ONE_TO_MODIFY_FIELDS_BITMAP: Self::Ux = 0; } #[doc = "`reset()` method sets I2C_TIMINGR to value 0"] impl crate::Resettable for I2C_TIMINGR_SPEC { const RESET_VALUE: Self::Ux = 0; }
/* * x is defined as an immutable variable, then defined again later (shadowed?) * redefining a variable like this lets you change the type. */ fn main() { let x = 5; println!("The value of x is: {}", x); let x = 6; println!("The value of x is: {}", x); }
#[doc = "Register `FMC_HWCFGR1` reader"] pub type R = crate::R<FMC_HWCFGR1_SPEC>; #[doc = "Field `NAND_SEL` reader - NAND_SEL"] pub type NAND_SEL_R = crate::BitReader; #[doc = "Field `NAND_ECC` reader - NAND_ECC"] pub type NAND_ECC_R = crate::BitReader; #[doc = "Field `SDRAM_SEL` reader - SDRAM_SEL"] pub type SDRAM_SEL_R = crate::BitReader; #[doc = "Field `ID_SIZE` reader - ID_SIZE"] pub type ID_SIZE_R = crate::FieldReader; #[doc = "Field `WA_LN2DPTH` reader - WA_LN2DPTH"] pub type WA_LN2DPTH_R = crate::FieldReader; #[doc = "Field `WD_LN2DPTH` reader - WD_LN2DPTH"] pub type WD_LN2DPTH_R = crate::FieldReader; #[doc = "Field `WR_LN2DPTH` reader - WR_LN2DPTH"] pub type WR_LN2DPTH_R = crate::FieldReader; #[doc = "Field `RA_LN2DPTH` reader - RA_LN2DPTH"] pub type RA_LN2DPTH_R = crate::FieldReader; impl R { #[doc = "Bit 0 - NAND_SEL"] #[inline(always)] pub fn nand_sel(&self) -> NAND_SEL_R { NAND_SEL_R::new((self.bits & 1) != 0) } #[doc = "Bit 4 - NAND_ECC"] #[inline(always)] pub fn nand_ecc(&self) -> NAND_ECC_R { NAND_ECC_R::new(((self.bits >> 4) & 1) != 0) } #[doc = "Bit 8 - SDRAM_SEL"] #[inline(always)] pub fn sdram_sel(&self) -> SDRAM_SEL_R { SDRAM_SEL_R::new(((self.bits >> 8) & 1) != 0) } #[doc = "Bits 12:15 - ID_SIZE"] #[inline(always)] pub fn id_size(&self) -> ID_SIZE_R { ID_SIZE_R::new(((self.bits >> 12) & 0x0f) as u8) } #[doc = "Bits 16:19 - WA_LN2DPTH"] #[inline(always)] pub fn wa_ln2dpth(&self) -> WA_LN2DPTH_R { WA_LN2DPTH_R::new(((self.bits >> 16) & 0x0f) as u8) } #[doc = "Bits 20:23 - WD_LN2DPTH"] #[inline(always)] pub fn wd_ln2dpth(&self) -> WD_LN2DPTH_R { WD_LN2DPTH_R::new(((self.bits >> 20) & 0x0f) as u8) } #[doc = "Bits 24:27 - WR_LN2DPTH"] #[inline(always)] pub fn wr_ln2dpth(&self) -> WR_LN2DPTH_R { WR_LN2DPTH_R::new(((self.bits >> 24) & 0x0f) as u8) } #[doc = "Bits 28:31 - RA_LN2DPTH"] #[inline(always)] pub fn ra_ln2dpth(&self) -> RA_LN2DPTH_R { RA_LN2DPTH_R::new(((self.bits >> 28) & 0x0f) as u8) } } #[doc = "FMC Hardware configuration register 1\n\nYou can [`read`](crate::generic::Reg::read) this register and get [`fmc_hwcfgr1::R`](R). See [API](https://docs.rs/svd2rust/#read--modify--write-api)."] pub struct FMC_HWCFGR1_SPEC; impl crate::RegisterSpec for FMC_HWCFGR1_SPEC { type Ux = u32; } #[doc = "`read()` method returns [`fmc_hwcfgr1::R`](R) reader structure"] impl crate::Readable for FMC_HWCFGR1_SPEC {} #[doc = "`reset()` method sets FMC_HWCFGR1 to value 0x2232_b011"] impl crate::Resettable for FMC_HWCFGR1_SPEC { const RESET_VALUE: Self::Ux = 0x2232_b011; }
// Copyright (c) Facebook, Inc. and its affiliates. // // This source code is licensed under the MIT license found in the // LICENSE file in the "hack" directory of this source tree. use arena_collections::list::List; use arena_trait::TrivialDrop; use ocamlrep::slab::OwnedSlab; use ocamlrep_derive::{FromOcamlRepIn, ToOcamlRep}; use oxidized::file_info::NameType; use serde::Serialize; use crate::{shallow_decl_defs, typing_defs}; type SMap<'a, T> = arena_collections::SortedAssocList<'a, &'a str, T>; #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, Ord, PartialEq, PartialOrd, Serialize, ToOcamlRep )] pub struct Decls<'a> { pub classes: SMap<'a, &'a shallow_decl_defs::ShallowClass<'a>>, pub funs: SMap<'a, &'a typing_defs::FunElt<'a>>, pub typedefs: SMap<'a, &'a typing_defs::TypedefType<'a>>, pub consts: SMap<'a, &'a typing_defs::ConstDecl<'a>>, } impl<'a> TrivialDrop for Decls<'a> {} impl<'a> Decls<'a> { pub fn get_slab(&self, kind: NameType, symbol: &str) -> Option<OwnedSlab> { match kind { NameType::Fun => Some(Self::decl_to_slab(self.funs.get(symbol)?)), NameType::Class => Some(Self::decl_to_slab(self.classes.get(symbol)?)), NameType::RecordDef => unimplemented!(), NameType::Typedef => Some(Self::decl_to_slab(self.typedefs.get(symbol)?)), NameType::Const => Some(Self::decl_to_slab(self.consts.get(symbol)?)), } } pub fn decl_to_slab(decl: &impl ocamlrep::ToOcamlRep) -> OwnedSlab { ocamlrep::slab::to_slab(decl) .expect("Got immediate value, but decls should always be block values") } } #[derive( Clone, Debug, Eq, FromOcamlRepIn, Hash, Ord, PartialEq, PartialOrd, ToOcamlRep )] pub struct DeclLists<'a> { pub classes: List<'a, (&'a str, &'a shallow_decl_defs::ShallowClass<'a>)>, pub funs: List<'a, (&'a str, &'a typing_defs::FunElt<'a>)>, pub typedefs: List<'a, (&'a str, &'a typing_defs::TypedefType<'a>)>, pub consts: List<'a, (&'a str, &'a typing_defs::ConstDecl<'a>)>, } impl<'a> TrivialDrop for DeclLists<'a> {}
// This file was generated by gir (https://github.com/gtk-rs/gir @ fbb95f4) // from gir-files (https://github.com/gtk-rs/gir-files @ 77d1f70) // DO NOT EDIT use OutputStream; use Seekable; use ffi; use glib; use glib::object::Downcast; use glib::object::IsA; use glib::signal::SignalHandlerId; use glib::signal::connect; use glib::translate::*; use glib_ffi; use gobject_ffi; use std::boxed::Box as Box_; use std::mem; use std::mem::transmute; use std::ptr; glib_wrapper! { pub struct MemoryOutputStream(Object<ffi::GMemoryOutputStream, ffi::GMemoryOutputStreamClass>): OutputStream, Seekable; match fn { get_type => || ffi::g_memory_output_stream_get_type(), } } impl MemoryOutputStream { #[cfg(any(feature = "v2_36", feature = "dox"))] pub fn new_resizable() -> MemoryOutputStream { unsafe { OutputStream::from_glib_full(ffi::g_memory_output_stream_new_resizable()).downcast_unchecked() } } } pub trait MemoryOutputStreamExt { fn get_data_size(&self) -> usize; #[cfg(any(feature = "v2_34", feature = "dox"))] fn steal_as_bytes(&self) -> Option<glib::Bytes>; fn connect_property_data_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId; } impl<O: IsA<MemoryOutputStream> + IsA<glib::object::Object>> MemoryOutputStreamExt for O { fn get_data_size(&self) -> usize { unsafe { ffi::g_memory_output_stream_get_data_size(self.to_glib_none().0) } } #[cfg(any(feature = "v2_34", feature = "dox"))] fn steal_as_bytes(&self) -> Option<glib::Bytes> { unsafe { from_glib_full(ffi::g_memory_output_stream_steal_as_bytes(self.to_glib_none().0)) } } fn connect_property_data_size_notify<F: Fn(&Self) + 'static>(&self, f: F) -> SignalHandlerId { unsafe { let f: Box_<Box_<Fn(&Self) + 'static>> = Box_::new(Box_::new(f)); connect(self.to_glib_none().0, "notify::data-size", transmute(notify_data_size_trampoline::<Self> as usize), Box_::into_raw(f) as *mut _) } } } unsafe extern "C" fn notify_data_size_trampoline<P>(this: *mut ffi::GMemoryOutputStream, _param_spec: glib_ffi::gpointer, f: glib_ffi::gpointer) where P: IsA<MemoryOutputStream> { callback_guard!(); let f: &&(Fn(&P) + 'static) = transmute(f); f(&MemoryOutputStream::from_glib_borrow(this).downcast_unchecked()) }