text
stringlengths
8
4.13M
/// Declares task-local values. /// /// The macro wraps any number of static declarations and makes them task-local. Attributes and /// visibility modifiers are allowed. /// /// Each declared value is of the accessor type [`LocalKey`]. /// /// [`LocalKey`]: task/struct.LocalKey.html /// /// # Examples /// /// ``` /// # /// use std::cell::Cell; /// /// use async_std::prelude::*; /// use async_std::task; /// /// task_local! { /// static VAL: Cell<u32> = Cell::new(5); /// } /// /// task::block_on(async { /// let v = VAL.with(|c| c.get()); /// assert_eq!(v, 5); /// }); /// ``` #[cfg(feature = "default")] #[macro_export] macro_rules! task_local { () => (); ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr) => ( $(#[$attr])* $vis static $name: $crate::task::LocalKey<$t> = { #[inline] fn __init() -> $t { $init } $crate::task::LocalKey { __init, __key: ::std::sync::atomic::AtomicU32::new(0), } }; ); ($(#[$attr:meta])* $vis:vis static $name:ident: $t:ty = $init:expr; $($rest:tt)*) => ( $crate::task_local!($(#[$attr])* $vis static $name: $t = $init); $crate::task_local!($($rest)*); ); }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from ../gir-files // DO NOT EDIT use std::ffi::CStr; #[doc(alias = "SOUP_ADDRESS_FAMILY")] pub static ADDRESS_FAMILY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_ADDRESS_FAMILY).to_str().unwrap()}); #[doc(alias = "SOUP_ADDRESS_NAME")] pub static ADDRESS_NAME: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_ADDRESS_NAME).to_str().unwrap()}); #[doc(alias = "SOUP_ADDRESS_PHYSICAL")] pub static ADDRESS_PHYSICAL: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_ADDRESS_PHYSICAL).to_str().unwrap()}); #[doc(alias = "SOUP_ADDRESS_PORT")] pub static ADDRESS_PORT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_ADDRESS_PORT).to_str().unwrap()}); #[doc(alias = "SOUP_ADDRESS_PROTOCOL")] pub static ADDRESS_PROTOCOL: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_ADDRESS_PROTOCOL).to_str().unwrap()}); #[doc(alias = "SOUP_ADDRESS_SOCKADDR")] pub static ADDRESS_SOCKADDR: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_ADDRESS_SOCKADDR).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_ADD_PATH")] pub static AUTH_DOMAIN_ADD_PATH: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_ADD_PATH).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_BASIC_AUTH_CALLBACK")] pub static AUTH_DOMAIN_BASIC_AUTH_CALLBACK: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_BASIC_AUTH_CALLBACK).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_BASIC_AUTH_DATA")] pub static AUTH_DOMAIN_BASIC_AUTH_DATA: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_BASIC_AUTH_DATA).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_DIGEST_AUTH_CALLBACK")] pub static AUTH_DOMAIN_DIGEST_AUTH_CALLBACK: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_DIGEST_AUTH_CALLBACK).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_DIGEST_AUTH_DATA")] pub static AUTH_DOMAIN_DIGEST_AUTH_DATA: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_DIGEST_AUTH_DATA).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_FILTER")] pub static AUTH_DOMAIN_FILTER: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_FILTER).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_FILTER_DATA")] pub static AUTH_DOMAIN_FILTER_DATA: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_FILTER_DATA).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_GENERIC_AUTH_CALLBACK")] pub static AUTH_DOMAIN_GENERIC_AUTH_CALLBACK: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_GENERIC_AUTH_CALLBACK).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_GENERIC_AUTH_DATA")] pub static AUTH_DOMAIN_GENERIC_AUTH_DATA: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_GENERIC_AUTH_DATA).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_PROXY")] pub static AUTH_DOMAIN_PROXY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_PROXY).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_REALM")] pub static AUTH_DOMAIN_REALM: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_REALM).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_DOMAIN_REMOVE_PATH")] pub static AUTH_DOMAIN_REMOVE_PATH: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_DOMAIN_REMOVE_PATH).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_HOST")] pub static AUTH_HOST: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_HOST).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_IS_AUTHENTICATED")] pub static AUTH_IS_AUTHENTICATED: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_IS_AUTHENTICATED).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_IS_FOR_PROXY")] pub static AUTH_IS_FOR_PROXY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_IS_FOR_PROXY).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_REALM")] pub static AUTH_REALM: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_REALM).to_str().unwrap()}); #[doc(alias = "SOUP_AUTH_SCHEME_NAME")] pub static AUTH_SCHEME_NAME: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_AUTH_SCHEME_NAME).to_str().unwrap()}); #[cfg(any(feature = "v2_30", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))] #[doc(alias = "SOUP_COOKIE_JAR_ACCEPT_POLICY")] pub static COOKIE_JAR_ACCEPT_POLICY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_COOKIE_JAR_ACCEPT_POLICY).to_str().unwrap()}); #[doc(alias = "SOUP_COOKIE_JAR_DB_FILENAME")] pub static COOKIE_JAR_DB_FILENAME: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_COOKIE_JAR_DB_FILENAME).to_str().unwrap()}); #[doc(alias = "SOUP_COOKIE_JAR_READ_ONLY")] pub static COOKIE_JAR_READ_ONLY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_COOKIE_JAR_READ_ONLY).to_str().unwrap()}); #[doc(alias = "SOUP_COOKIE_JAR_TEXT_FILENAME")] pub static COOKIE_JAR_TEXT_FILENAME: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_COOKIE_JAR_TEXT_FILENAME).to_str().unwrap()}); #[cfg(any(feature = "v2_26", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))] #[doc(alias = "SOUP_FORM_MIME_TYPE_MULTIPART")] pub static FORM_MIME_TYPE_MULTIPART: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_FORM_MIME_TYPE_MULTIPART).to_str().unwrap()}); #[cfg(any(feature = "v2_26", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_26")))] #[doc(alias = "SOUP_FORM_MIME_TYPE_URLENCODED")] pub static FORM_MIME_TYPE_URLENCODED: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_FORM_MIME_TYPE_URLENCODED).to_str().unwrap()}); #[doc(alias = "SOUP_HSTS_ENFORCER_DB_FILENAME")] pub static HSTS_ENFORCER_DB_FILENAME: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_HSTS_ENFORCER_DB_FILENAME).to_str().unwrap()}); #[cfg(any(feature = "v2_56", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_56")))] #[doc(alias = "SOUP_LOGGER_LEVEL")] pub static LOGGER_LEVEL: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_LOGGER_LEVEL).to_str().unwrap()}); #[cfg(any(feature = "v2_56", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_56")))] #[doc(alias = "SOUP_LOGGER_MAX_BODY_SIZE")] pub static LOGGER_MAX_BODY_SIZE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_LOGGER_MAX_BODY_SIZE).to_str().unwrap()}); #[cfg(any(feature = "v2_30", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))] #[doc(alias = "SOUP_MESSAGE_FIRST_PARTY")] pub static MESSAGE_FIRST_PARTY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_FIRST_PARTY).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_FLAGS")] pub static MESSAGE_FLAGS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_FLAGS).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_HTTP_VERSION")] pub static MESSAGE_HTTP_VERSION: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_HTTP_VERSION).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_IS_TOP_LEVEL_NAVIGATION")] pub static MESSAGE_IS_TOP_LEVEL_NAVIGATION: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_IS_TOP_LEVEL_NAVIGATION).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_METHOD")] pub static MESSAGE_METHOD: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_METHOD).to_str().unwrap()}); #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] #[doc(alias = "SOUP_MESSAGE_PRIORITY")] pub static MESSAGE_PRIORITY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_PRIORITY).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_REASON_PHRASE")] pub static MESSAGE_REASON_PHRASE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_REASON_PHRASE).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_REQUEST_BODY")] pub static MESSAGE_REQUEST_BODY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_REQUEST_BODY).to_str().unwrap()}); #[cfg(any(feature = "v2_46", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_46")))] #[doc(alias = "SOUP_MESSAGE_REQUEST_BODY_DATA")] pub static MESSAGE_REQUEST_BODY_DATA: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_REQUEST_BODY_DATA).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_REQUEST_HEADERS")] pub static MESSAGE_REQUEST_HEADERS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_REQUEST_HEADERS).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_RESPONSE_BODY")] pub static MESSAGE_RESPONSE_BODY: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_RESPONSE_BODY).to_str().unwrap()}); #[cfg(any(feature = "v2_46", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_46")))] #[doc(alias = "SOUP_MESSAGE_RESPONSE_BODY_DATA")] pub static MESSAGE_RESPONSE_BODY_DATA: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_RESPONSE_BODY_DATA).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_RESPONSE_HEADERS")] pub static MESSAGE_RESPONSE_HEADERS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_RESPONSE_HEADERS).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_SERVER_SIDE")] pub static MESSAGE_SERVER_SIDE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_SERVER_SIDE).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_SITE_FOR_COOKIES")] pub static MESSAGE_SITE_FOR_COOKIES: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_SITE_FOR_COOKIES).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_STATUS_CODE")] pub static MESSAGE_STATUS_CODE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_STATUS_CODE).to_str().unwrap()}); #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] #[doc(alias = "SOUP_MESSAGE_TLS_CERTIFICATE")] pub static MESSAGE_TLS_CERTIFICATE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_TLS_CERTIFICATE).to_str().unwrap()}); #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] #[doc(alias = "SOUP_MESSAGE_TLS_ERRORS")] pub static MESSAGE_TLS_ERRORS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_TLS_ERRORS).to_str().unwrap()}); #[doc(alias = "SOUP_MESSAGE_URI")] pub static MESSAGE_URI: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_MESSAGE_URI).to_str().unwrap()}); #[cfg(any(feature = "v2_42", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))] #[doc(alias = "SOUP_REQUEST_SESSION")] pub static REQUEST_SESSION: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_REQUEST_SESSION).to_str().unwrap()}); #[cfg(any(feature = "v2_42", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))] #[doc(alias = "SOUP_REQUEST_URI")] pub static REQUEST_URI: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_REQUEST_URI).to_str().unwrap()}); #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] #[doc(alias = "SOUP_SERVER_ADD_WEBSOCKET_EXTENSION")] pub static SERVER_ADD_WEBSOCKET_EXTENSION: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_ADD_WEBSOCKET_EXTENSION).to_str().unwrap()}); #[doc(alias = "SOUP_SERVER_ASYNC_CONTEXT")] pub static SERVER_ASYNC_CONTEXT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_ASYNC_CONTEXT).to_str().unwrap()}); #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] #[doc(alias = "SOUP_SERVER_HTTPS_ALIASES")] pub static SERVER_HTTPS_ALIASES: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_HTTPS_ALIASES).to_str().unwrap()}); #[cfg(any(feature = "v2_44", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_44")))] #[doc(alias = "SOUP_SERVER_HTTP_ALIASES")] pub static SERVER_HTTP_ALIASES: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_HTTP_ALIASES).to_str().unwrap()}); #[doc(alias = "SOUP_SERVER_INTERFACE")] pub static SERVER_INTERFACE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_INTERFACE).to_str().unwrap()}); #[doc(alias = "SOUP_SERVER_PORT")] pub static SERVER_PORT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_PORT).to_str().unwrap()}); #[doc(alias = "SOUP_SERVER_RAW_PATHS")] pub static SERVER_RAW_PATHS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_RAW_PATHS).to_str().unwrap()}); #[cfg(any(feature = "v2_68", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_68")))] #[doc(alias = "SOUP_SERVER_REMOVE_WEBSOCKET_EXTENSION")] pub static SERVER_REMOVE_WEBSOCKET_EXTENSION: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_REMOVE_WEBSOCKET_EXTENSION).to_str().unwrap()}); #[doc(alias = "SOUP_SERVER_SERVER_HEADER")] pub static SERVER_SERVER_HEADER: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_SERVER_HEADER).to_str().unwrap()}); #[doc(alias = "SOUP_SERVER_SSL_CERT_FILE")] pub static SERVER_SSL_CERT_FILE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_SSL_CERT_FILE).to_str().unwrap()}); #[doc(alias = "SOUP_SERVER_SSL_KEY_FILE")] pub static SERVER_SSL_KEY_FILE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_SSL_KEY_FILE).to_str().unwrap()}); #[cfg(any(feature = "v2_38", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))] #[doc(alias = "SOUP_SERVER_TLS_CERTIFICATE")] pub static SERVER_TLS_CERTIFICATE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SERVER_TLS_CERTIFICATE).to_str().unwrap()}); #[cfg(any(feature = "v2_30", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))] #[doc(alias = "SOUP_SESSION_ACCEPT_LANGUAGE")] pub static SESSION_ACCEPT_LANGUAGE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_ACCEPT_LANGUAGE).to_str().unwrap()}); #[cfg(any(feature = "v2_30", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))] #[doc(alias = "SOUP_SESSION_ACCEPT_LANGUAGE_AUTO")] pub static SESSION_ACCEPT_LANGUAGE_AUTO: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_ACCEPT_LANGUAGE_AUTO).to_str().unwrap()}); #[cfg(any(feature = "v2_24", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))] #[doc(alias = "SOUP_SESSION_ADD_FEATURE")] pub static SESSION_ADD_FEATURE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_ADD_FEATURE).to_str().unwrap()}); #[cfg(any(feature = "v2_24", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))] #[doc(alias = "SOUP_SESSION_ADD_FEATURE_BY_TYPE")] pub static SESSION_ADD_FEATURE_BY_TYPE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_ADD_FEATURE_BY_TYPE).to_str().unwrap()}); #[doc(alias = "SOUP_SESSION_ASYNC_CONTEXT")] pub static SESSION_ASYNC_CONTEXT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_ASYNC_CONTEXT).to_str().unwrap()}); #[cfg(any(feature = "v2_38", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))] #[doc(alias = "SOUP_SESSION_HTTPS_ALIASES")] pub static SESSION_HTTPS_ALIASES: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_HTTPS_ALIASES).to_str().unwrap()}); #[cfg(any(feature = "v2_38", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))] #[doc(alias = "SOUP_SESSION_HTTP_ALIASES")] pub static SESSION_HTTP_ALIASES: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_HTTP_ALIASES).to_str().unwrap()}); #[cfg(any(feature = "v2_24", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))] #[doc(alias = "SOUP_SESSION_IDLE_TIMEOUT")] pub static SESSION_IDLE_TIMEOUT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_IDLE_TIMEOUT).to_str().unwrap()}); #[cfg(any(feature = "v2_42", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_42")))] #[doc(alias = "SOUP_SESSION_LOCAL_ADDRESS")] pub static SESSION_LOCAL_ADDRESS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_LOCAL_ADDRESS).to_str().unwrap()}); #[doc(alias = "SOUP_SESSION_MAX_CONNS")] pub static SESSION_MAX_CONNS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_MAX_CONNS).to_str().unwrap()}); #[doc(alias = "SOUP_SESSION_MAX_CONNS_PER_HOST")] pub static SESSION_MAX_CONNS_PER_HOST: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_MAX_CONNS_PER_HOST).to_str().unwrap()}); #[doc(alias = "SOUP_SESSION_PROXY_RESOLVER")] pub static SESSION_PROXY_RESOLVER: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_PROXY_RESOLVER).to_str().unwrap()}); #[doc(alias = "SOUP_SESSION_PROXY_URI")] pub static SESSION_PROXY_URI: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_PROXY_URI).to_str().unwrap()}); #[cfg(any(feature = "v2_24", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_24")))] #[doc(alias = "SOUP_SESSION_REMOVE_FEATURE_BY_TYPE")] pub static SESSION_REMOVE_FEATURE_BY_TYPE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_REMOVE_FEATURE_BY_TYPE).to_str().unwrap()}); #[doc(alias = "SOUP_SESSION_SSL_CA_FILE")] pub static SESSION_SSL_CA_FILE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_SSL_CA_FILE).to_str().unwrap()}); #[cfg(any(feature = "v2_30", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_30")))] #[doc(alias = "SOUP_SESSION_SSL_STRICT")] pub static SESSION_SSL_STRICT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_SSL_STRICT).to_str().unwrap()}); #[cfg(any(feature = "v2_38", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))] #[doc(alias = "SOUP_SESSION_SSL_USE_SYSTEM_CA_FILE")] pub static SESSION_SSL_USE_SYSTEM_CA_FILE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_SSL_USE_SYSTEM_CA_FILE).to_str().unwrap()}); #[doc(alias = "SOUP_SESSION_TIMEOUT")] pub static SESSION_TIMEOUT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_TIMEOUT).to_str().unwrap()}); #[cfg(any(feature = "v2_38", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))] #[doc(alias = "SOUP_SESSION_TLS_DATABASE")] pub static SESSION_TLS_DATABASE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_TLS_DATABASE).to_str().unwrap()}); #[cfg(any(feature = "v2_48", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_48")))] #[doc(alias = "SOUP_SESSION_TLS_INTERACTION")] pub static SESSION_TLS_INTERACTION: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_TLS_INTERACTION).to_str().unwrap()}); #[doc(alias = "SOUP_SESSION_USER_AGENT")] pub static SESSION_USER_AGENT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_USER_AGENT).to_str().unwrap()}); #[doc(alias = "SOUP_SESSION_USE_NTLM")] pub static SESSION_USE_NTLM: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_USE_NTLM).to_str().unwrap()}); #[cfg(any(feature = "v2_38", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))] #[doc(alias = "SOUP_SESSION_USE_THREAD_CONTEXT")] pub static SESSION_USE_THREAD_CONTEXT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SESSION_USE_THREAD_CONTEXT).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_ASYNC_CONTEXT")] pub static SOCKET_ASYNC_CONTEXT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_ASYNC_CONTEXT).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_FLAG_NONBLOCKING")] pub static SOCKET_FLAG_NONBLOCKING: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_FLAG_NONBLOCKING).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_IS_SERVER")] pub static SOCKET_IS_SERVER: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_IS_SERVER).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_LOCAL_ADDRESS")] pub static SOCKET_LOCAL_ADDRESS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_LOCAL_ADDRESS).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_REMOTE_ADDRESS")] pub static SOCKET_REMOTE_ADDRESS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_REMOTE_ADDRESS).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_SSL_CREDENTIALS")] pub static SOCKET_SSL_CREDENTIALS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_SSL_CREDENTIALS).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_SSL_FALLBACK")] pub static SOCKET_SSL_FALLBACK: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_SSL_FALLBACK).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_SSL_STRICT")] pub static SOCKET_SSL_STRICT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_SSL_STRICT).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_TIMEOUT")] pub static SOCKET_TIMEOUT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_TIMEOUT).to_str().unwrap()}); #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] #[doc(alias = "SOUP_SOCKET_TLS_CERTIFICATE")] pub static SOCKET_TLS_CERTIFICATE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_TLS_CERTIFICATE).to_str().unwrap()}); #[cfg(any(feature = "v2_34", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_34")))] #[doc(alias = "SOUP_SOCKET_TLS_ERRORS")] pub static SOCKET_TLS_ERRORS: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_TLS_ERRORS).to_str().unwrap()}); #[doc(alias = "SOUP_SOCKET_TRUSTED_CERTIFICATE")] pub static SOCKET_TRUSTED_CERTIFICATE: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_TRUSTED_CERTIFICATE).to_str().unwrap()}); #[cfg(any(feature = "v2_38", feature = "dox"))] #[cfg_attr(feature = "dox", doc(cfg(feature = "v2_38")))] #[doc(alias = "SOUP_SOCKET_USE_THREAD_CONTEXT")] pub static SOCKET_USE_THREAD_CONTEXT: once_cell::sync::Lazy<&'static str> = once_cell::sync::Lazy::new(|| unsafe{CStr::from_ptr(ffi::SOUP_SOCKET_USE_THREAD_CONTEXT).to_str().unwrap()});
use sigmoid::Sigmoid; use error::*; use csv::{Reader, Writer}; use rand::thread_rng; use rand::distributions::{IndependentSample, Range}; // 过早扩展是万恶之源 pub struct Data { header: Option<Vec<String>>, records: Vec<Iris>, } impl Data { // 从文件读取 pub fn serialize(string: &str, has_header: bool) -> Result<Data> { let mut records = Reader::from_string(string).has_headers(has_header); let header: Option<Vec<String>>; if has_header { header = Some(records.headers().unwrap()); //println!("has_header"); } else { header = None; //println!("No header"); } let mut vec = Vec::<Iris>::new(); for r in records.decode() { let r: Iris = r.unwrap(); vec.push(r); } Ok(Data { header: header, records: vec, }) } // 分割测试数据 pub fn divide(&mut self, rate: f64) -> Data { let mut vec = Vec::<Iris>::new(); let size = (self.records.len() as f64 * rate) as i32; for _ in 0..size { let mut rng = thread_rng(); let range = Range::new(0, self.records.len()); let index = range.ind_sample(&mut rng); // swap_remove是O(1)操作 // remove是O(n)操作 vec.push(self.records.swap_remove(index)); } Data { header: self.header.clone(), records: vec, } } pub fn deserialize(self) -> String { let mut writer = Writer::from_memory(); for i in self.records { let result = writer.encode(i); assert!(result.is_ok()); } writer.as_string().to_owned() } // 导出为适合神经网络处理的输入矩阵 pub fn export_input(&self) -> Vec<Vec<f64>> { let mut vec = Vec::<Vec<f64>>::with_capacity(self.records.len()); for i in 0..self.records.len() { // 硬编码,待修改 let mut sample = Vec::<f64>::with_capacity(4); sample.push(self.records[i].sepal_length); sample.push(self.records[i].sepal_width); sample.push(self.records[i].petal_length); sample.push(self.records[i].petal_width); vec.push(sample); } vec } // 导出为适合神经网络处理的输出矩阵 pub fn export_output(&self, sigmoid: &Sigmoid) -> Vec<Vec<f64>> { let upper = sigmoid.get_upper(); let lower = sigmoid.get_lower(); let mut vec = Vec::<Vec<f64>>::with_capacity(self.records.len()); // 硬编码,待修改 for value in self.records.iter() { let sample: Vec<f64>; match &value.category as &str { "Iris-setosa" => sample = vec![upper, lower, lower], "Iris-versicolor" => sample = vec![lower, upper, lower], "Iris-virginica" => sample = vec![lower, lower, upper], _ => unreachable!(), } vec.push(sample); } vec } } #[derive(Debug, RustcDecodable, RustcEncodable)] pub struct Iris { sepal_length: f64, sepal_width: f64, petal_length: f64, petal_width: f64, category: String, }
use std::path::{Path, PathBuf}; use std::collections::HashMap; use std::fs::DirEntry; use vec1::Vec1; use mail::context::Source; use mail::{Resource, IRI}; use ::error::{CreatingSpecError, CreatingSpecErrorVariant}; use ::utils::{new_string_path, new_str_path}; use ::{TemplateSpec, SubTemplateSpec}; use ::settings::{LoadSpecSettings, Type}; //TODO missing global template level embeddings pub(crate) fn from_dirs( templates_dir: &Path, settings: &LoadSpecSettings ) -> Result<Vec<(String, TemplateSpec)>, CreatingSpecError> { let mut specs = Vec::new(); for entry in templates_dir.read_dir()? { let entry = entry?; if entry.metadata()?.is_dir() { let id = entry.file_name() .into_string() .map_err(|file_name| CreatingSpecErrorVariant::NonStringPath(file_name.into()))?; specs.push((id, TemplateSpec::from_dir(entry.path(), settings)?)); } } Ok(specs) } pub(crate) fn from_dir(base_path: &Path, settings: &LoadSpecSettings) -> Result<TemplateSpec, CreatingSpecError> { let mut glob_embeddings = HashMap::new(); let mut sub_template_dirs = Vec::new(); for folder in base_path.read_dir()? { let entry = folder?; if entry.file_type()?.is_dir() { let type_name = entry.file_name() .into_string().map_err(|_| CreatingSpecErrorVariant::NonStringPath(entry.path().into()))?; let (prio, type_) = settings.get_type_with_priority(&*type_name) .ok_or_else(|| CreatingSpecErrorVariant::MissingTypeInfo { type_name: type_name.clone() })?; sub_template_dirs.push((prio, entry.path(), type_)); } else { let (name, resource_spec) = embedding_from_path(entry.path(), settings)?; glob_embeddings.insert(name, resource_spec); } } sub_template_dirs.sort_by_key(|data| data.0); let mut sub_specs = Vec::with_capacity(sub_template_dirs.len()); for (_, dir_path, type_) in sub_template_dirs { sub_specs.push(sub_template_from_dir(&*dir_path, type_, settings)?); } let sub_specs = Vec1::from_vec(sub_specs) .map_err(|_| CreatingSpecErrorVariant::NoSubTemplatesFound { dir: base_path.into() })?; TemplateSpec::new_with_embeddings_and_base_path( sub_specs, glob_embeddings, base_path.to_owned()) } fn sub_template_from_dir(dir: &Path, type_: &Type, settings: &LoadSpecSettings) -> Result<SubTemplateSpec, CreatingSpecError> { let FindResult { template_file, other_files:embeddings } = find_files(dir, settings)?; let media_type = type_.to_media_type_for(&template_file)?; SubTemplateSpec::new(template_file, media_type, embeddings) } fn is_template_file(entry: &DirEntry) -> bool { entry.file_name() .to_str() .map(|name| name.starts_with("mail.")) .unwrap_or(false) } struct FindResult { template_file: PathBuf, other_files: HashMap<String, Resource>, } fn find_files(in_dir: &Path, settings: &LoadSpecSettings) -> Result<FindResult, CreatingSpecError> { use std::collections::hash_map::Entry::*; let mut template_file = None; let mut other_files = HashMap::new(); for entry in in_dir.read_dir()? { let entry = entry?; if is_template_file(&entry) { if template_file.is_none() { template_file = Some(entry.path()) } else { return Err(CreatingSpecErrorVariant::MultipleTemplateFiles { dir: in_dir.into() }.into()); } } else { let (key, value) = embedding_from_path(entry.path(), settings)?; match other_files.entry(key) { Occupied(oe) => { return Err(CreatingSpecErrorVariant::DuplicateEmbeddingName { name: oe.key().clone() }.into()); }, Vacant(ve) => {ve.insert(value);} } } } if let Some(template_file) = template_file { Ok(FindResult { template_file, other_files }) } else { Err(CreatingSpecErrorVariant::TemplateFileMissing { dir: in_dir.into() }.into()) } } fn embedding_from_path(path: PathBuf, settings: &LoadSpecSettings) -> Result<(String, Resource), CreatingSpecError> { if !path.is_file() { return Err(CreatingSpecErrorVariant::NotAFile(path.into()).into()); } let file_name = new_string_path( path.file_name() // UNWRAP_SAFE: file_name returns the file (,dir,symlink) name which // has to exist for a dir_entry .unwrap())?; let name = file_name.split(".") .next() //UNWRAP_SAFE: Split iterator has always at last one element .unwrap() .to_owned(); //TODO we can remove the media type sniffing from here let media_type = settings.determine_media_type(&path)?; let source = Source { iri: iri_from_path(path)?, use_name: None, use_media_type: Some(media_type) }; let resource = Resource::new(source); Ok((name, resource)) } fn iri_from_path<IP: AsRef<Path> + Into<PathBuf>>(path: IP) -> Result<IRI, CreatingSpecError> { { let path_ref = path.as_ref(); if let Ok(strfy) = new_str_path(&path_ref) { if let Ok(iri) = IRI::from_parts("path", strfy) { return Ok(iri) } } } Err(CreatingSpecErrorVariant::IRIConstructionFailed { scheme: "path", tail: path.into().into() }.into()) }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::collections::vec_deque::VecDeque; use super::super::super::asm::*; use super::super::super::qlib::common::*; use super::super::super::Kernel::HostSpace; use super::*; // defaultOverheadTSC is the default estimated syscall overhead in TSC cycles. // It is further refined as syscalls are made. pub const DEFAULT_OVERHEAD_CYCLES: TSCValue = 1 * 1000; // maxOverheadCycles is the maximum allowed syscall overhead in TSC cycles. pub const MAX_OVERHEAD_CYCLES: TSCValue = 100 * DEFAULT_OVERHEAD_CYCLES; // maxSampleLoops is the maximum number of times to try to get a clock sample // under the expected overhead. pub const MAX_SAMPLE_LOOPS: usize = 5; // maxSamples is the maximum number of samples to collect. pub const MAX_SAMPLES: usize = 11; // TSCValue is a value from the TSC. pub type TSCValue = i64; // ReferenceNS are nanoseconds in the reference clock domain. // int64 gives us ~290 years before this overflows. pub type ReferenceNS = i64; pub fn Magnitude(r: ReferenceNS) -> ReferenceNS { if r < 0 { return -r } return r } pub fn Sample(c: ClockID) -> Result<Sample> { let before = Rdtsc(); let time = HostSpace::KernelGetTime(c)?; if time < 0 { return Err(Error::SysError(-time as i32)); } let after = Rdtsc(); let res = Sample { Before: before, After: after, Ref: time, }; return Ok(res) } pub fn Cycles() -> TSCValue { return Rdtsc() } #[derive(Debug, Default, Copy, Clone)] pub struct Sample { pub Before: TSCValue, pub After: TSCValue, pub Ref: ReferenceNS, } impl Sample { pub fn Overhead(&self) -> TSCValue { return self.After - self.Before } } // sampler collects samples from a reference system clock, minimizing // the overhead in each sample. pub struct Sampler { // clockID is the reference clock ID (e.g., CLOCK_MONOTONIC). pub clockID: ClockID, // overhead is the estimated sample overhead in TSC cycles. pub overhead: TSCValue, // samples is a ring buffer of the latest samples collected. pub samples: VecDeque<Sample>, } impl Sampler { pub fn New(c: ClockID) -> Self { return Sampler { clockID: c, overhead: DEFAULT_OVERHEAD_CYCLES, samples: VecDeque::with_capacity(MAX_SAMPLES), } } pub fn Reset(&mut self) { self.overhead = DEFAULT_OVERHEAD_CYCLES; self.samples.clear(); } fn LowOverheadSample(&mut self) -> Result<Sample> { loop { for _i in 0..MAX_SAMPLE_LOOPS { let sample = Sample(self.clockID)?; if sample.Before > sample.After { info!("TSC went backwards: {:x} > {:x}", sample.Before, sample.After); continue; } if sample.Overhead() < self.overhead { return Ok(sample) } } let mut newOverhead = 2 * self.overhead; if newOverhead > MAX_OVERHEAD_CYCLES { if self.overhead == MAX_OVERHEAD_CYCLES { return Err(Error::Common(format!("time syscall overhead exceeds maximum, overhead is {}, MAX_OVERHEAD_CYCLES is {}, newOverhead is {}", self.overhead, MAX_OVERHEAD_CYCLES, newOverhead))); } newOverhead = MAX_OVERHEAD_CYCLES; } self.overhead = newOverhead; //info!("Time: Adjusting syscall overhead up to {}", self.overhead); } } pub fn Sample(&mut self) -> Result<()> { let sample = self.LowOverheadSample()?; if self.samples.len() == MAX_SAMPLES { self.samples.pop_front(); } self.samples.push_back(sample); // If the 4 most recent samples all have an overhead less than half the // expected overhead, adjust downwards. if self.samples.len() < 4 { return Ok(()) } for sample in self.samples.iter().skip(self.samples.len() - 4) { if sample.Overhead() > self.overhead / 2 { return Ok(()) } } self.overhead -= self.overhead / 8; //info!("Time: Adjusting syscall overhead down to {}", self.overhead); return Ok(()) } pub fn Syscall(&self) -> Result<ReferenceNS> { let sample = Sample(self.clockID)?; return Ok(sample.Ref); } pub fn Cycles(&self) -> TSCValue { return Rdtsc() } pub fn Range(&self) -> Option<(Sample, Sample)> { if self.samples.len() < 2 { return None } return Some((*self.samples.front().unwrap(), *self.samples.back().unwrap())) } }
//! Context extensions for tracing use crate::{ global, trace::{Span, SpanContext}, Context, ContextGuard, KeyValue, }; use pin_project::pin_project; use std::error::Error; use std::sync::Mutex; use std::{ borrow::Cow, pin::Pin, task::{Context as TaskContext, Poll}, }; lazy_static::lazy_static! { static ref NOOP_SPAN: SynchronizedSpan = SynchronizedSpan { span_context: SpanContext::empty_context(), inner: None, }; } /// A reference to the currently active span in this context. #[derive(Debug)] pub struct SpanRef<'a>(&'a SynchronizedSpan); #[derive(Debug)] struct SynchronizedSpan { /// Immutable span context span_context: SpanContext, /// Mutable span inner that requires synchronization inner: Option<Mutex<global::BoxedSpan>>, } impl SpanRef<'_> { fn with_inner_mut<F: FnOnce(&mut global::BoxedSpan)>(&self, f: F) { if let Some(ref inner) = self.0.inner { match inner.lock() { Ok(mut locked) => f(&mut *locked), Err(err) => global::handle_error(err), } } } } impl SpanRef<'_> { /// An API to record events in the context of a given `Span`. pub fn add_event<T>(&self, name: T, attributes: Vec<KeyValue>) where T: Into<Cow<'static, str>>, { self.with_inner_mut(|inner| inner.add_event(name, attributes)) } /// Convenience method to record an exception/error as an `Event` pub fn record_exception(&self, err: &dyn Error) { self.with_inner_mut(|inner| inner.record_exception(err)) } /// Convenience method to record a exception/error as an `Event` with custom stacktrace pub fn record_exception_with_stacktrace<T>(&self, err: &dyn Error, stacktrace: T) where T: Into<Cow<'static, str>>, { self.with_inner_mut(|inner| inner.record_exception_with_stacktrace(err, stacktrace)) } /// An API to record events at a specific time in the context of a given `Span`. pub fn add_event_with_timestamp<T>( &self, name: T, timestamp: std::time::SystemTime, attributes: Vec<crate::KeyValue>, ) where T: Into<Cow<'static, str>>, { self.with_inner_mut(move |inner| { inner.add_event_with_timestamp(name, timestamp, attributes) }) } /// Returns the `SpanContext` for the given `Span`. pub fn span_context(&self) -> &SpanContext { &self.0.span_context } /// Returns true if this `Span` is recording information like events with the `add_event` /// operation, attributes using `set_attributes`, status with `set_status`, etc. pub fn is_recording(&self) -> bool { self.0 .inner .as_ref() .and_then(|inner| inner.lock().ok().map(|active| active.is_recording())) .unwrap_or(false) } /// An API to set a single `Attribute` where the attribute properties are passed /// as arguments. To avoid extra allocations some implementations may offer a separate API for /// each of the possible value types. pub fn set_attribute(&self, attribute: crate::KeyValue) { self.with_inner_mut(move |inner| inner.set_attribute(attribute)) } /// Sets the status of the `Span`. If used, this will override the default `Span` /// status, which is `Unset`. `message` MUST be ignored when the status is `OK` or `Unset` pub fn set_status(&self, code: super::StatusCode, message: String) { self.with_inner_mut(move |inner| inner.set_status(code, message)) } /// Updates the `Span`'s name. After this update, any sampling behavior based on the /// name will depend on the implementation. pub fn update_name<T>(&self, new_name: String) where T: Into<Cow<'static, str>>, { self.with_inner_mut(move |inner| inner.update_name(new_name)) } /// Finishes the `Span`. pub fn end(&self) { self.end_with_timestamp(crate::time::now()); } /// Finishes the `Span` with given timestamp pub fn end_with_timestamp(&self, timestamp: std::time::SystemTime) { self.with_inner_mut(move |inner| inner.end_with_timestamp(timestamp)) } } /// Methods for storing and retrieving trace data in a context. pub trait TraceContextExt { /// Returns a clone of the current context with the included span. /// /// This is useful for building tracers. fn current_with_span<T: crate::trace::Span + Send + Sync + 'static>(span: T) -> Self; /// Returns a clone of this context with the included span. /// /// This is useful for building tracers. fn with_span<T: crate::trace::Span + Send + Sync + 'static>(&self, span: T) -> Self; /// Returns a reference to this context's span, or the default no-op span if /// none has been set. /// /// # Examples /// /// ``` /// use opentelemetry::{ /// sdk, /// trace::{SpanContext, TraceContextExt, Tracer, TracerProvider}, /// Context, /// }; /// /// // returns a reference to an empty span by default /// assert_eq!(Context::current().span().span_context(), &SpanContext::empty_context()); /// /// let provider = sdk::trace::TracerProvider::default(); /// provider.tracer("my-component", None).in_span("my-span", |cx| { /// // Returns a reference to the current span if set /// assert_ne!(cx.span().span_context(), &SpanContext::empty_context()); /// }); /// ``` fn span(&self) -> SpanRef<'_>; /// Used to see if a span has been marked as active /// /// This is useful for building tracers. fn has_active_span(&self) -> bool; /// Returns a copy of this context with the span context included. /// /// This is useful for building propagators. fn with_remote_span_context(&self, span_context: crate::trace::SpanContext) -> Self; } impl TraceContextExt for Context { fn current_with_span<T: crate::trace::Span + Send + Sync + 'static>(span: T) -> Self { Context::current_with_value(SynchronizedSpan { span_context: span.span_context().clone(), inner: Some(Mutex::new(global::BoxedSpan::new(span))), }) } fn with_span<T: crate::trace::Span + Send + Sync + 'static>(&self, span: T) -> Self { self.with_value(SynchronizedSpan { span_context: span.span_context().clone(), inner: Some(Mutex::new(global::BoxedSpan::new(span))), }) } fn span(&self) -> SpanRef<'_> { if let Some(span) = self.get::<SynchronizedSpan>() { SpanRef(span) } else { SpanRef(&*NOOP_SPAN) } } fn has_active_span(&self) -> bool { self.get::<SynchronizedSpan>().is_some() } fn with_remote_span_context(&self, span_context: crate::trace::SpanContext) -> Self { self.with_value(SynchronizedSpan { span_context, inner: None, }) } } /// Mark a given `Span` as active. /// /// The `Tracer` MUST provide a way to update its active `Span`, and MAY provide convenience /// methods to manage a `Span`'s lifetime and the scope in which a `Span` is active. When an /// active `Span` is made inactive, the previously-active `Span` SHOULD be made active. A `Span` /// maybe finished (i.e. have a non-null end time) but still be active. A `Span` may be active /// on one thread after it has been made inactive on another. /// /// # Examples /// /// ``` /// use opentelemetry::{global, trace::{Span, Tracer}, KeyValue}; /// use opentelemetry::trace::{get_active_span, mark_span_as_active}; /// /// fn my_function() { /// let tracer = global::tracer("my-component-a"); /// // start an active span in one function /// let span = tracer.start("span-name"); /// let _guard = mark_span_as_active(span); /// // anything happening in functions we call can still access the active span... /// my_other_function(); /// } /// /// fn my_other_function() { /// // call methods on the current span from /// get_active_span(|span| { /// span.add_event("An event!".to_string(), vec![KeyValue::new("happened", true)]); /// }); /// } /// ``` #[must_use = "Dropping the guard detaches the context."] pub fn mark_span_as_active<T: crate::trace::Span + Send + Sync + 'static>(span: T) -> ContextGuard { let cx = Context::current_with_span(span); cx.attach() } /// Executes a closure with a reference to this thread's current span. /// /// # Examples /// /// ``` /// use opentelemetry::{global, trace::{Span, Tracer}, KeyValue}; /// use opentelemetry::trace::get_active_span; /// /// fn my_function() { /// // start an active span in one function /// global::tracer("my-component").in_span("span-name", |_cx| { /// // anything happening in functions we call can still access the active span... /// my_other_function(); /// }) /// } /// /// fn my_other_function() { /// // call methods on the current span from /// get_active_span(|span| { /// span.add_event("An event!".to_string(), vec![KeyValue::new("happened", true)]); /// }) /// } /// ``` pub fn get_active_span<F, T>(f: F) -> T where F: FnOnce(SpanRef<'_>) -> T, { f(Context::current().span()) } /// A future, stream, or sink that has an associated context. #[pin_project] #[derive(Clone, Debug)] pub struct WithContext<T> { #[pin] inner: T, otel_cx: Context, } impl<T: Sized> FutureExt for T {} impl<T: std::future::Future> std::future::Future for WithContext<T> { type Output = T::Output; fn poll(self: Pin<&mut Self>, task_cx: &mut TaskContext<'_>) -> Poll<Self::Output> { let this = self.project(); let _guard = this.otel_cx.clone().attach(); this.inner.poll(task_cx) } } impl<T: futures::Stream> futures::Stream for WithContext<T> { type Item = T::Item; fn poll_next(self: Pin<&mut Self>, task_cx: &mut TaskContext<'_>) -> Poll<Option<Self::Item>> { let this = self.project(); let _guard = this.otel_cx.clone().attach(); T::poll_next(this.inner, task_cx) } } impl<I, T: futures::Sink<I>> futures::Sink<I> for WithContext<T> where T: futures::Sink<I>, { type Error = T::Error; fn poll_ready( self: Pin<&mut Self>, task_cx: &mut TaskContext<'_>, ) -> Poll<Result<(), Self::Error>> { let this = self.project(); let _guard = this.otel_cx.clone().attach(); T::poll_ready(this.inner, task_cx) } fn start_send(self: Pin<&mut Self>, item: I) -> Result<(), Self::Error> { let this = self.project(); let _guard = this.otel_cx.clone().attach(); T::start_send(this.inner, item) } fn poll_flush( self: Pin<&mut Self>, task_cx: &mut TaskContext<'_>, ) -> Poll<Result<(), Self::Error>> { let this = self.project(); let _guard = this.otel_cx.clone().attach(); T::poll_flush(this.inner, task_cx) } fn poll_close( self: Pin<&mut Self>, task_cx: &mut TaskContext<'_>, ) -> futures::task::Poll<Result<(), Self::Error>> { let this = self.project(); let _enter = this.otel_cx.clone().attach(); T::poll_close(this.inner, task_cx) } } /// Extension trait allowing futures, streams, and sinks to be traced with a span. pub trait FutureExt: Sized { /// Attaches the provided [`Context`] to this type, returning a `WithContext` /// wrapper. /// /// When the wrapped type is a future, stream, or sink, the attached context /// will be set as current while it is being polled. /// /// [`Context`]: crate::Context fn with_context(self, otel_cx: Context) -> WithContext<Self> { WithContext { inner: self, otel_cx, } } /// Attaches the current [`Context`] to this type, returning a `WithContext` /// wrapper. /// /// When the wrapped type is a future, stream, or sink, the attached context /// will be set as the default while it is being polled. /// /// [`Context`]: crate::Context fn with_current_context(self) -> WithContext<Self> { let otel_cx = Context::current(); self.with_context(otel_cx) } }
use std::io; use std::io::Read; fn main() { let mut input = String::new(); io::stdin().read_to_string(&mut input).unwrap(); let mut joltages: Vec<u8> = input.lines().map(|x| x.parse().unwrap()).collect(); joltages.push(0); // Outlet joltages.sort_unstable(); joltages.push(joltages[joltages.len() - 1] + 3); // Device let (ones, threes) = joltages[1..].iter().zip(joltages.iter()).fold((0, 0), |(ones, threes), (a, b)| match a - b { 1 => (ones + 1, threes), 3 => (ones, threes + 1), _ => (ones, threes), }); println!("{}", ones * threes); }
//! Sending and receiving slices of bytes. //! //! ## Example usage from a std crate //! //! See the `decode_*` and `encode_*` functions for simple uses with //! various input and output types. //! //! The `Sender` struct writes encoded payloads to an //! inner `std::io::Write` instance, and the `Receiver` struct reads //! and decodes payloads from an inner `std::io::Read` instance. //! //! ```rust //! # use framed::*; //! # use framed::bytes::*; //! # use std::io::Cursor; //! # //! let mut config = Config::default(); //! //! let payload = [1, 2, 3]; //! //! let mut encoded = vec![]; //! { //! let mut sender = config.clone().to_sender(&mut encoded); //! sender.send(&payload).expect("send ok"); //! } //! //! // `encoded` now contains the encoded frame. //! //! let mut receiver = config.clone().to_receiver(Cursor::new(encoded)); //! let decoded = receiver.recv().expect("recv ok"); //! //! assert_eq!(payload, *decoded); //! ``` //! //! ## Example usage from a no_std crate //! //! The `encode_to_slice` and `decode_from_slice` functions offer an //! API for `no_std` crates that do not have a heap allocator //! available and cannot use `std::io::Read` or `std::io::Write`. //! //! ```rust //! # use framed::*; //! # use framed::bytes::*; //! # //! let mut codec = Config::default().to_codec(); //! //! // In a no_std crate without dynamic memory allocation we would typically //! // know the maximum payload length, which we can use for payload buffers. //! const MAX_PAYLOAD_LEN: usize = 10; //! //! // The maximum payload length implies a maximum encoded frame length, //! // which we can use for frame buffers. //! // //! // Using a calculated frame buffer length like this requires //! // const fn, which is currently unstable and only available on nightly rust. //! // Enable cargo feature flag "use_nightly" to use it. //! const MAX_FRAME_LEN: usize = max_encoded_len(MAX_PAYLOAD_LEN); //! //! let payload: [u8; 3] = [1, 2, 3]; //! assert!(payload.len() <= MAX_PAYLOAD_LEN); //! //! let mut encoded_buf = [0u8; MAX_FRAME_LEN]; //! let encoded_len = codec.encode_to_slice(&payload, &mut encoded_buf) //! .expect("encode ok"); //! let encoded = &encoded_buf[0..encoded_len]; //! //! // `encoded` now contains the encoded frame. //! //! let mut decoded_buf = [0u8; MAX_PAYLOAD_LEN]; //! let decoded_len = codec.decode_to_slice(&encoded, &mut decoded_buf) //! .expect("decode ok"); //! let decoded = &decoded_buf[0..decoded_len]; //! //! assert_eq!(payload, *decoded); //! ``` //! // ## use statements use ::{Payload, Encoded, FRAME_END_SYMBOL}; #[cfg(feature = "use_std")] use ::{BoxPayload, BoxEncoded}; use ::checksum::MAX_CHECKSUM_LEN; use ::error::{Error, Result}; use ::typed; use cobs; use serde::Serialize; use serde::de::DeserializeOwned; #[cfg(feature = "use_std")] use ref_slice::ref_slice_mut; #[cfg(feature = "use_std")] use std::io::{self, Read, Write}; pub use ::checksum::Checksum; /// Contains methods for encoding and decoding byte slices with a /// specific configuration. /// /// Construct an instance from a `Config` instance with the /// `Config::to_codec` method. pub struct Codec { config: Config } /// Configurable options for encoding and decoding byte slices using a /// builder pattern. /// /// Construct an instance with `Config::default()`. #[derive(Clone, Debug, Default)] pub struct Config { checksum: Checksum, } impl Config { /// Construct a `Codec` instance with this configuration. pub fn to_codec(&mut self) -> Codec { Codec { config: self.clone(), } } #[cfg(feature = "use_std")] /// Construct a `Receiver` instance with this configuration. pub fn to_receiver<R: Read>(&mut self, r: R) -> Receiver<R> { Receiver::<R> { codec: self.to_codec(), r: r, } } #[cfg(feature = "use_std")] /// Construct a `Sender` instance with this configuration. pub fn to_sender<W: Write>(&mut self, w: W) -> Sender<W> { Sender::<W> { codec: self.to_codec(), w: w, } } /// Construct a `framed::typed::Config` instance to encode and decode a /// serializable type `T` with this byte encoding configuration. pub fn typed<T: DeserializeOwned + Serialize>(&mut self) -> typed::Config<T> { typed::Config::<T>::new(self) } /// Get the current checksum configuration. pub fn checksum(&self) -> &Checksum { &self.checksum } /// Set the checksum configuration. pub fn set_checksum(&mut self, checksum: Checksum) -> &mut Self { self.checksum = checksum; self } } const MAX_FRAMING_LEN: usize = MAX_CHECKSUM_LEN + 1; impl Codec { fn checksum(&self) -> &Checksum { &self.config.checksum } fn min_frame_len(&self) -> usize { 0 // payload length + self.checksum().len() + 1 // sentinel length } /// Encode the supplied payload data as a frame at the beginning of /// the supplied buffer `dest`. Available from `no_std` crates. /// /// Returns the number of bytes it has written to the buffer. /// /// # Panics /// /// This function will panic if `dest` is not large enough for the encoded frame. /// Ensure `dest.len() >= max_encoded_len(p.len())`. pub fn encode_to_slice(&mut self, p: &Payload, dest: &mut Encoded) -> Result<usize> { // Panic if encoded frame won't fit in `dest` because this is a // programmer error. assert!(max_encoded_len(p.len()) <= dest.len()); #[cfg(feature = "trace")] { println!("framed::encode: Payload = {:?}", p); } let checksum_type = self.checksum(); let checksum_value = checksum_type.calculate(p); let cobs_len = { let mut cobs_enc = cobs::CobsEncoder::new(dest); cobs_enc.push(p) .map_err(|_| Error::CobsEncodeFailed)?; if checksum_value.len() > 0 { cobs_enc.push(&*checksum_value) .map_err(|_| Error::CobsEncodeFailed)?; } let cobs_len = cobs_enc.finalize() .map_err(|_| Error::CobsEncodeFailed)?; cobs_len }; dest[cobs_len] = FRAME_END_SYMBOL; // len is cobs_len + len(FRAME_END_SYMBOL) let len = cobs_len + 1; #[cfg(feature = "trace")] { println!("framed::encode: Frame = {:?}", &dest[0..len]); } Ok(len) } /// Encode the supplied payload data as a frame and return it on the heap. #[cfg(feature = "use_std")] pub fn encode_to_box(&mut self, p: &Payload) -> Result<BoxEncoded> { let mut buf = vec![0; max_encoded_len(p.len())]; let len = self.encode_to_slice(p, &mut *buf)?; buf.truncate(len); Ok(BoxEncoded::from(buf)) } /// Encode the supplied payload data as a frame and write it to the /// supplied `Write`. /// /// This function will not call `flush` on the writer; the caller must do /// so if this is required. /// /// Returns the length of the frame it has written. #[cfg(feature = "use_std")] pub fn encode_to_writer<W: Write>(&mut self, p: &Payload, w: &mut W) -> Result<usize> { let b = self.encode_to_box(p)?; w.write_all(&*b.0)?; Ok(b.len()) } /// Decode the supplied encoded frame, placing the payload at the /// beginning of the supplied buffer `dest`. Available from `no_std` crates. /// /// When reading from a stream, the caller can continue reading data /// and buffering it until a `FRAME_END_SYMBOL` is read, then pass the /// whole buffer including `FRAME_END_SYMBOL` to this function for /// decoding. /// /// If there is more than 1 FRAME_END_SYMBOL within `e`, the result /// is undefined. Make sure you only pass 1 frame at a time. /// /// Returns the length of the payload it has decoded. /// /// # Errors /// /// Returns `Err(Error::EofDuringFrame`) if `e` contains >= 1 bytes of /// a frame, but not a complete frame. A complete frame should have /// `FRAME_END_SYMBOL` as the last byte. /// /// Returns `Err(Error::EofBeforeFrame`) if `e.len()` is 0. /// /// # Panics /// /// This function will panic if `dest` is not large enough for the decoded frame. /// Ensure `dest.len() >= e.len()`. pub fn decode_to_slice(&mut self, e: &Encoded, dest: &mut [u8]) -> Result<usize> { #[cfg(feature = "trace")] { println!("framed::decode: Encoded = {:?}", e); } if e.len() == 0 { return Err(Error::EofBeforeFrame); } if e.len() < self.min_frame_len() { return Err(Error::EofDuringFrame); } if e[e.len()-1] != FRAME_END_SYMBOL { return Err(Error::EofDuringFrame) } assert!(dest.len() >= max_decoded_len(e.len())); assert_eq!(e[e.len() - 1], FRAME_END_SYMBOL); let cobs_payload = &e[0..e.len() - 1]; let cobs_decoded_len = if cobs_payload.len() == 0 { 0 } else { cobs::decode(cobs_payload, dest) .map_err(|_| Error::CobsDecodeFailed)? }; let cobs_decoded = &dest[0..cobs_decoded_len]; if cobs_decoded_len < self.checksum().len() { return Err(Error::EofDuringFrame); } let payload = &cobs_decoded[0..cobs_decoded_len - self.checksum().len()]; #[cfg(feature = "trace")] { println!("framed::decode: cobs_decoded = {:?}", cobs_decoded); println!("framed::decode: payload = {:?}", payload); } let checksum = self.checksum(); let calc_checksum = checksum.calculate(payload); let recv_checksum = &cobs_decoded[payload.len() .. payload.len() + checksum.len()]; #[cfg(feature = "trace")] { println!("framed::decode: calc_checksum = {:?}\n\ framed::decode: recv_checksum = {:?}", calc_checksum, recv_checksum); } if &*calc_checksum != recv_checksum { return Err(Error::ChecksumError); } Ok(payload.len()) } /// Decode the supplied encoded frame, returning the payload on the heap. #[cfg(feature = "use_std")] pub fn decode_to_box(&mut self, e: &Encoded) -> Result<BoxPayload> { if e.len() == 0 { return Err(Error::EofBeforeFrame); } let mut buf = vec![0; max_decoded_len(e.len())]; let len = self.decode_to_slice(e, &mut buf)?; buf.truncate(len); Ok(BoxPayload::from(buf)) } /// Reads bytes from the supplied `Read` until it has a complete /// encoded frame, then decodes the frame, returning the payload on the heap. #[cfg(feature = "use_std")] pub fn decode_from_reader<R: Read>(&mut self, r: &mut dyn Read) -> Result<BoxPayload> { // Read until FRAME_END_SYMBOL let mut next_frame = Vec::new(); let mut b = 0u8; loop { let res = r.read(ref_slice_mut(&mut b)); #[cfg(feature = "trace")] { println!("framed: Read result = {:?}", res); } match res { // In the 2 EOF cases defer to decode_to_box to return the // correct error (EofBeforeFrame or EofDuringFrame). Err(ref e) if e.kind() == io::ErrorKind::UnexpectedEof => return self.decode_to_box(&*next_frame), Ok(0) => return self.decode_to_box(&*next_frame), Err(e) => return Err(Error::from(e)), Ok(1) => (), Ok(_) => unreachable!(), }; #[cfg(feature = "trace")] { println!("framed: Read byte = {}", b); } next_frame.push(b); if b == FRAME_END_SYMBOL { break; } } assert_eq!(next_frame[next_frame.len()-1], FRAME_END_SYMBOL); self.decode_to_box(&*next_frame) } } // End of impl Codec. const_fn! { /// Returns an upper bound for the decoded length of the payload /// within a frame with the encoded length supplied. /// /// Useful for calculating an appropriate buffer length. pub fn max_decoded_len(code_len: usize) -> usize { // This is an over-estimate of the required decoded buffer, but // wasting MAX_HEADER_LEN + MAX_FOOTER_LEN bytes should be acceptable and // we can calculate this trivially in a const fn. code_len } } const_fn! { /// Returns an upper bound for the encoded length of a frame with /// the payload length supplied. /// /// Useful for calculating an appropriate buffer length. pub fn max_encoded_len(payload_len: usize) -> usize { MAX_FRAMING_LEN + cobs_max_encoded_len(payload_len) } } const_fn! { /// Copied from `cobs` crate and modified to make a `const` version. /// /// Source: https://github.com/awelkie/cobs.rs/blob/f8ff1ad2aa7cd069a924d75170d3def3fa6df10b/src/lib.rs#L183-L188 /// /// TODO: Submit a PR to `cobs` to make `cobs::max_encoding_length` a `const fn`. /// Issue for this: https://github.com/fluffysquirrels/framed-rs/issues/19 fn cobs_max_encoded_len(payload_len: usize) -> usize { payload_len + (payload_len / 254) // This `+ 1` was // `+ if payload_len % 254 > 0 { 1 } else { 0 }` in cobs.rs, // but that won't compile in a const fn. `1` is less than both the // values in the if and else branches, so use that instead, with the // acceptable cost of allocating 1 byte more than required some of the // time. + 1 } } /// Sends encoded frames over an inner `std::io::Write` instance. /// /// Construct an instance using the method `Config::to_sender` #[cfg(feature = "use_std")] pub struct Sender<W: Write> { codec: Codec, w: W, } #[cfg(feature = "use_std")] impl<W: Write> Sender<W> { /// Consume this `Sender` and return the inner `std::io::Write`. pub fn into_inner(self) -> W { self.w } /// Flush all buffered data. Includes calling `flush` on the inner /// writer. pub fn flush(&mut self) -> Result<()> { Ok(self.w.flush()?) } /// Queue the supplied payload for transmission. /// /// This `Sender` may buffer the data indefinitely, as may the /// inner writer. To ensure all buffered data has been /// transmitted call [`flush`](#method.flush). /// /// See also: [`send`](#method.send) pub fn queue(&mut self, p: &Payload) -> Result<usize> { self.codec.encode_to_writer(p, &mut self.w) } /// Encode the supplied payload as a frame, write it to the /// inner writer, then flush. /// /// Ensures the data has been transmitted before returning to the /// caller. /// /// See also: [`queue`](#method.queue) pub fn send(&mut self, p: &Payload) -> Result<usize> { let len = self.queue(p)?; self.flush()?; Ok(len) } } /// Receives encoded frames from an inner `std::io::Read` instance. /// /// Construct an instance using the method `Config::to_receiver` #[cfg(feature = "use_std")] pub struct Receiver<R: Read> { codec: Codec, r: R, } #[cfg(feature = "use_std")] impl<R: Read> Receiver<R> { /// Consume this `Receiver` and return the inner `io::Read`. pub fn into_inner(self) -> R { self.r } /// Receive an encoded frame from the inner `io::Read`, decode it /// and return the payload. pub fn recv(&mut self) -> Result<BoxPayload> { self.codec.decode_from_reader::<R>(&mut self.r) } } #[cfg(test)] mod tests { #[cfg(feature = "use_std")] use std::io::Cursor; use super::*; #[test] fn max_encoded_len_ok() { assert_eq!(max_encoded_len(0) , 4); assert_eq!(max_encoded_len(1) , 5); assert_eq!(max_encoded_len(2) , 6); assert_eq!(max_encoded_len(254), 259); assert_eq!(max_encoded_len(255), 260); } #[test] fn max_decoded_len_ok() { assert_eq!(max_decoded_len(0) , 0); assert_eq!(max_decoded_len(1) , 1); assert_eq!(max_decoded_len(2) , 2); assert_eq!(max_decoded_len(3) , 3); assert_eq!(max_decoded_len(255), 255); } fn codec() -> Codec { Config::default().to_codec() } // A test payload. const PAYLOAD: [u8; PAYLOAD_LEN] = [0, 1, 2, 3]; const PAYLOAD_LEN: usize = 4; const ENCODED_LEN: usize = 9; /// Returns an encoded frame with payload PAYLOAD. fn encoded_payload(buf: &mut [u8; ENCODED_LEN]) -> &[u8] { let len = codec().encode_to_slice(&PAYLOAD, buf).unwrap(); &buf[0..len] } fn assert_payload_eq(encoded: &Encoded, payload: &Payload) { #[cfg(feature = "use_std")] { println!("assert_payload_eq \n\ - encoded = {:?}\n\ - payload = {:?}", encoded, payload); } let mut decoded_buf = [0; 100]; let len = codec().decode_to_slice(encoded, &mut decoded_buf).unwrap(); let decoded = &decoded_buf[0..len]; assert_eq!(decoded, payload); } #[test] #[should_panic] fn encode_to_slice_dest_too_small() { let mut encoded_buf = [0u8; PAYLOAD_LEN]; let _ = codec().encode_to_slice(&PAYLOAD, &mut encoded_buf); } #[test] #[cfg(feature = "use_std")] fn encode_to_slice_ok_dynamic_dest() { let mut encoded_buf = vec![0u8; max_encoded_len(PAYLOAD.len())]; let len = codec().encode_to_slice(&PAYLOAD, &mut *encoded_buf).unwrap(); let encoded = &encoded_buf[0..len]; assert_payload_eq(encoded, &PAYLOAD); } // use_nightly required for statically allocated buffer #[test] #[cfg(feature = "use_nightly")] fn encode_to_slice_ok_static_dest() { let mut encoded_buf = [0u8; max_encoded_len(PAYLOAD_LEN)]; let len = codec().encode_to_slice(&PAYLOAD, &mut encoded_buf).unwrap(); let encoded = &encoded_buf[0..len]; assert_payload_eq(encoded, &PAYLOAD); } #[test] #[cfg(feature = "use_std")] fn encode_to_writer_ok() { let mut encoded = vec![]; codec().encode_to_writer(&PAYLOAD, &mut encoded).unwrap(); assert_payload_eq(&*encoded, &PAYLOAD); } #[test] #[should_panic] fn decode_to_slice_dest_too_small() { let mut buf = [0; ENCODED_LEN]; let encoded = encoded_payload(&mut buf); let mut decoded_buf = [0u8; PAYLOAD_LEN - 1]; let _ = codec().decode_to_slice(&*encoded, &mut decoded_buf); } #[test] #[cfg(feature = "use_std")] fn decode_to_slice_ok_dynamic_dest() { let encoded = codec().encode_to_box(&PAYLOAD).unwrap(); let mut decoded_buf = vec![0u8; max_decoded_len(encoded.len())]; let len = codec().decode_to_slice(&*encoded, &mut decoded_buf).unwrap(); let decoded = &decoded_buf[0..len]; assert_eq!(&PAYLOAD, decoded); } #[test] #[cfg(feature = "use_std")] fn decode_to_slice_no_end_symbol() { let encoded = vec![FRAME_END_SYMBOL + 1; max_encoded_len(0)]; let mut decoded_buf = []; let res = codec().decode_to_slice(&*encoded, &mut decoded_buf); match res { Err(Error::EofDuringFrame) => (), _ => panic!("Bad output: {:?}", res), } } #[test] #[cfg(feature = "use_std")] fn decode_to_slice_encoded_too_short() { let mut c = codec(); let encoded = vec![FRAME_END_SYMBOL; c.min_frame_len() - 1]; let mut decoded_buf = []; let res = c.decode_to_slice(&*encoded, &mut decoded_buf); match res { Err(Error::EofDuringFrame) => (), _ => panic!("Bad output: {:?}", res), } } #[test] #[cfg(feature = "use_std")] fn decode_to_slice_encoded_empty() { let encoded = vec![]; let mut decoded_buf = []; let res = codec().decode_to_slice(&*encoded, &mut decoded_buf); match res { Err(Error::EofBeforeFrame) => (), _ => panic!("Bad output: {:?}", res), } } #[test] #[cfg(feature = "use_std")] fn decode_to_slice_bad_checksum() { let mut c = codec(); let encoded = c.encode_to_box(&PAYLOAD).unwrap(); let mut encoded = Vec::from(&*encoded); let checksum_offset = encoded.len() - c.checksum().len() - 1; { let checksum = &mut encoded[checksum_offset.. (checksum_offset + c.config.checksum.len())]; checksum[0] = checksum[0].wrapping_add(1); checksum[1] = checksum[1].wrapping_add(2); } let mut decoded_buf = vec![0u8; max_decoded_len(encoded.len())]; let res = codec().decode_to_slice(&*encoded, &mut decoded_buf); match res { Err(Error::ChecksumError) => (), _ => panic!("Bad output: {:?}", res), } } #[test] #[cfg(feature = "use_std")] fn decode_to_slice_missing_bytes() { let encoded = codec().encode_to_box(&PAYLOAD).unwrap(); let encoded = &encoded[1..encoded.len()]; let mut decoded_buf = vec![0u8; max_decoded_len(encoded.len())]; let res = codec().decode_to_slice(&*encoded, &mut decoded_buf); match res { Err(Error::ChecksumError) => (), _ => panic!("Bad output: {:?}", res), } } #[test] #[cfg(feature = "use_std")] fn decode_to_box_ok() { let encoded = codec().encode_to_box(&PAYLOAD).unwrap(); let decoded = codec().decode_to_box(&*encoded).unwrap(); assert_eq!(&PAYLOAD, &*decoded); } #[test] #[cfg(feature = "use_std")] fn decode_from_reader_ok() { let mut c = codec(); let encoded = c.encode_to_box(&PAYLOAD).unwrap(); let mut reader = Cursor::new(&*encoded); let decoded = c.decode_from_reader::<Cursor<&[u8]>>(&mut reader).unwrap(); assert_eq!(&*decoded, &PAYLOAD); } #[test] #[cfg(feature = "use_std")] fn roundtrip_default_config() { roundtrip_case(&mut Config::default() .to_codec(), &PAYLOAD) } #[test] #[cfg(feature = "use_std")] fn roundtrip_no_checksum() { roundtrip_case(&mut Config::default() .set_checksum(Checksum::None) .to_codec(), &PAYLOAD) } #[test] #[cfg(feature = "use_std")] fn roundtrip_empty_payload() { roundtrip_case(&mut Config::default() .to_codec(), &[]) } #[cfg(feature = "use_std")] fn roundtrip_case(c: &mut Codec, payload: &Payload) { let encoded = c.encode_to_box(payload); println!("encoded: {:?}", encoded); let encoded = encoded.unwrap(); let decoded = c.decode_to_box(&*encoded); println!("decoded: {:?}", decoded); let decoded = decoded.unwrap(); assert_eq!(&*decoded, payload); } } #[cfg(all(test, feature = "use_std"))] mod rw_tests { use channel::Channel; use error::Error; use std::io::{Read, Write}; use super::*; #[test] fn one_frame() { let (mut tx, mut rx) = pair(); let p = [0x00, 0x01, 0x02]; tx.send(&p).unwrap(); let recvd = rx.recv().unwrap(); assert_eq!(*recvd, p); } #[test] fn two_frames_sequentially() { let (mut tx, mut rx) = pair(); { let sent = [0x00, 0x01, 0x02]; tx.send(&sent).unwrap(); let recvd = rx.recv().unwrap(); assert_eq!(*recvd, sent); } { let sent = [0x10, 0x11, 0x12]; tx.send(&sent).unwrap(); let recvd = rx.recv().unwrap(); assert_eq!(*recvd, sent); } } #[test] fn two_frames_at_once() { let (mut tx, mut rx) = pair(); let s1 = [0x00, 0x01, 0x02]; let s2 = [0x10, 0x11, 0x12]; tx.send(&s1).unwrap(); tx.send(&s2).unwrap(); let r1 = rx.recv().unwrap(); let r2 = rx.recv().unwrap(); println!("r1: {:?}\n\ r2: {:?}", r1, r2); assert_eq!(*r1, s1); assert_eq!(*r2, s2); } #[test] fn empty_input() { let (mut _tx, mut rx) = pair(); match rx.recv() { Err(Error::EofBeforeFrame) => (), e @ _ => panic!("Bad value: {:?}", e) } } #[test] fn partial_input() { let chan = Channel::new(); let mut rx = config().to_receiver(chan.reader()); let mut tx_raw = chan.writer(); tx_raw.write(&[0x01]).unwrap(); match rx.recv() { Err(Error::EofDuringFrame) => (), e @ _ => panic!("Bad value: {:?}", e) } } fn config() -> Config { Config::default() } fn pair() -> (Sender<Box<dyn Write>>, Receiver<Box<dyn Read>>) { let chan = Channel::new(); let c = config(); let tx = c.clone().to_sender(Box::new(chan.writer()) as Box<dyn Write>); let rx = c.clone().to_receiver(Box::new(chan.reader()) as Box<dyn Read>); (tx, rx) } }
use super::Part; use crate::codec::{Decode, Encode}; use crate::{remote_type, RemoteObject}; remote_type!( /// A launch clamp. Obtained by calling `Part::launch_clamp().` object SpaceCenter.LaunchClamp { properties: { { Part { /// Returns the part object for this launch clamp. /// /// **Game Scenes**: All get: part -> Part } } } methods: { { /// Releases the docking clamp. Has no effect if the clamp has already been released. /// /// **Game Scenes**: All fn release() { Release() } } } });
use super::group_indices; use petgraph::graph::{Graph, IndexType, NodeIndex}; use petgraph::EdgeType; use petgraph_layout_force_simulation::{Force, Point, MIN_DISTANCE}; use std::collections::HashMap; #[derive(Copy, Clone)] pub struct GroupManyBodyForceArgument { pub group: usize, pub strength: Option<f32>, } pub struct GroupManyBodyForce { groups: HashMap<usize, Vec<usize>>, strength: Vec<f32>, } impl GroupManyBodyForce { pub fn new< N, E, Ty: EdgeType, Ix: IndexType, F: FnMut(&Graph<N, E, Ty, Ix>, NodeIndex<Ix>) -> GroupManyBodyForceArgument, >( graph: &Graph<N, E, Ty, Ix>, mut accessor: F, ) -> GroupManyBodyForce { let mut groups = vec![]; let mut strength = vec![]; for u in graph.node_indices() { let arg = accessor(graph, u); groups.push(arg.group); strength.push(if let Some(value) = arg.strength { value } else { -30. }); } let groups = group_indices(&groups); GroupManyBodyForce { groups, strength } } } impl Force for GroupManyBodyForce { fn apply(&self, points: &mut [Point], alpha: f32) { for indices in self.groups.values() { let n = indices.len(); for i in 0..n { let a = indices[i]; let x0 = points[a].x; let y0 = points[a].y; let mut dvx = 0.; let mut dvy = 0.; for j in 0..n { if i == j { continue; } let b = indices[j]; let strength = self.strength[b]; let dx = points[b].x - x0; let dy = points[b].y - y0; let l = (dx * dx + dy * dy).max(MIN_DISTANCE); dvx += dx * strength * alpha / l; dvy += dy * strength * alpha / l; } points[a].vx += dvx; points[a].vy += dvy } } } }
use core::{cell::RefCell, usize}; use cortex_m::interrupt::{CriticalSection, Mutex}; #[derive(Debug, Clone, Copy, defmt::Format)] pub enum InterruptEvent { Tick, Encoder(i8), ShortPress, LongPress, Alarm, } /// Inner implementation for EventQueue protected by a Mutex for inner mutability #[derive(Debug)] struct EventQueueInner<const N: usize> { queue: [Option<InterruptEvent>; N], head: usize, tail: usize, } /// A queue that stores `InterruptEvent` and provides inner mutability to the /// queue itrustupef, as long as a `CriticalSection` is passed as an argument to most functions. // #[derive(Debug)] pub struct EventQueue<const N: usize> { inner: Mutex<RefCell<EventQueueInner<N>>>, } #[allow(dead_code)] impl<const N: usize> EventQueue<N> { pub const fn new() -> Self { EventQueue { inner: Mutex::new(RefCell::new(EventQueueInner { queue: [None; N], head: 0, tail: 0, })), } } pub fn take(&self, cs: &CriticalSection) -> Option<InterruptEvent> { let mut inner = self.inner.borrow(cs).borrow_mut(); let head = inner.head; let evt = inner.queue[head].take()?; inner.head += 1; if inner.head >= inner.queue.len() { inner.head = 0; } Some(evt) } pub fn put(&self, cs: &CriticalSection, evt: InterruptEvent) { let mut inner = self.inner.borrow(cs).borrow_mut(); let tail = inner.tail; inner.queue[tail] = Some(evt); inner.tail += 1; if inner.tail >= inner.queue.len() { inner.tail = 0; } } pub fn count(&self, cs: &CriticalSection) -> usize { let inner = self.inner.borrow(cs).borrow(); inner.tail.wrapping_sub(inner.head) } }
use super::helpers::subtract_reuse_lhs; use crate::{integer::Integer, rational::Rational}; use core::ops::Sub; // Sub The subtraction operator -. // ['Rational', 'Rational', 'Rational', 'Rational::subtract_assign', 'lhs', // ['ref_mut'], ['ref']] impl Sub<Rational> for Rational { type Output = Rational; fn sub(mut self, rhs: Rational) -> Self::Output { Rational::subtract_assign(&mut self, &rhs); self } } // ['Rational', '&Rational', 'Rational', 'Rational::subtract_assign', 'lhs', // ['ref_mut'], []] impl Sub<&Rational> for Rational { type Output = Rational; fn sub(mut self, rhs: &Rational) -> Self::Output { Rational::subtract_assign(&mut self, rhs); self } } // ['&Rational', 'Rational', 'Rational', 'Rational::subtract', 'no', [], // ['ref']] impl Sub<Rational> for &Rational { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { Rational::subtract(self, &rhs) } } // ['&Rational', '&Rational', 'Rational', 'Rational::subtract', 'no', [], []] impl Sub<&Rational> for &Rational { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { Rational::subtract(self, rhs) } } // ['Rational', 'Integer', 'Rational', 'Rational::subtract_assign_integer', // 'lhs', ['ref_mut'], ['ref']] impl Sub<Integer> for Rational { type Output = Rational; fn sub(mut self, rhs: Integer) -> Self::Output { Rational::subtract_assign_integer(&mut self, &rhs); self } } // ['Rational', '&Integer', 'Rational', 'Rational::subtract_assign_integer', // 'lhs', ['ref_mut'], []] impl Sub<&Integer> for Rational { type Output = Rational; fn sub(mut self, rhs: &Integer) -> Self::Output { Rational::subtract_assign_integer(&mut self, rhs); self } } // ['&Rational', 'Integer', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref']] impl Sub<Integer> for &Rational { type Output = Rational; fn sub(self, rhs: Integer) -> Self::Output { Rational::subtract_integer(self, &rhs) } } // ['&Rational', '&Integer', 'Rational', 'Rational::subtract_integer', 'no', [], // []] impl Sub<&Integer> for &Rational { type Output = Rational; fn sub(self, rhs: &Integer) -> Self::Output { Rational::subtract_integer(self, rhs) } } // ['Integer', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for Integer { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['Integer', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for Integer { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&Integer', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &Integer { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&Integer', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &Integer { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'i8', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<i8> for Rational { type Output = Rational; fn sub(mut self, rhs: i8) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&i8', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i8> for Rational { type Output = Rational; fn sub(mut self, rhs: &i8) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'i8', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<i8> for &Rational { type Output = Rational; fn sub(self, rhs: i8) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&i8', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i8> for &Rational { type Output = Rational; fn sub(self, rhs: &i8) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['i8', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for i8 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['i8', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for i8 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&i8', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &i8 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&i8', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &i8 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'u8', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<u8> for Rational { type Output = Rational; fn sub(mut self, rhs: u8) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&u8', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u8> for Rational { type Output = Rational; fn sub(mut self, rhs: &u8) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'u8', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<u8> for &Rational { type Output = Rational; fn sub(self, rhs: u8) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&u8', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u8> for &Rational { type Output = Rational; fn sub(self, rhs: &u8) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['u8', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for u8 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['u8', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for u8 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&u8', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &u8 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&u8', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &u8 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'i16', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<i16> for Rational { type Output = Rational; fn sub(mut self, rhs: i16) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&i16', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i16> for Rational { type Output = Rational; fn sub(mut self, rhs: &i16) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'i16', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<i16> for &Rational { type Output = Rational; fn sub(self, rhs: i16) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&i16', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i16> for &Rational { type Output = Rational; fn sub(self, rhs: &i16) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['i16', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for i16 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['i16', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for i16 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&i16', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &i16 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&i16', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &i16 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'u16', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<u16> for Rational { type Output = Rational; fn sub(mut self, rhs: u16) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&u16', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u16> for Rational { type Output = Rational; fn sub(mut self, rhs: &u16) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'u16', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<u16> for &Rational { type Output = Rational; fn sub(self, rhs: u16) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&u16', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u16> for &Rational { type Output = Rational; fn sub(self, rhs: &u16) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['u16', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for u16 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['u16', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for u16 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&u16', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &u16 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&u16', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &u16 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'i32', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<i32> for Rational { type Output = Rational; fn sub(mut self, rhs: i32) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&i32', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i32> for Rational { type Output = Rational; fn sub(mut self, rhs: &i32) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'i32', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<i32> for &Rational { type Output = Rational; fn sub(self, rhs: i32) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&i32', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i32> for &Rational { type Output = Rational; fn sub(self, rhs: &i32) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['i32', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for i32 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['i32', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for i32 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&i32', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &i32 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&i32', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &i32 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'u32', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<u32> for Rational { type Output = Rational; fn sub(mut self, rhs: u32) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&u32', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u32> for Rational { type Output = Rational; fn sub(mut self, rhs: &u32) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'u32', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<u32> for &Rational { type Output = Rational; fn sub(self, rhs: u32) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&u32', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u32> for &Rational { type Output = Rational; fn sub(self, rhs: &u32) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['u32', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for u32 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['u32', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for u32 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&u32', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &u32 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&u32', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &u32 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'i64', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<i64> for Rational { type Output = Rational; fn sub(mut self, rhs: i64) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&i64', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i64> for Rational { type Output = Rational; fn sub(mut self, rhs: &i64) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'i64', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<i64> for &Rational { type Output = Rational; fn sub(self, rhs: i64) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&i64', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i64> for &Rational { type Output = Rational; fn sub(self, rhs: &i64) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['i64', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for i64 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['i64', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for i64 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&i64', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &i64 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&i64', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &i64 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'u64', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<u64> for Rational { type Output = Rational; fn sub(mut self, rhs: u64) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&u64', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u64> for Rational { type Output = Rational; fn sub(mut self, rhs: &u64) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'u64', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<u64> for &Rational { type Output = Rational; fn sub(self, rhs: u64) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&u64', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u64> for &Rational { type Output = Rational; fn sub(self, rhs: &u64) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['u64', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for u64 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['u64', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for u64 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&u64', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &u64 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&u64', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &u64 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'i128', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<i128> for Rational { type Output = Rational; fn sub(mut self, rhs: i128) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&i128', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i128> for Rational { type Output = Rational; fn sub(mut self, rhs: &i128) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'i128', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<i128> for &Rational { type Output = Rational; fn sub(self, rhs: i128) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&i128', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&i128> for &Rational { type Output = Rational; fn sub(self, rhs: &i128) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['i128', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for i128 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['i128', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for i128 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&i128', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &i128 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&i128', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &i128 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['Rational', 'u128', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}]] impl Sub<u128> for Rational { type Output = Rational; fn sub(mut self, rhs: u128) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(rhs)); self } } // ['Rational', '&u128', 'Rational', 'Rational::subtract_assign_integer', 'lhs', // ['ref_mut'], ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u128> for Rational { type Output = Rational; fn sub(mut self, rhs: &u128) -> Self::Output { Rational::subtract_assign_integer(&mut self, &Integer::from(*rhs)); self } } // ['&Rational', 'u128', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}]] impl Sub<u128> for &Rational { type Output = Rational; fn sub(self, rhs: u128) -> Self::Output { Rational::subtract_integer(self, &Integer::from(rhs)) } } // ['&Rational', '&u128', 'Rational', 'Rational::subtract_integer', 'no', [], // ['ref', {'convert': 'Integer'}, 'deref']] impl Sub<&u128> for &Rational { type Output = Rational; fn sub(self, rhs: &u128) -> Self::Output { Rational::subtract_integer(self, &Integer::from(*rhs)) } } // ['u128', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for u128 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['u128', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for u128 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } } // ['&u128', 'Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], ['ref']] impl Sub<Rational> for &u128 { type Output = Rational; fn sub(self, rhs: Rational) -> Self::Output { subtract_reuse_lhs(self, &rhs) } } // ['&u128', '&Rational', 'Rational', 'subtract_reuse_lhs', 'no', [], []] impl Sub<&Rational> for &u128 { type Output = Rational; fn sub(self, rhs: &Rational) -> Self::Output { subtract_reuse_lhs(self, rhs) } }
use crate::event::*; use crate::types::*; use chrono::Local; use std::collections::hash_map::HashMap; use std::collections::BTreeMap; // Really, a resting order on the book. #[allow(dead_code)] #[derive(Clone, PartialEq)] pub struct Order { pub side: Side, pub price: Price, pub qty: Qty, pub order_id: OrderId, pub time: Timestamp, } type OrderMap = BTreeMap<Price, BTreeMap<Timestamp, OrderId>>; type OrderSet = HashMap<OrderId, Order>; // Orderbook for a single symbol. pub struct OrderBook { symbol: String, buy_order_tree: OrderMap, sell_order_tree: OrderMap, buy_order_set: OrderSet, sell_order_set: OrderSet, } impl OrderBook { pub fn new(symbol: String) -> OrderBook { OrderBook { symbol: symbol, buy_order_tree: OrderMap::new(), sell_order_tree: OrderMap::new(), buy_order_set: OrderSet::new(), sell_order_set: OrderSet::new(), } } pub fn best_bid(&self) -> Option<Price> { self.buy_order_tree .iter() .rev() .next() .map(|(price, _time_map)| price.clone()) } pub fn best_ask(&self) -> Option<Price> { self.sell_order_tree .iter() .next() .map(|(price, _time_map)| price.clone()) } fn get_side_objs(&mut self, side: &Side) -> (&mut OrderMap, &mut OrderSet) { match side { Side::Buy => { return (&mut self.buy_order_tree, &mut self.buy_order_set); } Side::Sell => { return (&mut self.sell_order_tree, &mut self.sell_order_set); } } } pub fn add_order(&mut self, order: Order) -> Vec<Event> { let (book, order_set) = self.get_side_objs(&order.side); if !book.contains_key(&order.price) { book.insert(order.price, BTreeMap::new()); } book.get_mut(&order.price) .unwrap() .insert(order.time, order.order_id); order_set.insert(order.order_id, order); self.process_trades() } pub fn remove_order(&mut self, order_id: OrderId) { let order: Order = if self.buy_order_set.contains_key(&order_id) { self.buy_order_set.remove(&order_id).unwrap() } else { self.sell_order_set.remove(&order_id).unwrap() }; let (book, _order_set) = self.get_side_objs(&order.side); if !book.contains_key(&order.price) { return; } let time_map = book.get_mut(&order.price).unwrap(); time_map.remove(&order.time); if time_map.is_empty() { book.remove(&order.price); } } fn price_cross(&self) -> bool { let best_bid = self.best_bid(); let best_ask = self.best_ask(); if best_bid.is_none() || best_ask.is_none() { return false; } return best_bid.unwrap() >= best_ask.unwrap(); } fn process_trades(&mut self) -> Vec<Event> { let mut events = Vec::new(); while self.price_cross() { let (bid_timestamp, bid_id): (Timestamp, OrderId); let (ask_timestamp, ask_id): (Timestamp, OrderId); { let (_, level_bids) = self.buy_order_tree.iter().rev().next().unwrap(); let (_, level_asks) = self.sell_order_tree.iter().next().unwrap(); // Get earliest bid and ask order_ids at current price level. let (bid_timestamp_ref, bid_id_ref): (&Timestamp, &OrderId) = level_bids.iter().next().unwrap(); let (ask_timestamp_ref, ask_id_ref): (&Timestamp, &OrderId) = level_asks.iter().next().unwrap(); bid_timestamp = *bid_timestamp_ref; bid_id = *bid_id_ref; ask_timestamp = *ask_timestamp_ref; ask_id = *ask_id_ref; } let bid_order = self.buy_order_set.get_mut(&bid_id).unwrap(); let ask_order = self.sell_order_set.get_mut(&ask_id).unwrap(); let trade_price = if bid_timestamp < ask_timestamp { bid_order.price } else { ask_order.price }; /* We need to delete or modify the orders being matched. */ let executed_qty; // Delete both orders. if bid_order.qty == ask_order.qty { executed_qty = bid_order.qty; self.remove_order(bid_id); self.remove_order(ask_id); } // Only remove ask order, modify qty on bid order. else if bid_order.qty > ask_order.qty { executed_qty = ask_order.qty; // Modify bid order to have lower quantity. bid_order.qty -= executed_qty; // Remove ask order self.remove_order(ask_id); } else { executed_qty = bid_order.qty; // Modify ask order to have lower quantity. ask_order.qty -= executed_qty; // Remove bid order. self.remove_order(bid_id); } let event = Event::Executed(ExecutedEvent { bid_id: bid_id.clone(), ask_id: ask_id.clone(), price: trade_price.clone(), qty: executed_qty, time: Local::now(), }); events.push(event); } events } } #[cfg(test)] mod test { use super::*; #[test] fn simple_test() { let mut orderbook = OrderBook::new(String::from("GOOG")); assert_eq!(orderbook.best_bid(), None); assert_eq!(orderbook.best_ask(), None); assert_eq!( orderbook .add_order(Order { side: Side::Buy, price: 10500, qty: 100, order_id: 15, time: Local::now(), }) .len(), 0 ); assert_eq!(orderbook.best_bid(), Some(10500)); assert_eq!(orderbook.best_ask(), None); assert_eq!( orderbook .add_order(Order { side: Side::Sell, price: 11000, qty: 100, order_id: 16, time: Local::now(), }) .len(), 0 ); assert_eq!(orderbook.best_bid(), Some(10500)); assert_eq!(orderbook.best_ask(), Some(11000)); assert_eq!( orderbook .add_order(Order { side: Side::Sell, price: 10700, qty: 100, order_id: 17, time: Local::now(), }) .len(), 0 ); assert_eq!(orderbook.best_bid(), Some(10500)); assert_eq!(orderbook.best_ask(), Some(10700)); let trade_events = orderbook.add_order(Order { side: Side::Buy, price: 11100, qty: 150, order_id: 18, time: Local::now(), }); // Make sure 2 orders were matched. assert_eq!(trade_events.len(), 2); match &trade_events[0] { Event::Executed(executed_event) => { assert_eq!(executed_event.bid_id, 18); assert_eq!(executed_event.ask_id, 17); assert_eq!(executed_event.qty, 100); assert_eq!(executed_event.price, 10700); } } match &trade_events[1] { Event::Executed(executed_event) => { assert_eq!(executed_event.bid_id, 18); assert_eq!(executed_event.ask_id, 16); assert_eq!(executed_event.qty, 50); assert_eq!(executed_event.price, 11000); } } assert_eq!(orderbook.best_bid(), Some(10500)); assert_eq!(orderbook.best_ask(), Some(11000)); } #[test] fn same_level_clear_order() { let mut orderbook = OrderBook::new(String::from("GOOG")); assert_eq!(orderbook.best_bid(), None); assert_eq!(orderbook.best_ask(), None); assert_eq!( orderbook .add_order(Order { side: Side::Buy, price: 11000, qty: 100, order_id: 16, time: Local::now(), }) .len(), 0 ); assert_eq!(orderbook.best_bid(), Some(11000)); assert_eq!(orderbook.best_ask(), None); assert_eq!( orderbook .add_order(Order { side: Side::Buy, price: 11000, qty: 100, order_id: 17, time: Local::now(), }) .len(), 0 ); assert_eq!(orderbook.best_bid(), Some(11000)); assert_eq!(orderbook.best_ask(), None); let trade_events = orderbook.add_order(Order { side: Side::Sell, price: 10500, qty: 150, order_id: 18, time: Local::now(), }); // Make sure 2 orders were matched. assert_eq!(trade_events.len(), 2); match &trade_events[0] { Event::Executed(executed_event) => { assert_eq!(executed_event.bid_id, 16); assert_eq!(executed_event.ask_id, 18); assert_eq!(executed_event.qty, 100); assert_eq!(executed_event.price, 11000); } } match &trade_events[1] { Event::Executed(executed_event) => { assert_eq!(executed_event.bid_id, 17); assert_eq!(executed_event.ask_id, 18); assert_eq!(executed_event.qty, 50); assert_eq!(executed_event.price, 11000); } } } }
use crate::{ abi_stability::{GetStaticEquivalent, GetStaticEquivalent_, PrefixStableAbi, StableAbi}, pointer_trait::{GetPointerKind, PK_Reference}, prefix_type::{FieldAccessibility, PTStructLayout, PrefixRefTrait, WithMetadata_}, reexports::True, reflection::ModReflMode, sabi_types::StaticRef, std_types::RSlice, type_layout::{ CompTLField, GenericTLData, LifetimeRange, MonoTLData, MonoTypeLayout, ReprAttr, TypeLayout, }, utils::Transmuter, }; use std::{ fmt::{self, Debug}, ptr::NonNull, }; /// A reference to a prefix type. /// /// This is the type that all `*_Ref` pointer types generated by `StableAbi` wrap. /// /// # Example /// /// ```rust /// use abi_stable::{ /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// staticref, StableAbi, /// }; /// /// fn main() { /// // `Module_Ref`'s constructor can also be called at compile-time /// asserts(Module_Ref(PREFIX_A)); /// asserts(Module_Ref(PREFIX_B)); /// } /// /// fn asserts(module: Module_Ref) { /// assert_eq!(module.first(), 5); /// assert_eq!(module.second(), 8); /// /// // If this Module_Ref had come from a previous version of the library without a /// // `third` field it would return `None`. /// assert_eq!(module.third(), Some(13)); /// } /// /// #[repr(C)] /// #[derive(StableAbi)] /// #[sabi(kind(Prefix(prefix_ref = Module_Ref, prefix_fields = Module_Prefix)))] /// struct Module { /// first: usize, /// // The `#[sabi(last_prefix_field)]` attribute here means that this is /// // the last field in this struct that was defined in the /// // first compatible version of the library, /// // requiring new fields to always be added after it. /// // Moving this attribute is a breaking change, it can only be done in a /// // major version bump.. /// #[sabi(last_prefix_field)] /// second: usize, /// third: usize, /// } /// /// const MOD_VAL: Module = Module { /// first: 5, /// second: 8, /// third: 13, /// }; /// /// ///////////////////////////////////////// /// // First way to construct a PrefixRef /// // This is a way that PrefixRef can be constructed in statics /// /// const PREFIX_A: PrefixRef<Module_Prefix> = { /// const S: &WithMetadata<Module> = &WithMetadata::new(MOD_VAL); /// /// S.static_as_prefix() /// }; /// /// ///////////////////////////////////////// /// // Second way to construct a PrefixRef /// // This is a way that PrefixRef can be constructed in associated constants, /// /// struct WithAssoc; /// /// impl WithAssoc { /// // This macro declares a `StaticRef` pointing to the assigned `WithMetadata`. /// staticref!{const MOD_WM: WithMetadata<Module> = WithMetadata::new(MOD_VAL)} /// } /// /// const PREFIX_B: PrefixRef<Module_Prefix> = WithAssoc::MOD_WM.as_prefix(); /// /// ///////////////////////////////////////// /// /// ``` #[repr(transparent)] pub struct PrefixRef<P> { ptr: NonNull<WithMetadata_<P, P>>, } impl<P> Clone for PrefixRef<P> { #[inline] fn clone(&self) -> Self { *self } } impl<P> Copy for PrefixRef<P> {} unsafe impl<'a, P: 'a> Sync for PrefixRef<P> where &'a WithMetadata_<P, P>: Sync {} unsafe impl<'a, P: 'a> Send for PrefixRef<P> where &'a WithMetadata_<P, P>: Send {} impl<P> Debug for PrefixRef<P> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.debug_struct("PrefixRef") .field("type_layout", &self.type_layout()) .field("field_accessibility", &self.field_accessibility()) .field("value_type", &std::any::type_name::<P>()) .finish() } } impl<P> PrefixRef<P> { /// Constructs a `PrefixRef` from a raw pointer. /// /// # Safety /// /// The pointer must be a non-dangling pointer to a valid, initialized instance of `T`, /// and live for the rest of the program's lifetime /// (if called at compile-time it means live for the entire program). /// /// `T` must implement `PrefixTypeTrait<Fields = P>`, /// this is automatically true if this is called with /// `&WithMetadata::new(<value>)`. /// /// # Example /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix, Module_Ref}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// rstr, /// std_types::*, /// }; /// /// const MOD_WM: &WithMetadata<Module> = { /// &WithMetadata::new( /// Module { /// first: RSome(3), /// second: rstr!("hello"), /// third: 8, /// }, /// ) /// }; /// /// const PREFIX: PrefixRef<Module_Prefix> = unsafe { PrefixRef::from_raw(MOD_WM) }; /// /// const MODULE: Module_Ref = Module_Ref(PREFIX); /// /// assert_eq!(MODULE.first(), RSome(3)); /// /// assert_eq!(MODULE.second().as_str(), "hello"); /// /// // The accessor returns an `Option` because the field comes after the prefix, /// // and returning an Option is the default for those. /// assert_eq!(MODULE.third(), Some(8)); /// /// ``` #[inline(always)] pub const unsafe fn from_raw<T>(ptr: *const WithMetadata_<T, P>) -> Self { Self { ptr: unsafe { NonNull::new_unchecked( ptr as *const WithMetadata_<P, P> as *mut WithMetadata_<P, P>, ) }, } } /// Constructs a `PrefixRef` from a [`StaticRef`]. /// /// # Example /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix, Module_Ref}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// rstr, staticref, /// std_types::*, /// }; /// /// struct Foo {} /// /// impl Foo { /// // This macro declares a `StaticRef` pointing to the assigned `WithMetadata`. /// staticref! {const MOD_WM: WithMetadata<Module> = /// WithMetadata::new(Module{ /// first: RNone, /// second: rstr!("world"), /// third: 13, /// }) /// } /// } /// /// const PREFIX: PrefixRef<Module_Prefix> = PrefixRef::from_staticref(Foo::MOD_WM); /// /// const MODULE: Module_Ref = Module_Ref(PREFIX); /// /// assert_eq!(MODULE.first(), RNone); /// /// assert_eq!(MODULE.second().as_str(), "world"); /// /// // The accessor returns an `Option` because the field comes after the prefix, /// // and returning an Option is the default for those. /// assert_eq!(MODULE.third(), Some(13)); /// /// ``` /// /// [`StaticRef`]: ../sabi_types/struct.StaticRef.html #[inline] pub const fn from_staticref<T>(ptr: StaticRef<WithMetadata_<T, P>>) -> Self { unsafe { Self::from_raw(ptr.as_ptr()) } } /// Constructs a `PrefixRef` from a static reference. /// /// # Example /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix, Module_Ref}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// rstr, /// std_types::*, /// }; /// /// const MOD_WM: &WithMetadata<Module> = { /// &WithMetadata::new( /// Module { /// first: RNone, /// second: rstr!("foo"), /// third: 21, /// }, /// ) /// }; /// /// const PREFIX: PrefixRef<Module_Prefix> = PrefixRef::from_ref(MOD_WM); /// /// const MODULE: Module_Ref = Module_Ref(PREFIX); /// /// assert_eq!(MODULE.first(), RNone); /// /// assert_eq!(MODULE.second().as_str(), "foo"); /// /// // The accessor returns an `Option` because the field comes after the prefix, /// // and returning an Option is the default for those. /// assert_eq!(MODULE.third(), Some(21)); /// /// ``` /// #[inline] pub const fn from_ref<T>(ptr: &'static WithMetadata_<T, P>) -> Self { unsafe { Self::from_raw(ptr) } } /// A bit array that describes the accessibility of each field in `P`. /// /// # Example /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// std_types::*, /// }; /// /// const MOD_WM: &WithMetadata<Module> = { /// &WithMetadata::new( /// Module { /// first: RNone, /// second: RStr::empty(), /// third: 0, /// }, /// ) /// }; /// /// const PREFIX: PrefixRef<Module_Prefix> = PrefixRef::from_ref(MOD_WM); /// /// let accessibility = PREFIX.field_accessibility(); /// /// assert!(accessibility.at(0).is_accessible()); // The `first` field /// assert!(accessibility.at(1).is_accessible()); // The `second` field /// assert!(accessibility.at(2).is_accessible()); // The `third` field /// assert!(!accessibility.at(3).is_accessible()); // There's no field after `third` /// /// ``` /// pub const fn field_accessibility(&self) -> FieldAccessibility { let ptr: *const _ = self.ptr.as_ptr(); unsafe { (*ptr).field_accessibility } } /// The basic layout of the prefix type, for error messages. pub const fn type_layout(&self) -> &'static PTStructLayout { let ptr: *const _ = self.ptr.as_ptr(); unsafe { (*ptr).type_layout } } /// Gets a reference to the pointed-to prefix. /// /// # Example /// /// ```rust /// use abi_stable::{ /// for_examples::{Module, Module_Prefix}, /// prefix_type::{PrefixRef, PrefixTypeTrait, WithMetadata}, /// rstr, /// std_types::*, /// }; /// /// const MOD_WM: &WithMetadata<Module> = { /// &WithMetadata::new( /// Module { /// first: RNone, /// second: rstr!("foo"), /// third: 21, /// }, /// ) /// }; /// /// const PREFIX_REF: PrefixRef<Module_Prefix> = PrefixRef::from_ref(MOD_WM); /// /// let prefix: &Module_Prefix = PREFIX_REF.prefix(); /// /// assert_eq!(prefix.first, RNone); /// /// assert_eq!(prefix.second.as_str(), "foo"); /// /// // The `third` field is not in the prefix, so it can't be accessed here. /// // prefix.third; /// /// ``` /// #[inline] pub const fn prefix<'a>(self) -> &'a P { let ptr: *const _ = self.ptr.as_ptr(); unsafe { &(*ptr).value.0 } } /// Converts this PrefixRef into a raw pointer. #[inline(always)] pub const fn to_raw_ptr(self) -> *const WithMetadata_<P, P> { unsafe { Transmuter { from: self }.to } } /// Casts the pointed-to prefix to another type. /// /// # Safety /// /// This function is intended for casting the `PrefixRef<P>` to `PrefixRef<U>`, /// and then cast back to `PrefixRef<P>` to use it again. /// /// The prefix in the returned `PrefixRef<U>` must only be accessed /// when this `PrefixRef` was originally cosntructed with a `ẀithMetadata_<_, U>`. /// access includes calling `prefix`, and reading the `value` field in the `WithMetadata` /// that this points to. /// pub const unsafe fn cast<U>(self) -> PrefixRef<U> { PrefixRef { ptr: self.ptr.cast(), } } } unsafe impl<P> GetStaticEquivalent_ for PrefixRef<P> where P: GetStaticEquivalent_, { type StaticEquivalent = PrefixRef<GetStaticEquivalent<P>>; } unsafe impl<P> StableAbi for PrefixRef<P> where P: PrefixStableAbi, { type IsNonZeroType = True; const LAYOUT: &'static TypeLayout = { const MONO_TYPE_LAYOUT: &MonoTypeLayout = &MonoTypeLayout::new( *mono_shared_vars, rstr!("PrefixRef"), make_item_info!(), MonoTLData::struct_(rslice![]), tl_genparams!('a;0;), ReprAttr::Transparent, ModReflMode::DelegateDeref { layout_index: 0 }, { const S: &[CompTLField] = &[CompTLField::std_field(field0, LifetimeRange::EMPTY, 0)]; RSlice::from_slice(S) }, ); make_shared_vars! { impl[P] PrefixRef<P> where [P: PrefixStableAbi]; let (mono_shared_vars,shared_vars)={ strings={ field0:"0", }, prefix_type_layouts=[P], }; } &TypeLayout::from_std::<Self>( shared_vars, MONO_TYPE_LAYOUT, Self::ABI_CONSTS, GenericTLData::Struct, ) }; } unsafe impl<P> GetPointerKind for PrefixRef<P> { type PtrTarget = WithMetadata_<P, P>; type Kind = PK_Reference; } unsafe impl<P> PrefixRefTrait for PrefixRef<P> { type PrefixFields = P; }
extern crate olin; use log::info; use olin::random; pub extern "C" fn test() -> Result<(), i32> { info!("running ns::random tests"); info!("i31: {}, i63: {}", random::i31(), random::i63()); info!("ns::random tests passed"); Ok(()) }
use crate::{Error, mock::*}; use frame_support::{assert_ok, assert_noop}; #[test] fn it_works_for_default_value() { new_test_ext().execute_with(|| { // Dispatch a signed extrinsic. assert_ok!(TemplateModule::do_something(Origin::signed(1), 42)); // Read pallet storage and assert an expected result. assert_eq!(TemplateModule::something(), Some(42)); }); } #[test] fn correct_error_for_none_value() { new_test_ext().execute_with(|| { // Ensure the expected error is thrown when no value is present. assert_noop!( TemplateModule::cause_error(Origin::signed(1)), Error::<Test>::NoneValue ); }); }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. /// Used to pass a constructor across threads. pub trait ReactorsRegistration { /// Register any reactors with the `reactors_registrar` when called. /// /// Will be called once per thread. fn register_any_reactors<AR: ReactorsRegistrar>(&self, reactors_registrar: &AR); }
use std::{collections::VecDeque, sync::Arc}; use sourcerenderer_core::graphics::{BindingFrequency, Buffer, BufferInfo, BufferUsage, CommandBuffer, LoadOp, MemoryUsage, PipelineBinding, Queue, Scissor, ShaderType, Viewport, IndexFormat, WHOLE_BUFFER, Texture, RenderpassRecordingMode, TextureView, Format}; use wasm_bindgen::JsValue; use web_sys::{WebGl2RenderingContext, WebGlBuffer, WebGlRenderingContext}; use crate::{GLThreadSender, WebGLBackend, WebGLBuffer, WebGLFence, WebGLGraphicsPipeline, WebGLSwapchain, WebGLTexture, WebGLTextureView, device::WebGLHandleAllocator, sync::WebGLSemaphore, texture::{WebGLSampler, compare_func_to_gl}, thread::{TextureHandle, WebGLThreadBuffer, WebGLVBThreadBinding, WebGLTextureHandleView}, rt::WebGLAccelerationStructureStub, WebGLWork}; use bitflags::bitflags; bitflags! { #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Default)] pub struct WebGLCommandBufferDirty: u32 { const VAO = 0b0001; } } pub struct WebGLVBBinding { buffer: Arc<WebGLBuffer>, offset: u64, } pub struct WebGLCommandBuffer { sender: GLThreadSender, pipeline: Option<Arc<WebGLGraphicsPipeline>>, commands: VecDeque<WebGLWork>, inline_buffer: Arc<WebGLBuffer>, handles: Arc<WebGLHandleAllocator>, dirty: WebGLCommandBufferDirty, vertex_buffer: Option<WebGLVBBinding>, index_buffer_offset: usize, used_pipelines: Vec<Arc<WebGLGraphicsPipeline>>, used_textures: Vec<Arc<WebGLTexture>>, used_samplers: Vec<Arc<WebGLSampler>>, used_buffers: Vec<Arc<WebGLBuffer>>, } impl WebGLCommandBuffer { pub fn new(sender: &GLThreadSender, handle_allocator: &Arc<WebGLHandleAllocator>) -> Self { let inline_buffer = Arc::new(WebGLBuffer::new(handle_allocator.new_buffer_handle(), &BufferInfo { size: 256, usage: BufferUsage::CONSTANT, }, MemoryUsage::UncachedRAM, sender)); WebGLCommandBuffer { pipeline: None, commands: VecDeque::new(), sender: sender.clone(), handles: handle_allocator.clone(), inline_buffer, dirty: WebGLCommandBufferDirty::empty(), vertex_buffer: None, index_buffer_offset: 0, used_pipelines: Vec::new(), used_textures: Vec::new(), used_samplers: Vec::new(), used_buffers: Vec::new(), } } fn before_draw(&mut self) { if self.dirty.is_empty() { return; } assert!(self.pipeline.is_some()); assert!(self.vertex_buffer.is_some()); let dirty = self.dirty; let pipeline = self.pipeline.as_ref().unwrap(); let pipeline_handle = pipeline.handle(); let vbo = self.vertex_buffer.as_ref().unwrap(); let vbo_handle = vbo.buffer.handle(); let vbo_offset = vbo.offset; self.commands.push_back(Box::new(move |device| { let pipeline = device.pipeline(pipeline_handle); let vbo = device.buffer(vbo_handle); if dirty.contains(WebGLCommandBufferDirty::VAO) { let index_buffer: WebGlBuffer = device.get_parameter(WebGl2RenderingContext::ELEMENT_ARRAY_BUFFER_BINDING).unwrap().into(); let mut vbs: [Option<WebGLVBThreadBinding>; 4] = Default::default(); vbs[0] = Some(WebGLVBThreadBinding { buffer: vbo.clone(), offset: vbo_offset, }); let vao = pipeline.get_vao(&vbs); device.bind_vertex_array(Some(&vao)); device.bind_buffer(WebGl2RenderingContext::ELEMENT_ARRAY_BUFFER, Some(&index_buffer)); } })); self.dirty = WebGLCommandBufferDirty::empty(); } } impl CommandBuffer<WebGLBackend> for WebGLCommandBuffer { fn set_pipeline(&mut self, pipeline: PipelineBinding<WebGLBackend>) { match pipeline { PipelineBinding::Graphics(pipeline) => { self.used_pipelines.push(pipeline.clone()); self.pipeline = Some(pipeline.clone()); let handle = pipeline.handle(); self.dirty |= WebGLCommandBufferDirty::VAO; self.commands.push_back(Box::new(move |device| { let pipeline = device.pipeline(handle).clone(); device.use_program(Some(pipeline.gl_program())); let info = pipeline.info(); if info.depth_stencil.depth_test_enabled { device.enable(WebGl2RenderingContext::DEPTH_TEST); } else { device.disable(WebGl2RenderingContext::DEPTH_TEST); } device.depth_mask(info.depth_stencil.depth_write_enabled); device.depth_func(compare_func_to_gl(info.depth_stencil.depth_func)); device.front_face(pipeline.gl_front_face()); let cull_face = pipeline.gl_cull_face(); if cull_face == 0 { device.disable(WebGl2RenderingContext::CULL_FACE); } else { device.enable(WebGl2RenderingContext::CULL_FACE); device.cull_face(cull_face); } })); }, PipelineBinding::Compute(_) => panic!("WebGL does not support compute shaders"), PipelineBinding::RayTracing(_) => panic!("WebGL does not support ray tracing") } } fn set_vertex_buffer(&mut self, vertex_buffer: &Arc<WebGLBuffer>, offset: usize) { self.used_buffers.push(vertex_buffer.clone()); self.vertex_buffer = Some(WebGLVBBinding { buffer: vertex_buffer.clone(), offset: offset as u64 }); self.dirty |= WebGLCommandBufferDirty::VAO; } fn set_index_buffer(&mut self, index_buffer: &Arc<WebGLBuffer>, offset: usize, index_format: IndexFormat) { // TODO: maybe track dirty and do before draw if index_format != IndexFormat::U32 { unimplemented!("16 bit indices are not implemented"); } self.used_buffers.push(index_buffer.clone()); self.index_buffer_offset = offset; let handle = index_buffer.handle(); self.commands.push_back(Box::new(move |device| { let buffer = device.buffer(handle).clone(); device.bind_buffer(WebGlRenderingContext::ELEMENT_ARRAY_BUFFER, Some(buffer.gl_buffer())); })); } fn set_viewports(&mut self, viewports: &[ Viewport ]) { // TODO: maybe track dirty and do before draw if viewports.len() == 0 { return; } debug_assert_eq!(viewports.len(), 1); let viewports: Vec<Viewport> = viewports.iter().cloned().collect(); self.commands.push_back(Box::new(move |device| { let viewport = viewports.first().unwrap(); device.viewport(viewport.position.x as i32, viewport.position.y as i32, viewport.extent.x as i32, viewport.extent.y as i32); })); } fn set_scissors(&mut self, scissors: &[ Scissor ]) { // TODO: maybe track dirty and do before draw if scissors.len() == 0 { return; } debug_assert_eq!(scissors.len(), 1); let scissors: Vec<Scissor> = scissors.iter().cloned().collect(); self.commands.push_back(Box::new(move |device| { let scissor = scissors.first().unwrap(); device.scissor(scissor.position.x as i32, scissor.position.y as i32, scissor.extent.x as i32, scissor.extent.y as i32); })); } fn upload_dynamic_data<T>(&mut self, data: &[T], usage: BufferUsage) -> Arc<WebGLBuffer> where T: 'static + Send + Sync + Sized + Clone { let buffer_handle = self.handles.new_buffer_handle(); let buffer = Arc::new(WebGLBuffer::new(buffer_handle, &BufferInfo { size: std::mem::size_of_val(data), usage }, MemoryUsage::UncachedRAM, &self.sender)); unsafe { let mapped = buffer.map_unsafe(false).unwrap(); std::ptr::copy(data.as_ptr() as *const u8, mapped, std::mem::size_of_val(data)); buffer.unmap_unsafe(true); } self.used_buffers.push(buffer.clone()); buffer } fn upload_dynamic_data_inline<T>(&mut self, data: &[T], _visible_for_shader_stage: ShaderType) where T: 'static + Send + Sync + Sized + Clone { assert!(self.pipeline.is_some()); let pipeline = self.pipeline.as_ref().unwrap(); unsafe { let mapped = self.inline_buffer.map_unsafe(false).unwrap(); std::ptr::copy(data.as_ptr() as *const u8, mapped, std::mem::size_of_val(data)); self.inline_buffer.unmap_unsafe(true); } let pipeline_handle = pipeline.handle(); let buffer_handle = self.inline_buffer.handle(); self.commands.push_back(Box::new(move |device| { let pipeline = device.pipeline(pipeline_handle); if let Some(info) = pipeline.push_constants_info() { let binding = info.binding; let buffer = device.buffer(buffer_handle); debug_assert!(buffer.info().size as u32 >= info.size); device.bind_buffer_base(WebGl2RenderingContext::UNIFORM_BUFFER, binding, Some(&buffer.gl_buffer())); } })); } fn draw(&mut self, vertices: u32, offset: u32) { self.before_draw(); self.commands.push_back(Box::new(move |device| { device.draw_arrays( WebGlRenderingContext::TRIANGLES, // TODO: self.pipeline.as_ref().unwrap().gl_draw_mode(), offset as i32, vertices as i32 ); })); } fn draw_indexed(&mut self, instances: u32, first_instance: u32, indices: u32, first_index: u32, vertex_offset: i32) { self.before_draw(); // TODO: support instancing with WebGL2 assert_eq!(instances, 1); assert_eq!(first_instance, 0); assert_eq!(vertex_offset, 0); let pipeline_handle = self.pipeline.as_ref().unwrap().handle(); let index_offset = self.index_buffer_offset as i32; self.commands.push_back(Box::new(move |device| { let pipeline = device.pipeline(pipeline_handle); device.draw_elements_with_i32( pipeline.gl_draw_mode(), indices as i32, WebGlRenderingContext::UNSIGNED_INT, first_index as i32 * std::mem::size_of::<u32>() as i32 + index_offset, ); })); } fn bind_sampling_view(&mut self, _frequency: BindingFrequency, _binding: u32, _texture: &Arc<WebGLTextureView>) { panic!("WebGL only supports combined images and samplers") } fn bind_sampling_view_and_sampler(&mut self, frequency: BindingFrequency, binding: u32, texture: &Arc<WebGLTextureView>, sampler: &Arc<WebGLSampler>) { let handle = texture.texture().handle(); let info = texture.texture().info(); let is_cubemap = info.array_length == 6; let target = if is_cubemap { WebGlRenderingContext::TEXTURE_CUBE_MAP } else { WebGlRenderingContext::TEXTURE_2D }; let pipeline = self.pipeline.as_ref().expect("Can't bind texture without active pipeline."); let pipeline_handle = pipeline.handle(); let sampler_handle = sampler.handle(); self.used_samplers.push(sampler.clone()); self.used_textures.push(texture.texture().clone()); self.commands.push_back(Box::new(move |device| { let pipeline = device.pipeline(pipeline_handle); let tex_uniform_info = pipeline.uniform_location(frequency, binding); if tex_uniform_info.is_none() { return; } let tex_uniform_info = tex_uniform_info.unwrap(); let texture = device.texture(handle); let sampler = device.sampler(sampler_handle); device.active_texture(WebGlRenderingContext::TEXTURE0 + tex_uniform_info.texture_unit); device.bind_texture(target, Some(texture.gl_handle())); device.uniform1i(Some(&tex_uniform_info.uniform_location), tex_uniform_info.texture_unit as i32); device.bind_sampler(tex_uniform_info.texture_unit, Some(sampler.gl_handle())); })); } fn bind_uniform_buffer(&mut self, frequency: BindingFrequency, binding: u32, buffer: &Arc<WebGLBuffer>, offset: usize, length: usize) { assert!(self.pipeline.is_some()); let pipeline = self.pipeline.as_ref().unwrap(); let pipeline_handle = pipeline.handle(); let buffer_handle = buffer.handle(); self.used_buffers.push(buffer.clone()); self.commands.push_back(Box::new(move |device| { let buffer = device.buffer(buffer_handle); let pipeline = device.pipeline(pipeline_handle); let info = pipeline.ubo_info(frequency, binding); if let Some(info) = info { debug_assert!(buffer.info().size as u32 >= info.size); let binding_index = info.binding; let size = if length == WHOLE_BUFFER { info.size as i32 } else { length as i32 }; device.bind_buffer_range_with_i32_and_i32(WebGl2RenderingContext::UNIFORM_BUFFER, binding_index, Some(buffer.gl_buffer()), offset as i32, size); } })); } fn bind_storage_buffer(&mut self, _frequency: BindingFrequency, _binding: u32, _buffer: &Arc<WebGLBuffer>, _offset: usize, _length: usize) { panic!("WebGL does not support storage buffers"); } fn finish_binding(&mut self) { // nop } fn begin_label(&mut self, _label: &str) {} fn end_label(&mut self) {} fn dispatch(&mut self, _group_count_x: u32, _group_count_y: u32, _group_count_z: u32) { panic!("WebGL does not support compute shaders"); } fn blit(&mut self, _src_texture: &Arc<WebGLTexture>, _src_array_layer: u32, _src_mip_level: u32, _dst_texture: &Arc<WebGLTexture>, _dst_array_layer: u32, _dst_mip_level: u32) { unimplemented!() } fn finish(self) -> WebGLCommandSubmission { // nop WebGLCommandSubmission { cmd_buffer: self } } fn bind_storage_texture(&mut self, _frequency: BindingFrequency, _binding: u32, _texture: &Arc<WebGLTextureView>) { panic!("WebGL does not support storage textures") } fn begin_render_pass(&mut self, renderpass_info: &sourcerenderer_core::graphics::RenderPassBeginInfo<WebGLBackend>, recording_mode: RenderpassRecordingMode) { debug_assert_eq!(recording_mode, RenderpassRecordingMode::Commands); let mut color_attachments: [Option<WebGLTextureHandleView>; 8] = Default::default(); let mut color_attachment_load_ops: [Option<LoadOp>; 8] = Default::default(); let subpass = &renderpass_info.subpasses[0]; for (index, attachment_ref) in subpass.output_color_attachments.iter().enumerate() { let attachment = &renderpass_info.attachments[attachment_ref.index as usize]; match &attachment.view { sourcerenderer_core::graphics::RenderPassAttachmentView::RenderTarget(rt) => { let info = rt.info(); color_attachments[index] = Some(WebGLTextureHandleView { texture: rt.texture().handle(), array_layer: info.base_array_layer, mip: info.base_mip_level }); color_attachment_load_ops[index] = Some(attachment.load_op); self.used_textures.push(rt.texture().clone()); }, _ => panic!("Found depth stencil attachment being used as a color target.") } } let mut depth_attachment = Option::<WebGLTextureHandleView>::None; let mut ds_format = Format::Unknown; let mut ds_load_op = LoadOp::DontCare; if let Some(attachment_ref) = subpass.depth_stencil_attachment.as_ref() { let attachment = &renderpass_info.attachments[attachment_ref.index as usize]; match &attachment.view { sourcerenderer_core::graphics::RenderPassAttachmentView::DepthStencil(ds) => { ds_format = ds.texture().info().format; let info = ds.info(); depth_attachment = Some(WebGLTextureHandleView { texture: ds.texture().handle(), array_layer: info.base_array_layer, mip: info.base_mip_level }); ds_load_op = attachment.load_op; self.used_textures.push(ds.texture().clone()); }, _ => panic!("Found color attachment being used as a depth stencil.") } } self.commands.push_back(Box::new(move |context| { let fbo = context.get_framebuffer(&color_attachments, depth_attachment, ds_format); context.bind_framebuffer(WebGl2RenderingContext::DRAW_FRAMEBUFFER, Some(&fbo)); let invalidate_color_attachments = js_sys::Array::new(); for (index, load_op_opt) in color_attachment_load_ops.iter().enumerate() { if load_op_opt.is_none() { continue; } let load_op = load_op_opt.unwrap(); if load_op == LoadOp::Clear { let clear_color = [0f32, 0f32, 0f32, 1f32]; context.clear_bufferfv_with_f32_array(WebGl2RenderingContext::COLOR, index as i32, &clear_color); } else { if load_op == LoadOp::DontCare { invalidate_color_attachments.push(&JsValue::from_f64((WebGl2RenderingContext::COLOR_ATTACHMENT0 + index as u32) as f64)); } } } if invalidate_color_attachments.length() != 0 { let _ = context.invalidate_framebuffer(WebGl2RenderingContext::DRAW_FRAMEBUFFER, &invalidate_color_attachments).unwrap(); } if ds_format != Format::Unknown { if ds_load_op == LoadOp::Clear { if ds_format.is_depth() && ds_format.is_stencil() { context.clear_bufferfi(WebGl2RenderingContext::DEPTH_STENCIL, 0 as i32, 1.0f32, 0i32); } else if ds_format.is_depth() { context.clear_bufferfv_with_f32_array(WebGl2RenderingContext::DEPTH, 0 as i32, &[1f32]); } else { context.clear_bufferiv_with_i32_array(WebGl2RenderingContext::STENCIL, 0 as i32, &[0i32]); } } else if ds_load_op == LoadOp::DontCare { let invalidate_depth_attachments = js_sys::Array::new(); if ds_format.is_depth() && ds_format.is_stencil() { invalidate_depth_attachments.push(&JsValue::from_f64((WebGl2RenderingContext::DEPTH_STENCIL_ATTACHMENT) as f64)); } else if ds_format.is_depth() { invalidate_depth_attachments.push(&JsValue::from_f64((WebGl2RenderingContext::DEPTH_ATTACHMENT) as f64)); } else { invalidate_depth_attachments.push(&JsValue::from_f64((WebGl2RenderingContext::STENCIL_ATTACHMENT) as f64)); } let _ = context.invalidate_framebuffer(WebGl2RenderingContext::DRAW_FRAMEBUFFER, &invalidate_depth_attachments).unwrap(); } } })); } fn advance_subpass(&mut self) { } fn end_render_pass(&mut self) { } fn barrier<'a>(&mut self, _barriers: &[sourcerenderer_core::graphics::Barrier<WebGLBackend>]) { // nop } fn flush_barriers(&mut self) { // nop } fn inheritance(&self) -> &Self::CommandBufferInheritance { panic!("WebGL does not support inner command buffers") } type CommandBufferInheritance = (); fn execute_inner(&mut self, _submission: Vec<WebGLCommandSubmission>) { panic!("WebGL does not support inner command buffers") } fn create_query_range(&mut self, _count: u32) -> Arc<()> { todo!() } fn begin_query(&mut self, _query_range: &Arc<()>, _query_index: u32) { todo!() } fn end_query(&mut self, _query_range: &Arc<()>, _query_index: u32) { todo!() } fn copy_query_results_to_buffer(&mut self, _query_range: &Arc<()>, _buffer: &Arc<WebGLBuffer>, _start_index: u32, _count: u32) { todo!() } fn create_temporary_buffer(&mut self, _info: &BufferInfo, _memory_usage: MemoryUsage) -> Arc<WebGLBuffer> { unimplemented!() } fn bind_sampler(&mut self, _frequency: BindingFrequency, _binding: u32, _sampler: &Arc<WebGLSampler>) { panic!("WebGL does not support separate samplers") } fn bind_acceleration_structure(&mut self, _frequency: BindingFrequency, _binding: u32, _acceleration_structure: &Arc<WebGLAccelerationStructureStub>) { panic!("WebGL does not support ray tracing") } fn create_bottom_level_acceleration_structure(&mut self, _info: &sourcerenderer_core::graphics::BottomLevelAccelerationStructureInfo<WebGLBackend>, _size: usize, _target_buffer: &Arc<WebGLBuffer>, _scratch_buffer: &Arc<WebGLBuffer>) -> Arc<WebGLAccelerationStructureStub> { panic!("WebGL does not support ray tracing") } fn upload_top_level_instances(&mut self, _instances: &[sourcerenderer_core::graphics::AccelerationStructureInstance<WebGLBackend>]) -> Arc<WebGLBuffer> { panic!("WebGL does not support ray tracing") } fn create_top_level_acceleration_structure(&mut self, _info: &sourcerenderer_core::graphics::TopLevelAccelerationStructureInfo<WebGLBackend>, _size: usize, _target_buffer: &Arc<WebGLBuffer>, _scratch_buffer: &Arc<WebGLBuffer>) -> Arc<WebGLAccelerationStructureStub> { panic!("WebGL does not support ray tracing") } fn trace_ray(&mut self, _width: u32, _height: u32, _depth: u32) { panic!("WebGL does not support ray tracing") } fn track_texture_view(&mut self, _texture_view: &Arc<WebGLTextureView>) { // nop } fn draw_indexed_indirect(&mut self, _draw_buffer: &Arc<WebGLBuffer>, _draw_buffer_offset: u32, _count_buffer: &Arc<WebGLBuffer>, _count_buffer_offset: u32, _max_draw_count: u32, _stride: u32) { panic!("WebGL does not support indirect rendering."); } fn draw_indirect(&mut self, _draw_buffer: &Arc<WebGLBuffer>, _draw_buffer_offset: u32, _count_buffer: &Arc<WebGLBuffer>, _count_buffer_offset: u32, _max_draw_count: u32, _stride: u32) { panic!("WebGL does not support indirect rendering."); } fn bind_sampling_view_and_sampler_array(&mut self, _frequency: BindingFrequency, _binding: u32, _textures_and_samplers: &[(&Arc<WebGLTextureView>, &Arc<WebGLSampler>)]) { panic!("No plans to support texture and sampler arrays on WebGL") } fn bind_storage_view_array(&mut self, _frequency: BindingFrequency, _binding: u32, _textures: &[&Arc<WebGLTextureView>]) { panic!("WebGL doesnt support storage textures") } fn clear_storage_texture(&mut self, _view: &Arc<WebGLTexture>, _array_layer: u32, _mip_leve: u32, _values: [u32; 4]) { panic!("WebGL doesnt support storage textures") } fn clear_storage_buffer(&mut self, _buffer: &Arc<WebGLBuffer>, _offset: usize, _length_in_u32s: usize, _value: u32) { todo!() } } pub struct WebGLCommandSubmission { cmd_buffer: WebGLCommandBuffer } pub struct WebGLQueue { sender: GLThreadSender, handle_allocator: Arc<WebGLHandleAllocator>, } impl WebGLQueue { pub fn new(sender: &GLThreadSender, handle_allocator: &Arc<WebGLHandleAllocator>) -> Self { Self { sender: sender.clone(), handle_allocator: handle_allocator.clone() } } } impl Queue<WebGLBackend> for WebGLQueue { fn create_command_buffer(&self) -> WebGLCommandBuffer { WebGLCommandBuffer::new(&self.sender, &self.handle_allocator) } fn create_inner_command_buffer(&self, _inheritance: &()) -> WebGLCommandBuffer { panic!("WebGL does not support inner command buffers") } fn submit(&self, mut submission: WebGLCommandSubmission, _fence: Option<&Arc<WebGLFence>>, _wait_semaphores: &[&Arc<WebGLSemaphore>], _signal_semaphores: &[&Arc<WebGLSemaphore>], _delay: bool) { while let Some(cmd) = submission.cmd_buffer.commands.pop_front() { self.sender.send(cmd); } } fn present(&self, swapchain: &Arc<WebGLSwapchain>, _wait_semaphores: &[&Arc<WebGLSemaphore>], _delay: bool) { swapchain.present(); } fn process_submissions(&self) { // WebGL Queue isn't threaded right now } }
use bellman::groth16::*; use pairing::*; use pairing::bls12_381::{Fr, FrRepr, Bls12}; use bellman::*; use rand::thread_rng; use jubjub::*; use base::*; use convert::*; use std::fs::File; struct P2Ccircuit<'a> { generators: &'a [(Vec<Fr>, Vec<Fr>)], j: &'a JubJub, //r_h rh: Assignment<Fr>, //r_cm rcm: Assignment<Fr>, //Balance ba: Assignment<Fr>, //value va: Assignment<Fr>, //addr addr: (Assignment<Fr>, Assignment<Fr>), //random number, random: Assignment<Fr>, //addr_sk addr_sk: Vec<Assignment<bool>>, //result res: &'a mut Vec<FrRepr> } impl<'a> P2Ccircuit<'a> { fn blank( generators: &'a [(Vec<Fr>, Vec<Fr>)], j: &'a JubJub, res: &'a mut Vec<FrRepr> ) -> P2Ccircuit<'a> { P2Ccircuit { generators, j, rh: Assignment::unknown(), rcm: Assignment::unknown(), ba: Assignment::unknown(), va: Assignment::unknown(), addr: (Assignment::unknown(), Assignment::unknown()), random: Assignment::unknown(), addr_sk: (0..ADSK).map(|_| Assignment::unknown()).collect(), res, } } fn new( generators: &'a [(Vec<Fr>, Vec<Fr>)], j: &'a JubJub, rh: Fr, rcm: Fr, ba: Fr, va: Fr, addr: (Fr, Fr), random: Fr, addr_sk: Vec<bool>, res: &'a mut Vec<FrRepr> ) -> P2Ccircuit<'a> { assert_eq!(res.len(), 0); P2Ccircuit { generators, j, rh: Assignment::known(rh), rcm: Assignment::known(rcm), ba: Assignment::known(ba), va: Assignment::known(va), addr: (Assignment::known(addr.0), Assignment::known(addr.1)), random: Assignment::known(random), addr_sk: addr_sk.iter().map(|&b| Assignment::known(b)).collect(), res, } } } struct P2CcircuitInput { //ba*P1+rh*P2 hb: (Num<Bls12>, Num<Bls12>), //coin coin: Num<Bls12>, //delta_balance, delt_ba: (Num<Bls12>, Num<Bls12>), //rP rp: (Num<Bls12>, Num<Bls12>), //enc enc: Num<Bls12>, //addr addr: (Num<Bls12>, Num<Bls12>) } impl<'a> Input<Bls12> for P2CcircuitInput { fn synthesize<CS: PublicConstraintSystem<Bls12>>(self, cs: &mut CS) -> Result<(), Error> { let delt_x_input = cs.alloc_input(|| Ok(*self.delt_ba.0.getvalue().get()?))?; let delt_y_input = cs.alloc_input(|| Ok(*self.delt_ba.1.getvalue().get()?))?; let hb_x_input = cs.alloc_input(|| Ok(*self.hb.0.getvalue().get()?))?; let hb_y_input = cs.alloc_input(|| Ok(*self.hb.1.getvalue().get()?))?; let coin_input = cs.alloc_input(|| Ok(*self.coin.getvalue().get()?))?; let rpx_input = cs.alloc_input(|| Ok(*self.rp.0.getvalue().get()?))?; let rpy_input = cs.alloc_input(|| Ok(*self.rp.1.getvalue().get()?))?; let enc_input = cs.alloc_input(|| Ok(*self.enc.getvalue().get()?))?; let addrx_input = cs.alloc_input(|| Ok(*self.addr.0.getvalue().get()?))?; let addry_input = cs.alloc_input(|| Ok(*self.addr.1.getvalue().get()?))?; cs.enforce( LinearCombination::zero() + self.delt_ba.0.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + delt_x_input, ); cs.enforce( LinearCombination::zero() + self.delt_ba.1.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + delt_y_input, ); cs.enforce( LinearCombination::zero() + self.hb.0.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + hb_x_input, ); cs.enforce( LinearCombination::zero() + self.hb.1.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + hb_y_input, ); cs.enforce( LinearCombination::zero() + self.coin.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + coin_input, ); cs.enforce( LinearCombination::zero() + self.rp.0.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + rpx_input, ); cs.enforce( LinearCombination::zero() + self.rp.1.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + rpy_input, ); cs.enforce( LinearCombination::zero() + self.enc.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + enc_input, ); cs.enforce( LinearCombination::zero() + self.addr.0.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + addrx_input, ); cs.enforce( LinearCombination::zero() + self.addr.1.getvar(), LinearCombination::zero() + CS::one(), LinearCombination::zero() + addry_input, ); Ok(()) } } impl<'a> Circuit<Bls12> for P2Ccircuit<'a> { type InputMap = P2CcircuitInput; fn synthesize<CS: ConstraintSystem<Bls12>>(self, cs: &mut CS) -> Result<Self::InputMap, Error> { let rh_num = Num::new(cs, self.rh)?; let rh = rh_num.unpack_sized(cs, RHBIT)?; let rcm_num = Num::new(cs, self.rcm)?; let mut rcm = rcm_num.unpack_sized(cs, RCMBIT)?; let random_num = Num::new(cs, self.random)?; let random = random_num.unpack_sized(cs, 256)?; let addr_x_num = Num::new(cs, self.addr.0)?; let addr_x_bit = addr_x_num.unpack_sized(cs, PHOUT)?; let addr_y_num = Num::new(cs, self.addr.1)?; let bit_ba = Num::new(cs, self.ba)?.unpack_sized(cs, VBIT)?; let va = Num::new(cs, self.va)?; let bit_va = va.unpack_sized(cs, VBIT)?; assert_eq!(bit_ba.len(), VBIT); assert_eq!(bit_va.len(), VBIT); assert_nonless_than(&bit_ba, &bit_va, cs)?; //prepare table let p1 = Point::enc_point_table(256, 1, cs)?; let p2 = Point::enc_point_table(256, 2, cs)?; //ba*P1+rh*P2 let hb = Point::encrypt((&p1, &p2), &bit_ba, &rh, cs)?; if let (Ok(x), Ok(y)) = (hb.0.getvalue().get(), hb.1.getvalue().get()) { self.res.push(x.into_repr()); self.res.push(y.into_repr()); } //coin = PH(addr|value|rcm) let rcm2 = rcm.clone(); let vin = { for b in bit_va.iter() { rcm.push(*b); } for b in addr_x_bit.iter() { rcm.push(*b); } rcm }; assert_eq!(vin.len(), PHIN); let coin = pedersen_hash(cs, &vin, self.generators, self.j)?; if let Ok(x) = coin.getvalue().get() { self.res.push(x.into_repr()); } //delta_ba let rcm = rcm2; let p0 = Point::encrypt((&p1, &p2), &bit_va, &rcm, cs)?; if let (Ok(x), Ok(y)) = (p0.0.getvalue().get(), p0.1.getvalue().get()) { self.res.push(x.into_repr()); self.res.push(y.into_repr()); } let delt_ba = (p0.0, p0.1); //Enc let message = { let b128 = Num::new( cs, Assignment::known(Fr::from_repr(FrRepr::from_serial([0, 0, 1, 0])).unwrap()), )?; va.mul(cs, &b128)?.add(cs, &rcm_num) }?; let qtable = Point::point_mul_table((&addr_x_num, &addr_y_num), 256, cs)?; let rp = Point::multiply(&p1, &random, cs)?; let rq = Point::multiply(&qtable, &random, cs)?; if let (Ok(x), Ok(y)) = (rp.0.getvalue().get(), rp.1.getvalue().get()) { self.res.push(x.into_repr()); self.res.push(y.into_repr()); } let key = rq.0; let enc = key.add(cs, &message)?; if let Ok(x) = enc.getvalue().get() { self.res.push(x.into_repr()); } let mut addr_sk = Vec::with_capacity(ADSK); for b in self.addr_sk.iter() { addr_sk.push(Bit::alloc(cs, *b)?); } let p1 = Point::enc_point_table(ADSK, 1, cs)?; let addr = Point::multiply(&p1, &addr_sk, cs)?; Ok(P2CcircuitInput { hb, coin, delt_ba, rp, enc, addr }) } } pub fn p2c_info( rh: [u64; 4], rcm: [u64; 2], ba: [u64; 2], va: [u64; 2], addr: String, addr_sk: String, enc_random: [u64; 4], ) -> Result<(String,String,String,String,String), Error> { let addr = str2point(addr); let addr_sk = str2sk(addr_sk); let rng = &mut thread_rng(); let j = JubJub::new(); //TODO:Balance&value<2^vbit let mut res: Vec<FrRepr> = vec![]; let proof = create_random_proof::<Bls12, _, _, _>( P2Ccircuit::new( &ph_generator(), &j, Fr::from_repr(FrRepr(rh)).unwrap(), Fr::from_repr(FrRepr([rcm[0], rcm[1], 0, 0])).unwrap(), Fr::from_repr(FrRepr([ba[0], ba[1], 0, 0])).unwrap(), Fr::from_repr(FrRepr([va[0], va[1], 0, 0])).unwrap(), ( Fr::from_repr(FrRepr(addr.0)).unwrap(), Fr::from_repr(FrRepr(addr.1)).unwrap(), ), Fr::from_serial(enc_random), addr_sk, &mut res ), p2c_param()?, rng, )?.serial(); let hb = (res[0].serial(), res[1].serial()); let coin = res[2].serial(); let delt_ba = (res[3].serial(), res[4].serial()); let enc = (res[5].serial(), res[6].serial(),res[7].serial()); Ok((proof2str(proof), point2str(hb), u6442str(coin), point2str(delt_ba), enc2str(enc))) } pub fn p2c_verify( hb: String, coin: String, delt_ba: String, enc: String, address:String, proof: String) -> Result<bool, Error> { let hb = str2point(hb); let coin = str2u644(coin); let delt_ba = str2point(delt_ba); let enc = str2enc(enc); let address = str2point(address); let proof = str2proof(proof); verify_proof(&p2c_vk()?, &Proof::from_serial(proof), |cs| { let delt_x = Fr::from_repr(FrRepr::from_serial(delt_ba.0)).unwrap(); let delt_y = Fr::from_repr(FrRepr::from_serial(delt_ba.1)).unwrap(); let hb_x = Fr::from_repr(FrRepr::from_serial(hb.0)).unwrap(); let hb_y = Fr::from_repr(FrRepr::from_serial(hb.1)).unwrap(); let coin = Fr::from_repr(FrRepr::from_serial(coin)).unwrap(); let rpx = Fr::from_repr(FrRepr::from_serial(enc.0)).unwrap(); let rpy = Fr::from_repr(FrRepr::from_serial(enc.1)).unwrap(); let enc = Fr::from_repr(FrRepr::from_serial(enc.2)).unwrap(); let addrx = Fr::from_repr(FrRepr::from_serial(address.0)).unwrap(); let addry = Fr::from_repr(FrRepr::from_serial(address.1)).unwrap(); Ok(P2CcircuitInput { hb: ( Num::new(cs, Assignment::known(hb_x))?, Num::new(cs, Assignment::known(hb_y))?, ), coin: Num::new(cs, Assignment::known(coin))?, delt_ba: ( Num::new(cs, Assignment::known(delt_x))?, Num::new(cs, Assignment::known(delt_y))?, ), rp: ( Num::new(cs, Assignment::known(rpx))?, Num::new(cs, Assignment::known(rpy))?, ), enc: Num::new(cs, Assignment::known(enc))?, addr:( Num::new(cs, Assignment::known(addrx))?, Num::new(cs, Assignment::known(addry))? ) }) }) } pub(crate) fn gen_p2c_param() { let p2c_param_path = p2c_param_path(); let p2c_param_path = p2c_param_path.to_str().unwrap(); let rng = &mut thread_rng(); let params = generate_random_parameters::<Bls12, _, _>( P2Ccircuit::blank(&ph_generator(), &JubJub::new(), &mut vec![]), rng, ).unwrap(); params .write(&mut File::create(p2c_param_path).unwrap()) .unwrap(); } pub fn p2c_param() -> Result<ProverStream, Error> { let p2c_param_path = p2c_param_path(); let p2c_param_path = p2c_param_path.to_str().unwrap(); let params = ProverStream::new(p2c_param_path).unwrap(); Ok(params) } pub fn p2c_vk() -> Result<(PreparedVerifyingKey<Bls12>), Error> { let p2c_param_path = p2c_param_path(); let p2c_param_path = p2c_param_path.to_str().unwrap(); let mut params = ProverStream::new(p2c_param_path)?; let vk2 = params.get_vk(11)?; let vk = prepare_verifying_key(&vk2); Ok(vk) }
// generated by `sqlx migrate build-script` fn main() { // trigger recompilation when a new migration is added println!("cargo:rerun-if-changed=migrations"); }
use crate::flat; use crate::raw; use crate::typeshape; use crate::typeshape::{desugar, typeshape, FieldShape, TypeShape, WireFormat}; // use crate::raw::Spanned; // use serde::ser::SerializeMap; use serde::{Serialize, Serializer}; use std::collections::HashMap; // impl Serialize for flat::Libraries { // fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error> // where // S: Serializer, // { // let lib = self.libraries.last().unwrap(); // let mut ir = serializer.serialize_map(None)?; // ir.serialize_entry("version", "0.0.1")?; // ir.serialize_entry("name", &lib.name)?; // ir.end() // } // } impl flat::Libraries { pub fn to_ir(mut self) -> Library { // TODO: this block of code does stuff on the library before mutating it (by popping // below) while it's still valid. this should be moved to a separate step, including // storing precomputed constant values. for time reasons of getting this step working // it's here (and half done) for now. in general this step needs to be thought through // some more, e.g. consider moving it along with kinds/types from flat::Validator into // either Libraries (along with flattened scope) or some other thing. let lib = self.libraries.last().unwrap(); let mut typeshapes = HashMap::new(); let mut fieldshapes = HashMap::new(); for (name, entry) in lib.types.iter() { let (_, ty) = &entry.value; let desugared = desugar(&ty.value, &self, false); typeshapes.insert(name.clone(), typeshape(&desugared, WireFormat::V1)); if let flat::Type::Struct(_) = &ty.value { fieldshapes.insert( name.clone(), typeshape::fieldshapes(&desugared, false, WireFormat::V1).unwrap(), ); } } let lib = self.libraries.pop().unwrap(); let lib_id = self.next_library_id(); let id_to_name: HashMap<_, _> = self .name_to_id .into_iter() .map(|(name, id)| (id, name)) .collect(); let mut declmap: HashMap<CompoundIdentifier, DeclType> = HashMap::new(); let mut consts = Vec::new(); for (name, entry) in lib.terms { let (attributes, ty, term) = entry.value; let full_name = CompoundIdentifier { library_name: id_to_name.get(&lib_id).unwrap().clone(), decl_name: name, }; consts.push(ConstDecl { attributes: attributes, ty: to_type(ty.value, &id_to_name, false), name: full_name.clone(), value: to_constant(term.value, &id_to_name), }); declmap.insert(full_name, DeclType::Const); } let mut structs = Vec::new(); let mut bits = Vec::new(); let mut enums = Vec::new(); let mut tables = Vec::new(); let mut unions = Vec::new(); for (name, entry) in lib.types { let (attributes, ty) = entry.value; let full_name = CompoundIdentifier { library_name: id_to_name.get(&lib_id).unwrap().clone(), decl_name: name.clone(), }; match ty.value { flat::Type::Struct(decl) => { let members = decl .members .into_iter() .zip(fieldshapes.remove(&name).unwrap().into_iter()) .map(|(m, fs)| to_structmember(m.value, fs, &id_to_name)) .collect(); structs.push(StructDecl { maybe_attributes: attributes, name: full_name.clone(), anonymous: false, members, type_shape_v1: typeshapes.remove(&name).unwrap(), }); declmap.insert(full_name, DeclType::Struct); } flat::Type::Bits(decl) => { let ty = decl.get_type().clone(); let members = decl .members .into_iter() .map(|m| to_bitsmember(m.value, &id_to_name)) .collect(); bits.push(BitsDecl { maybe_attributes: attributes, name: full_name.clone(), ty: to_type(ty, &id_to_name, false), members, strict: decl.strictness.map_or(true, |s| !s.value.is_flexible()), }); declmap.insert(full_name, DeclType::Bits); } flat::Type::Enum(decl) => { let ty = decl.get_type().clone(); let members = decl .members .into_iter() .map(|m| to_enummember(m.value, &id_to_name)) .collect(); enums.push(EnumDecl { maybe_attributes: attributes, name: full_name.clone(), ty: to_type(ty, &id_to_name, false), members, strict: decl.strictness.map_or(true, |s| !s.value.is_flexible()), }); declmap.insert(full_name, DeclType::Enum); } flat::Type::Table(decl) => { let members = decl .members .into_iter() .map(|m| to_tablemember(m.value, &id_to_name)) .collect(); tables.push(TableDecl { maybe_attributes: attributes, name: full_name.clone(), members, strict: decl.strictness.map_or(false, |s| !s.value.is_flexible()), type_shape_v1: typeshapes.remove(&name).unwrap(), }); declmap.insert(full_name, DeclType::Table); } flat::Type::Union(decl) => { let members = decl .members .into_iter() .map(|m| to_unionmember(m.value, &id_to_name)) .collect(); unions.push(UnionDecl { maybe_attributes: attributes, name: full_name.clone(), members, strict: decl.strictness.map_or(false, |s| !s.value.is_flexible()), type_shape_v1: typeshapes.remove(&name).unwrap(), }); declmap.insert(full_name, DeclType::Union); } _ => panic!("only layouts here"), } } let mut protocols = Vec::new(); for (name, protocol) in lib.protocols { let full_name = CompoundIdentifier { library_name: id_to_name.get(&lib_id).unwrap().clone(), decl_name: name, }; let methods = protocol .value .methods .into_iter() .map(|m| to_method(m.value, &id_to_name)) .collect(); protocols.push(Interface { maybe_attributes: protocol.value.attributes, name: full_name.clone(), methods, }); declmap.insert(full_name, DeclType::Protocol); } let mut services = Vec::new(); for (name, service) in lib.services { let full_name = CompoundIdentifier { library_name: id_to_name.get(&lib_id).unwrap().clone(), decl_name: name, }; let members = service .value .members .into_iter() .map(|m| to_servicemember(m.value, &id_to_name)) .collect(); services.push(Service { maybe_attributes: service.value.attributes, name: full_name.clone(), members, }); declmap.insert(full_name, DeclType::Service); } Library { version: "0.0.1", name: lib.name, // TODO: move instead attributes: lib.attributes, // TODO: move instead consts, structs, bits, enums, tables, unions, protocols, services, declarations: declmap, // library_dependencies: Vec::new(), } } } pub fn to_structmember( member: flat::StructMember, fieldshape: FieldShape, id_to_name: &HashMap<flat::LibraryId, String>, ) -> StructMember { StructMember { maybe_attributes: member.attributes, name: member.name.value, ty: to_type(*member.ty.value, id_to_name, false), field_shape_v1: fieldshape, maybe_default_value: member .default_value .map(|v| to_constant(v.value, id_to_name)), } } pub fn to_bitsmember( member: flat::BitsMember, id_to_name: &HashMap<flat::LibraryId, String>, ) -> BitsMember { BitsMember { name: member.name.value, maybe_attributes: member.attributes, value: to_constant(member.value.value, id_to_name), } } pub fn to_enummember( member: flat::EnumMember, id_to_name: &HashMap<flat::LibraryId, String>, ) -> EnumMember { EnumMember { name: member.name.value, maybe_attributes: member.attributes, value: to_constant(member.value.value, id_to_name), } } pub fn to_tablemember( member: flat::TableMember, id_to_name: &HashMap<flat::LibraryId, String>, ) -> TableMember { let (reserved, ty, name) = match member.inner { flat::TableMemberInner::Reserved => (true, None, None), flat::TableMemberInner::Used { ty, name } => ( false, Some(to_type(*ty.value, id_to_name, false)), Some(name.value), ), }; TableMember { maybe_attributes: member.attributes, ordinal: member.ordinal.value.value as u32, reserved, ty, name, } } pub fn to_unionmember( member: flat::UnionMember, id_to_name: &HashMap<flat::LibraryId, String>, ) -> UnionMember { let (reserved, ty, name) = match member.inner { flat::UnionMemberInner::Reserved => (true, None, None), flat::UnionMemberInner::Used { ty, name } => ( false, Some(to_type(*ty.value, id_to_name, false)), Some(name.value), ), }; UnionMember { maybe_attributes: member.attributes, ordinal: member.ordinal.value.value as u32, reserved, ty, name, } } pub fn to_method(method: flat::Method, _id_to_name: &HashMap<flat::LibraryId, String>) -> Method { Method { maybe_attributes: method.attributes, ordinal: 0, // TODO name: method.name.value, has_request: method.request.is_some(), maybe_request_payload: None, // TODO has_response: method.response.is_some(), maybe_response_payload: None, // TODO is_composed: false, // TODO } } pub fn to_servicemember( member: flat::ServiceMember, id_to_name: &HashMap<flat::LibraryId, String>, ) -> ServiceMember { ServiceMember { maybe_attributes: member.attributes, name: member.name.value, ty: Type { kind: TypeKind::Identifier { identifier: to_name(member.protocol.value, id_to_name), }, nullable: false, }, } } pub fn to_type( ty: flat::Type, id_to_name: &HashMap<flat::LibraryId, String>, nullable: bool, ) -> Type { match ty { // these are stored separately in a foo_declarations field, we don't need // to deal with this until anonymous layouts are introduced flat::Type::Struct(_) | flat::Type::Bits(_) | flat::Type::Enum(_) | flat::Type::Table(_) | flat::Type::Union(_) => panic!("should not get here"), // nothing in the scope should have this type, since it's only used during // validation flat::Type::Int | flat::Type::Any => panic!("should not get here either"), flat::Type::Identifier(n) => Type { kind: TypeKind::Identifier { identifier: to_name(n, id_to_name), }, nullable, }, flat::Type::Ptr(ty) => to_type(*ty.value, id_to_name, true), flat::Type::Array(flat::Array { element_type, .. }) => Type { kind: TypeKind::Array { element_type: Box::new(to_type(*element_type.unwrap().value, id_to_name, nullable)), // TODO: we need to save this inside Libraries, because here the Library // has already been consumed and we can't do eval element_count: 0, }, nullable, }, flat::Type::Vector(flat::Vector { element_type, .. }) => Type { kind: TypeKind::Vector { element_type: Box::new(to_type(*element_type.unwrap().value, id_to_name, nullable)), // TODO: same as for arrays maybe_element_count: None, }, nullable, }, flat::Type::Str(_) => Type { kind: TypeKind::String { // TODO: same as for arrays maybe_element_count: None, }, nullable, }, flat::Type::Handle(subtype) => Type { kind: TypeKind::Handle { // TODO: add a Handle subtype, which is actually just when there is no // subtype. set the subtype to it if none is specified, and remove the Option subtype: subtype.unwrap(), }, nullable, }, flat::Type::ClientEnd(n) => Type { kind: TypeKind::Identifier { identifier: to_name(n, id_to_name), }, nullable, }, flat::Type::ServerEnd(n) => Type { kind: TypeKind::Request { subtype: to_name(n, id_to_name), }, nullable, }, // TODO: we actually do need to handle this, e.g. for a member of type array<foo>:bar, since // it's possible to have non type aliases here (though we'd be able to assume that this is // of kind *). in the same way that we "unflatten" type function application, we'd need to // re flatten them for the IR. either that or we'd need to keep self valid up to here so that // we can eval flat::Type::TypeSubstitution(_) => panic!("fidlc currently doesn't emit these"), flat::Type::Primitive(subtype) => Type { kind: TypeKind::Primitive { subtype }, nullable, }, } } pub fn to_constant(term: flat::Term, id_to_name: &HashMap<flat::LibraryId, String>) -> Constant { match term { flat::Term::Identifier(n) => Constant::Identifier { identifier: to_name(n, id_to_name), }, flat::Term::Str(_) => Constant::Literal { literal: Literal { kind: LiteralKind::String, }, }, flat::Term::Int(_) => Constant::Literal { literal: Literal { kind: LiteralKind::Numeric, }, }, flat::Term::Float(_) => Constant::Literal { literal: Literal { kind: LiteralKind::Numeric, }, }, flat::Term::True => Constant::Literal { literal: Literal { kind: LiteralKind::True, }, }, flat::Term::False => Constant::Literal { literal: Literal { kind: LiteralKind::True, }, }, } } pub fn to_name( name: flat::Name, id_to_name: &HashMap<flat::LibraryId, String>, ) -> CompoundIdentifier { if name.member.is_some() { panic!("todo") } CompoundIdentifier { library_name: id_to_name.get(&name.library).unwrap().clone(), decl_name: name.name, } } #[derive(Debug, Clone, Serialize)] pub struct Library { pub version: &'static str, pub name: String, pub attributes: raw::Attributes, #[serde(rename = "const_declarations")] pub consts: Vec<ConstDecl>, #[serde(rename = "struct_declarations")] pub structs: Vec<StructDecl>, #[serde(rename = "bits_declarations")] pub bits: Vec<BitsDecl>, #[serde(rename = "enum_declarations")] pub enums: Vec<EnumDecl>, #[serde(rename = "table_declarations")] pub tables: Vec<TableDecl>, #[serde(rename = "union_declarations")] pub unions: Vec<UnionDecl>, #[serde(rename = "interface_declarations")] pub protocols: Vec<Interface>, #[serde(rename = "service_declarations")] pub services: Vec<Service>, // pub declaration_order: Vec<String>, pub declarations: HashMap<CompoundIdentifier, DeclType>, // pub library_dependencies: Vec<LibraryDep>, // note: these are used only prior to resolution. // #[serde(skip_serializing, skip_deserializing)] // pub usings: Vec<Spanned<Using>>, } // NOTE: fidlc omits attributes if they're empty. is this behavior necessary? #[derive(Debug, Clone, Serialize)] pub struct ConstDecl { pub attributes: raw::Attributes, #[serde(rename = "type")] pub ty: Type, pub name: CompoundIdentifier, pub value: Constant, } #[derive(Debug, Clone, Serialize)] pub struct StructDecl { pub maybe_attributes: raw::Attributes, pub name: CompoundIdentifier, pub anonymous: bool, pub members: Vec<StructMember>, pub type_shape_v1: TypeShape, } #[derive(Debug, Clone, Serialize)] pub struct StructMember { pub maybe_attributes: raw::Attributes, pub name: String, #[serde(rename = "type")] pub ty: Type, pub field_shape_v1: FieldShape, pub maybe_default_value: Option<Constant>, } #[derive(Debug, Clone, Serialize)] pub struct BitsDecl { pub maybe_attributes: raw::Attributes, pub name: CompoundIdentifier, #[serde(rename = "type")] pub ty: Type, // TODO: mask pub members: Vec<BitsMember>, pub strict: bool, } #[derive(Debug, Clone, Serialize)] pub struct BitsMember { pub name: String, pub maybe_attributes: raw::Attributes, pub value: Constant, } #[derive(Debug, Clone, Serialize)] pub struct EnumDecl { pub maybe_attributes: raw::Attributes, pub name: CompoundIdentifier, #[serde(rename = "type")] pub ty: Type, pub members: Vec<EnumMember>, pub strict: bool, } #[derive(Debug, Clone, Serialize)] pub struct EnumMember { pub name: String, pub maybe_attributes: raw::Attributes, pub value: Constant, } #[derive(Debug, Clone, Serialize)] pub struct TableDecl { pub maybe_attributes: raw::Attributes, pub name: CompoundIdentifier, pub members: Vec<TableMember>, pub strict: bool, pub type_shape_v1: TypeShape, } #[derive(Debug, Clone, Serialize)] pub struct TableMember { pub maybe_attributes: raw::Attributes, pub ordinal: u32, pub reserved: bool, #[serde(rename = "type")] pub ty: Option<Type>, pub name: Option<String>, } #[derive(Debug, Clone, Serialize)] pub struct UnionDecl { pub maybe_attributes: raw::Attributes, pub name: CompoundIdentifier, pub members: Vec<UnionMember>, pub strict: bool, pub type_shape_v1: TypeShape, } #[derive(Debug, Clone, Serialize)] pub struct UnionMember { pub maybe_attributes: raw::Attributes, pub ordinal: u32, pub reserved: bool, #[serde(rename = "type")] pub ty: Option<Type>, pub name: Option<String>, } #[derive(Debug, Clone, Serialize)] pub struct Interface { pub maybe_attributes: raw::Attributes, pub name: CompoundIdentifier, pub methods: Vec<Method>, } #[derive(Debug, Clone, Serialize)] pub struct Method { pub maybe_attributes: raw::Attributes, pub ordinal: u64, pub name: String, pub has_request: bool, pub maybe_request_payload: Option<CompoundIdentifier>, pub has_response: bool, pub maybe_response_payload: Option<CompoundIdentifier>, pub is_composed: bool, } #[derive(Debug, Clone, Serialize)] pub struct Service { pub maybe_attributes: raw::Attributes, pub name: CompoundIdentifier, pub members: Vec<ServiceMember>, } #[derive(Debug, Clone, Serialize)] pub struct ServiceMember { pub maybe_attributes: raw::Attributes, pub name: String, #[serde(rename = "type")] pub ty: Type, } #[derive(Debug, Clone, Serialize)] pub struct Type { #[serde(flatten)] pub kind: TypeKind, pub nullable: bool, } #[derive(Debug, Clone, Serialize)] pub enum TypeKind { Array { element_type: Box<Type>, element_count: u32, }, Vector { element_type: Box<Type>, #[serde(default)] maybe_element_count: Option<u32>, }, String { #[serde(default)] maybe_element_count: Option<u32>, }, Handle { subtype: flat::HandleSubtype, }, Request { subtype: CompoundIdentifier, }, Primitive { subtype: flat::PrimitiveSubtype, }, Identifier { identifier: CompoundIdentifier, }, } #[derive(Debug, Clone, Serialize)] #[serde(tag = "kind")] #[serde(rename_all = "lowercase")] pub enum Constant { Identifier { identifier: CompoundIdentifier }, // missing value, expression Literal { literal: Literal }, // missing value, expression } #[derive(Debug, Clone, Serialize)] pub struct Literal { pub kind: LiteralKind, // #[serde(default)] // pub value: Option<String>, // missing expression } #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "lowercase")] pub enum LiteralKind { String, Numeric, True, False, } #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct CompoundIdentifier { pub library_name: String, pub decl_name: String, } impl Serialize for CompoundIdentifier { fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> { [&self.library_name, "/", &self.decl_name] .concat() .serialize(serializer) } } // TODO: can this be merged with placement? #[derive(Debug, Clone, Serialize)] #[serde(rename_all = "lowercase")] pub enum DeclType { Const, Bits, Enum, #[serde(rename = "interface")] Protocol, Struct, Table, Union, Service, }
#[derive(Copy, Clone, Debug, PartialEq, Hash, Eq)] pub enum Player { White, Black, } impl Player { pub fn other(&self) -> Player { match *self { Player::White => Player::Black, Player::Black => Player::White, } } } #[derive(Copy, Clone, Debug, PartialEq)] pub struct Coordinate { pub x: usize, pub y: usize, } #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq)] pub struct Board { cells: [[Option<Player>; 8]; 8], } impl Board { pub fn initial() -> Board { let mut cells = [[None; 8]; 8]; cells[3][3] = Some(Player::White); cells[4][4] = Some(Player::White); cells[3][4] = Some(Player::Black); cells[4][3] = Some(Player::Black); Board { cells } } pub fn cell(&self, c: Coordinate) -> Option<Player> { self.cells[c.x][c.y] } pub fn count(&self, player: Player) -> i32 { let mut cnt = 0; for x in 0..8 { for y in 0..8 { if let Some(p) = self.cells[x][y] { if p == player { cnt = cnt + 1; } } } } cnt } // return None if invalid pub fn simulate(&self, c: Coordinate, player: Player) -> Option<Board> { if self.cells[c.x][c.y] != None { return None; } let mut cells_to_flip = Vec::new(); for dx in [-1, 0, 1].iter().cloned() { for dy in [-1, 0, 1].iter().cloned() { if dx == 0 && dy == 0 { continue; } for i in 1..8 { let x = c.x as i32 + dx * (i as i32); let y = c.y as i32 + dy * (i as i32); if x < 0 || 7 < x || y < 0 || 7 < y { break; } let x = x as usize; let y = y as usize; if self.cells[x][y] == None { break; } if self.cells[x][y] == Some(player) { for j in 1..i { cells_to_flip.push(Coordinate { x: (c.x as i32 + dx * (j as i32)) as usize, y: (c.y as i32 + dy * (j as i32)) as usize, }); } break; } } } } if cells_to_flip.len() == 0 { return None; } let mut board_updated = Board { cells: self.cells }; board_updated.cells[c.x][c.y] = Some(player); for cell_to_flip in cells_to_flip.iter() { board_updated.cells[cell_to_flip.x][cell_to_flip.y] = Some(player); } Some(board_updated) } pub fn is_valid_move(&self, coordinate: Coordinate, player: Player) -> bool { match self.simulate(coordinate, player) { None => false, Some(_) => true, } } pub fn has_valid_move(&self, player: Player) -> bool { for x in 0..8 { for y in 0..8 { if self.is_valid_move(Coordinate { x, y }, player) { return true; } } } false } }
mod types; use super::type_test::TypeTest; use crate::{connector::Queryable, single::Quaint}; use names::Generator; use once_cell::sync::Lazy; use std::env; static CONN_STR: Lazy<String> = Lazy::new(|| env::var("TEST_MYSQL").expect("TEST_MYSQL env var")); pub struct MySql<'a> { names: Generator<'a>, conn: Quaint, } #[async_trait::async_trait] impl<'a> TypeTest for MySql<'a> { async fn new() -> crate::Result<MySql<'a>> { let names = Generator::default(); let conn = Quaint::new(&CONN_STR).await?; Ok(Self { names, conn }) } async fn create_table(&mut self, r#type: &str) -> crate::Result<String> { let table = self.names.next().unwrap().replace('-', ""); let create_table = format!( r##" CREATE TEMPORARY TABLE `{}` ( `id` int(11) NOT NULL AUTO_INCREMENT, `value` {}, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 "##, table, r#type, ); self.conn.raw_cmd(&create_table).await?; Ok(table) } fn conn(&self) -> &Quaint { &self.conn } }
extern crate carillon; use std::path::Path; use std::process::exit; use clap::{App, Arg, SubCommand}; use log; use log4rs; use carillon::tools; /// # Carillon CLI /// /// Carillon ノードの初期化、起動、停止、状態参照を行うための CLI です。 /// fn main() { let matches = App::new("Carillon CIL") .version("1.0") .author("TAKAMI Torao <koiroha@gmail.com>") .about("A self-sufficient commandline interface for Carillon runtime.") .arg(Arg::with_name("verbose") .short("v") .long("verbose") .multiple(true) .help("Sets the level of verbosity")) .subcommand(SubCommand::with_name("init") .about("Create and initialize a new context directory.") .version("1.0") .author("TAKAMI Torao") .arg(Arg::with_name("DIR") .help("context directory (error if it already exists)") .required(true)) .arg(Arg::with_name("force") .short("f") .long("force") .help("Overwrite without error if the directory exists.")) .arg(Arg::with_name("debug") .short("d") .help("print debug information verbosely"))) .subcommand(SubCommand::with_name("start") .about("Starts a Carillon node based on the specified context directory.") .version("1.0") .author("TAKAMI Torao") .arg(Arg::with_name("DIR") .help("Specify the context directory of node to be launched. If omitted, the current directory is used.") .required(false) .index(1)) .arg(Arg::with_name("debug") .short("d") .long("debug") .help("Print debug information verbosely"))) .get_matches(); // CLI のログ出力設定 let logging_config = { use log4rs::append::console::ConsoleAppender; use log4rs::config::{Appender, Root}; let stdout = ConsoleAppender::builder().build(); let verbose = matches.is_present("verbose"); let level = if verbose { log::LevelFilter::Debug } else { log::LevelFilter::Info }; log4rs::config::Config::builder() .appender(Appender::builder().build("stdout", Box::new(stdout))) .build(Root::builder().appender("stdout").build(level)) .unwrap() }; if let Err(err) = log4rs::init_config(logging_config) { error(&err) } if let Some(matches) = matches.subcommand_matches("init") { // コンテキストディレクトリの新規作成 let init = tools::init::Init { dir: Path::new(matches.value_of("DIR").unwrap()), force: matches.is_present("force"), }; match init.init() { Ok(()) => log::info!( "SUCCESS: The context directory was created successfully: {}", tools::abs_path(init.dir) ), Err(err) => error(&err), } } else if let Some(matches) = matches.subcommand_matches("start") { // ノードの起動 let dir = match matches.value_of("DIR") { Some(dir) => Path::new(dir).to_path_buf(), None => std::env::current_dir().unwrap_or(Path::new(".").to_path_buf()), }; let start = tools::start::Start { dir: &dir }; match start.start() { Ok(()) => log::info!("The carillon node has been deactivated"), Err(err) => error(&err), } } } fn error(err: &dyn std::error::Error) { eprintln!("ERROR: {}", err.to_string()); exit(1) }
use super::*; #[derive(Debug, PartialEq)] pub struct BinaryOp { pub op: BinaryOpKind, pub lhs: Box<Node>, pub rhs: Box<Node>, } #[derive(Debug, PartialEq)] pub enum BinaryOpKind { /// <=> Compare, /// == Equal, /// === CaseEqual, /// != NotEqual, /// =~ RegexMatch, /// !~ NotRegexMatch, /// > GreaterThan, /// >= GreaterEqual, /// < LessThan, /// <= LessEqual, /// | BitOr, /// ^ BitXor, /// & BitAnd, /// << ShiftLeft, /// >> ShiftRight, /// + Add, /// - Subtract, /// * Multiply, /// / Divide, /// % Modulus, /// ** Power, }
extern crate collections; use std::char::is_alphanumeric; use std::io::{IoResult, IoError, Buffer}; use std::string::String; pub enum Node { Atom(String), ParseError(String) } pub fn parse(source: &mut Buffer) -> IoResult<Node> { match source.read_char() { Ok(c) => { if is_alphanumeric(c) { // Read an atom. let mut atom = String::new(); atom.push_char(c); loop { match source.read_char() { Ok(c) => { if is_alphanumeric(c) || c == '_' { atom.push_char(c); } else { // TODO: save c? break; } } Err(e) => return Err(e) } } return Ok(Atom(atom)); } else { return Err(IoError { kind: std::io::OtherIoError, desc: "Unknown error", detail: None}); } } Err(e) => return Err(e) } }
use config::Config; use errors::*; use clap::{App, Arg, ArgMatches, SubCommand}; pub fn setup<'a, 'b>() -> App<'a, 'b> { SubCommand::with_name("rm") .about("Removes a user") .arg( Arg::with_name("USER") .help("Specifies the user") .required(true) .index(1) ) } pub fn call(args: &ArgMatches) -> Result<()> { // Load the config let config_file = args.value_of("config").unwrap(); let mut config = Config::load(config_file)?; // Remove the user, if existing let user = args.value_of("USER").unwrap(); if config.users.remove(user).is_none() { bail!(format!("A user named '{}' does not exist", user)); // TODO Use proper error! } // Store the config config.store(config_file)?; Ok(()) }
use super::VarResult; use crate::ast::syntax_type::{FunctionType, FunctionTypes, SimpleSyntaxType, SyntaxType}; use crate::helper::{pine_ref_to_f64, pine_ref_to_i64}; use crate::runtime::context::{downcast_ctx, Ctx}; use crate::types::{Callable, Float, Int, PineFrom, PineRef, RuntimeErr, Series, SeriesCall, NA}; use std::mem; use std::mem::transmute; use std::rc::Rc; #[derive(Debug, Clone, PartialEq)] struct MathCallVal { func: *mut (), } impl MathCallVal { pub fn new(func: *mut ()) -> MathCallVal { MathCallVal { func } } } impl<'a> SeriesCall<'a> for MathCallVal { fn step( &mut self, _ctx: &mut dyn Ctx<'a>, mut param: Vec<Option<PineRef<'a>>>, func_type: FunctionType<'a>, ) -> Result<PineRef<'a>, RuntimeErr> { let xval = mem::replace(&mut param[0], None); let handler = unsafe { transmute::<_, fn(Option<PineRef<'a>>) -> Float>(self.func) }; match ((func_type.signature.0)[0]).1 { SyntaxType::Simple(SimpleSyntaxType::Float) => { let res = handler(xval); Ok(PineRef::new_box(res)) } SyntaxType::Series(SimpleSyntaxType::Float) => { let res = handler(xval); Ok(PineRef::new_rc(Series::from(res))) } _ => unreachable!(), } } fn copy(&self) -> Box<dyn SeriesCall<'a> + 'a> { Box::new(self.clone()) } } pub const VAR_NAME: &'static str = "cos"; pub fn declare_math_var<'a>( varname: &'static str, func: fn(Option<PineRef<'a>>) -> Float, ) -> VarResult<'a> { let value = PineRef::new(Callable::new( None, Some(Box::new(MathCallVal::new(func as *mut ()))), )); let func_type = FunctionTypes(vec![ FunctionType::new((vec![("x", SyntaxType::float())], SyntaxType::float())), FunctionType::new(( vec![("x", SyntaxType::float_series())], SyntaxType::float_series(), )), ]); let syntax_type = SyntaxType::Function(Rc::new(func_type)); VarResult::new(value, syntax_type, varname) } fn float_cos<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.cos()), } } pub fn declare_cos_var<'a>() -> VarResult<'a> { declare_math_var("cos", float_cos) } fn float_acos<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.acos()), } } pub fn declare_acos_var<'a>() -> VarResult<'a> { declare_math_var("acos", float_acos) } fn float_sin<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.sin()), } } pub fn declare_sin_var<'a>() -> VarResult<'a> { declare_math_var("sin", float_sin) } fn float_asin<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.asin()), } } pub fn declare_asin_var<'a>() -> VarResult<'a> { declare_math_var("asin", float_asin) } fn float_tan<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.tan()), } } pub fn declare_tan_var<'a>() -> VarResult<'a> { declare_math_var("tan", float_tan) } fn float_atan<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.atan()), } } pub fn declare_atan_var<'a>() -> VarResult<'a> { declare_math_var("atan", float_atan) } fn float_sqrt<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.sqrt()), } } pub fn declare_sqrt_var<'a>() -> VarResult<'a> { declare_math_var("sqrt", float_sqrt) } fn float_exp<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.exp()), } } pub fn declare_exp_var<'a>() -> VarResult<'a> { declare_math_var("exp", float_exp) } fn float_log<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.log(std::f64::consts::E)), } } pub fn declare_log_var<'a>() -> VarResult<'a> { declare_math_var("log", float_log) } fn float_log10<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) => Some(v.log10()), } } pub fn declare_log10_var<'a>() -> VarResult<'a> { declare_math_var("log10", float_log10) } fn float_sign<'a>(xval: Option<PineRef<'a>>) -> Float { match pine_ref_to_f64(xval) { None => None, Some(v) if v > 0f64 => Some(1f64), Some(v) if v == 0f64 => Some(0f64), Some(v) if v < 0f64 => Some(-1f64), Some(_) => unreachable!(), } } pub fn declare_sign_var<'a>() -> VarResult<'a> { declare_math_var("sign", float_sign) } #[cfg(test)] mod tests { use super::*; use crate::ast::stat_expr_types::VarIndex; use crate::ast::syntax_type::SimpleSyntaxType; use crate::runtime::{AnySeries, NoneCallback, VarOperate}; use crate::{LibInfo, PineParser, PineRunner}; #[test] fn cos_test() { let lib_info = LibInfo::new( vec![ declare_cos_var(), declare_acos_var(), declare_sin_var(), declare_asin_var(), declare_tan_var(), declare_atan_var(), declare_sqrt_var(), declare_exp_var(), declare_log_var(), declare_log10_var(), declare_sign_var(), ], vec![("close", SyntaxType::Series(SimpleSyntaxType::Float))], ); let src = " m1 = cos(0)\nm2 = acos(1)\n m3 = sin(0)\nm4 = asin(0)\n m5 = tan(0)\nm6 = atan(0)\n m7 = sqrt(16)\nm8 = exp(3)\n m9 = log(exp(3))\nm10 = log10(100)\n m11 = sign(12)\n "; let blk = PineParser::new(src, &lib_info).parse_blk().unwrap(); let mut runner = PineRunner::new(&lib_info, &blk, &NoneCallback()); runner .run( &vec![("close", AnySeries::from_float_vec(vec![Some(-2f64)]))], None, ) .unwrap(); let starti = 0; assert_eq!( runner.get_context().move_var(VarIndex::new(starti, 0)), Some(PineRef::new(Some(1f64))) ); assert_eq!( runner.get_context().move_var(VarIndex::new(starti + 1, 0)), Some(PineRef::new(Some(0f64))) ); assert_eq!( runner.get_context().move_var(VarIndex::new(starti + 2, 0)), Some(PineRef::new(Some(0f64))) ); assert_eq!( runner.get_context().move_var(VarIndex::new(starti + 3, 0)), Some(PineRef::new(Some(0f64))) ); assert_eq!( runner.get_context().move_var(VarIndex::new(starti + 4, 0)), Some(PineRef::new(Some(0f64))) ); assert_eq!( runner.get_context().move_var(VarIndex::new(starti + 5, 0)), Some(PineRef::new(Some(0f64))) ); assert_eq!( runner.get_context().move_var(VarIndex::new(starti + 6, 0)), Some(PineRef::new(Some(4f64))) ); let result = runner.get_context().move_var(VarIndex::new(starti + 7, 0)); assert_eq!( Float::implicity_from(result.unwrap()) .unwrap() .into_inner() .unwrap() .floor(), std::f64::consts::E.powf(3f64).floor() ); assert_eq!( runner.get_context().move_var(VarIndex::new(starti + 8, 0)), Some(PineRef::new(Some(3f64))) ); assert_eq!( runner.get_context().move_var(VarIndex::new(starti + 9, 0)), Some(PineRef::new(Some(2f64))) ); assert_eq!( runner.get_context().move_var(VarIndex::new(starti + 10, 0)), Some(PineRef::new(Some(1f64))) ); } }
#[doc = r"Value read from the register"] pub struct R { bits: u32, } #[doc = r"Value to write to the register"] pub struct W { bits: u32, } impl super::BOOTCFG { #[doc = r"Modifies the contents of the register"] #[inline(always)] pub fn modify<F>(&self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W, { let bits = self.register.get(); self.register.set(f(&R { bits }, &mut W { bits }).bits); } #[doc = r"Reads the contents of the register"] #[inline(always)] pub fn read(&self) -> R { R { bits: self.register.get(), } } #[doc = r"Writes to the register"] #[inline(always)] pub fn write<F>(&self, f: F) where F: FnOnce(&mut W) -> &mut W, { self.register.set( f(&mut W { bits: Self::reset_value(), }) .bits, ); } #[doc = r"Reset value of the register"] #[inline(always)] pub const fn reset_value() -> u32 { 0 } #[doc = r"Writes the reset value to the register"] #[inline(always)] pub fn reset(&self) { self.register.set(Self::reset_value()) } } #[doc = r"Value of the field"] pub struct FLASH_BOOTCFG_DBG0R { bits: bool, } impl FLASH_BOOTCFG_DBG0R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_BOOTCFG_DBG0W<'a> { w: &'a mut W, } impl<'a> _FLASH_BOOTCFG_DBG0W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 0); self.w.bits |= ((value as u32) & 1) << 0; self.w } } #[doc = r"Value of the field"] pub struct FLASH_BOOTCFG_DBG1R { bits: bool, } impl FLASH_BOOTCFG_DBG1R { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_BOOTCFG_DBG1W<'a> { w: &'a mut W, } impl<'a> _FLASH_BOOTCFG_DBG1W<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 1); self.w.bits |= ((value as u32) & 1) << 1; self.w } } #[doc = r"Value of the field"] pub struct FLASH_BOOTCFG_KEYR { bits: bool, } impl FLASH_BOOTCFG_KEYR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_BOOTCFG_KEYW<'a> { w: &'a mut W, } impl<'a> _FLASH_BOOTCFG_KEYW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 4); self.w.bits |= ((value as u32) & 1) << 4; self.w } } #[doc = r"Value of the field"] pub struct FLASH_BOOTCFG_ENR { bits: bool, } impl FLASH_BOOTCFG_ENR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_BOOTCFG_ENW<'a> { w: &'a mut W, } impl<'a> _FLASH_BOOTCFG_ENW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 8); self.w.bits |= ((value as u32) & 1) << 8; self.w } } #[doc = r"Value of the field"] pub struct FLASH_BOOTCFG_POLR { bits: bool, } impl FLASH_BOOTCFG_POLR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_BOOTCFG_POLW<'a> { w: &'a mut W, } impl<'a> _FLASH_BOOTCFG_POLW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 9); self.w.bits |= ((value as u32) & 1) << 9; self.w } } #[doc = "Possible values of the field `FLASH_BOOTCFG_PIN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FLASH_BOOTCFG_PINR { #[doc = "Pin 0"] FLASH_BOOTCFG_PIN_0, #[doc = "Pin 1"] FLASH_BOOTCFG_PIN_1, #[doc = "Pin 2"] FLASH_BOOTCFG_PIN_2, #[doc = "Pin 3"] FLASH_BOOTCFG_PIN_3, #[doc = "Pin 4"] FLASH_BOOTCFG_PIN_4, #[doc = "Pin 5"] FLASH_BOOTCFG_PIN_5, #[doc = "Pin 6"] FLASH_BOOTCFG_PIN_6, #[doc = "Pin 7"] FLASH_BOOTCFG_PIN_7, } impl FLASH_BOOTCFG_PINR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_0 => 0, FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_1 => 1, FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_2 => 2, FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_3 => 3, FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_4 => 4, FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_5 => 5, FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_6 => 6, FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_7 => 7, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> FLASH_BOOTCFG_PINR { match value { 0 => FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_0, 1 => FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_1, 2 => FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_2, 3 => FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_3, 4 => FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_4, 5 => FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_5, 6 => FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_6, 7 => FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_7, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PIN_0`"] #[inline(always)] pub fn is_flash_bootcfg_pin_0(&self) -> bool { *self == FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_0 } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PIN_1`"] #[inline(always)] pub fn is_flash_bootcfg_pin_1(&self) -> bool { *self == FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_1 } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PIN_2`"] #[inline(always)] pub fn is_flash_bootcfg_pin_2(&self) -> bool { *self == FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_2 } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PIN_3`"] #[inline(always)] pub fn is_flash_bootcfg_pin_3(&self) -> bool { *self == FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_3 } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PIN_4`"] #[inline(always)] pub fn is_flash_bootcfg_pin_4(&self) -> bool { *self == FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_4 } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PIN_5`"] #[inline(always)] pub fn is_flash_bootcfg_pin_5(&self) -> bool { *self == FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_5 } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PIN_6`"] #[inline(always)] pub fn is_flash_bootcfg_pin_6(&self) -> bool { *self == FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_6 } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PIN_7`"] #[inline(always)] pub fn is_flash_bootcfg_pin_7(&self) -> bool { *self == FLASH_BOOTCFG_PINR::FLASH_BOOTCFG_PIN_7 } } #[doc = "Values that can be written to the field `FLASH_BOOTCFG_PIN`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FLASH_BOOTCFG_PINW { #[doc = "Pin 0"] FLASH_BOOTCFG_PIN_0, #[doc = "Pin 1"] FLASH_BOOTCFG_PIN_1, #[doc = "Pin 2"] FLASH_BOOTCFG_PIN_2, #[doc = "Pin 3"] FLASH_BOOTCFG_PIN_3, #[doc = "Pin 4"] FLASH_BOOTCFG_PIN_4, #[doc = "Pin 5"] FLASH_BOOTCFG_PIN_5, #[doc = "Pin 6"] FLASH_BOOTCFG_PIN_6, #[doc = "Pin 7"] FLASH_BOOTCFG_PIN_7, } impl FLASH_BOOTCFG_PINW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_0 => 0, FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_1 => 1, FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_2 => 2, FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_3 => 3, FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_4 => 4, FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_5 => 5, FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_6 => 6, FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_7 => 7, } } } #[doc = r"Proxy"] pub struct _FLASH_BOOTCFG_PINW<'a> { w: &'a mut W, } impl<'a> _FLASH_BOOTCFG_PINW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FLASH_BOOTCFG_PINW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Pin 0"] #[inline(always)] pub fn flash_bootcfg_pin_0(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_0) } #[doc = "Pin 1"] #[inline(always)] pub fn flash_bootcfg_pin_1(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_1) } #[doc = "Pin 2"] #[inline(always)] pub fn flash_bootcfg_pin_2(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_2) } #[doc = "Pin 3"] #[inline(always)] pub fn flash_bootcfg_pin_3(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_3) } #[doc = "Pin 4"] #[inline(always)] pub fn flash_bootcfg_pin_4(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_4) } #[doc = "Pin 5"] #[inline(always)] pub fn flash_bootcfg_pin_5(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_5) } #[doc = "Pin 6"] #[inline(always)] pub fn flash_bootcfg_pin_6(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_6) } #[doc = "Pin 7"] #[inline(always)] pub fn flash_bootcfg_pin_7(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PINW::FLASH_BOOTCFG_PIN_7) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(7 << 10); self.w.bits |= ((value as u32) & 7) << 10; self.w } } #[doc = "Possible values of the field `FLASH_BOOTCFG_PORT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FLASH_BOOTCFG_PORTR { #[doc = "Port A"] FLASH_BOOTCFG_PORT_A, #[doc = "Port B"] FLASH_BOOTCFG_PORT_B, #[doc = "Port C"] FLASH_BOOTCFG_PORT_C, #[doc = "Port D"] FLASH_BOOTCFG_PORT_D, #[doc = "Port E"] FLASH_BOOTCFG_PORT_E, #[doc = "Port F"] FLASH_BOOTCFG_PORT_F, #[doc = "Port G"] FLASH_BOOTCFG_PORT_G, #[doc = "Port H"] FLASH_BOOTCFG_PORT_H, } impl FLASH_BOOTCFG_PORTR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bits(&self) -> u8 { match *self { FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_A => 0, FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_B => 1, FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_C => 2, FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_D => 3, FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_E => 4, FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_F => 5, FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_G => 6, FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_H => 7, } } #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _from(value: u8) -> FLASH_BOOTCFG_PORTR { match value { 0 => FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_A, 1 => FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_B, 2 => FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_C, 3 => FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_D, 4 => FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_E, 5 => FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_F, 6 => FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_G, 7 => FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_H, _ => unreachable!(), } } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PORT_A`"] #[inline(always)] pub fn is_flash_bootcfg_port_a(&self) -> bool { *self == FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_A } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PORT_B`"] #[inline(always)] pub fn is_flash_bootcfg_port_b(&self) -> bool { *self == FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_B } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PORT_C`"] #[inline(always)] pub fn is_flash_bootcfg_port_c(&self) -> bool { *self == FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_C } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PORT_D`"] #[inline(always)] pub fn is_flash_bootcfg_port_d(&self) -> bool { *self == FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_D } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PORT_E`"] #[inline(always)] pub fn is_flash_bootcfg_port_e(&self) -> bool { *self == FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_E } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PORT_F`"] #[inline(always)] pub fn is_flash_bootcfg_port_f(&self) -> bool { *self == FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_F } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PORT_G`"] #[inline(always)] pub fn is_flash_bootcfg_port_g(&self) -> bool { *self == FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_G } #[doc = "Checks if the value of the field is `FLASH_BOOTCFG_PORT_H`"] #[inline(always)] pub fn is_flash_bootcfg_port_h(&self) -> bool { *self == FLASH_BOOTCFG_PORTR::FLASH_BOOTCFG_PORT_H } } #[doc = "Values that can be written to the field `FLASH_BOOTCFG_PORT`"] #[derive(Clone, Copy, Debug, PartialEq)] pub enum FLASH_BOOTCFG_PORTW { #[doc = "Port A"] FLASH_BOOTCFG_PORT_A, #[doc = "Port B"] FLASH_BOOTCFG_PORT_B, #[doc = "Port C"] FLASH_BOOTCFG_PORT_C, #[doc = "Port D"] FLASH_BOOTCFG_PORT_D, #[doc = "Port E"] FLASH_BOOTCFG_PORT_E, #[doc = "Port F"] FLASH_BOOTCFG_PORT_F, #[doc = "Port G"] FLASH_BOOTCFG_PORT_G, #[doc = "Port H"] FLASH_BOOTCFG_PORT_H, } impl FLASH_BOOTCFG_PORTW { #[allow(missing_docs)] #[doc(hidden)] #[inline(always)] pub fn _bits(&self) -> u8 { match *self { FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_A => 0, FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_B => 1, FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_C => 2, FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_D => 3, FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_E => 4, FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_F => 5, FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_G => 6, FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_H => 7, } } } #[doc = r"Proxy"] pub struct _FLASH_BOOTCFG_PORTW<'a> { w: &'a mut W, } impl<'a> _FLASH_BOOTCFG_PORTW<'a> { #[doc = r"Writes `variant` to the field"] #[inline(always)] pub fn variant(self, variant: FLASH_BOOTCFG_PORTW) -> &'a mut W { { self.bits(variant._bits()) } } #[doc = "Port A"] #[inline(always)] pub fn flash_bootcfg_port_a(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_A) } #[doc = "Port B"] #[inline(always)] pub fn flash_bootcfg_port_b(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_B) } #[doc = "Port C"] #[inline(always)] pub fn flash_bootcfg_port_c(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_C) } #[doc = "Port D"] #[inline(always)] pub fn flash_bootcfg_port_d(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_D) } #[doc = "Port E"] #[inline(always)] pub fn flash_bootcfg_port_e(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_E) } #[doc = "Port F"] #[inline(always)] pub fn flash_bootcfg_port_f(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_F) } #[doc = "Port G"] #[inline(always)] pub fn flash_bootcfg_port_g(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_G) } #[doc = "Port H"] #[inline(always)] pub fn flash_bootcfg_port_h(self) -> &'a mut W { self.variant(FLASH_BOOTCFG_PORTW::FLASH_BOOTCFG_PORT_H) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bits(self, value: u8) -> &'a mut W { self.w.bits &= !(7 << 13); self.w.bits |= ((value as u32) & 7) << 13; self.w } } #[doc = r"Value of the field"] pub struct FLASH_BOOTCFG_NWR { bits: bool, } impl FLASH_BOOTCFG_NWR { #[doc = r"Value of the field as raw bits"] #[inline(always)] pub fn bit(&self) -> bool { self.bits } #[doc = r"Returns `true` if the bit is clear (0)"] #[inline(always)] pub fn bit_is_clear(&self) -> bool { !self.bit() } #[doc = r"Returns `true` if the bit is set (1)"] #[inline(always)] pub fn bit_is_set(&self) -> bool { self.bit() } } #[doc = r"Proxy"] pub struct _FLASH_BOOTCFG_NWW<'a> { w: &'a mut W, } impl<'a> _FLASH_BOOTCFG_NWW<'a> { #[doc = r"Sets the field bit"] #[inline(always)] pub fn set_bit(self) -> &'a mut W { self.bit(true) } #[doc = r"Clears the field bit"] #[inline(always)] pub fn clear_bit(self) -> &'a mut W { self.bit(false) } #[doc = r"Writes raw bits to the field"] #[inline(always)] pub fn bit(self, value: bool) -> &'a mut W { self.w.bits &= !(1 << 31); self.w.bits |= ((value as u32) & 1) << 31; self.w } } impl R { #[doc = r"Value of the register as raw bits"] #[inline(always)] pub fn bits(&self) -> u32 { self.bits } #[doc = "Bit 0 - Debug Control 0"] #[inline(always)] pub fn flash_bootcfg_dbg0(&self) -> FLASH_BOOTCFG_DBG0R { let bits = ((self.bits >> 0) & 1) != 0; FLASH_BOOTCFG_DBG0R { bits } } #[doc = "Bit 1 - Debug Control 1"] #[inline(always)] pub fn flash_bootcfg_dbg1(&self) -> FLASH_BOOTCFG_DBG1R { let bits = ((self.bits >> 1) & 1) != 0; FLASH_BOOTCFG_DBG1R { bits } } #[doc = "Bit 4 - KEY Select"] #[inline(always)] pub fn flash_bootcfg_key(&self) -> FLASH_BOOTCFG_KEYR { let bits = ((self.bits >> 4) & 1) != 0; FLASH_BOOTCFG_KEYR { bits } } #[doc = "Bit 8 - Boot GPIO Enable"] #[inline(always)] pub fn flash_bootcfg_en(&self) -> FLASH_BOOTCFG_ENR { let bits = ((self.bits >> 8) & 1) != 0; FLASH_BOOTCFG_ENR { bits } } #[doc = "Bit 9 - Boot GPIO Polarity"] #[inline(always)] pub fn flash_bootcfg_pol(&self) -> FLASH_BOOTCFG_POLR { let bits = ((self.bits >> 9) & 1) != 0; FLASH_BOOTCFG_POLR { bits } } #[doc = "Bits 10:12 - Boot GPIO Pin"] #[inline(always)] pub fn flash_bootcfg_pin(&self) -> FLASH_BOOTCFG_PINR { FLASH_BOOTCFG_PINR::_from(((self.bits >> 10) & 7) as u8) } #[doc = "Bits 13:15 - Boot GPIO Port"] #[inline(always)] pub fn flash_bootcfg_port(&self) -> FLASH_BOOTCFG_PORTR { FLASH_BOOTCFG_PORTR::_from(((self.bits >> 13) & 7) as u8) } #[doc = "Bit 31 - Not Written"] #[inline(always)] pub fn flash_bootcfg_nw(&self) -> FLASH_BOOTCFG_NWR { let bits = ((self.bits >> 31) & 1) != 0; FLASH_BOOTCFG_NWR { bits } } } impl W { #[doc = r"Writes raw bits to the register"] #[inline(always)] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } #[doc = "Bit 0 - Debug Control 0"] #[inline(always)] pub fn flash_bootcfg_dbg0(&mut self) -> _FLASH_BOOTCFG_DBG0W { _FLASH_BOOTCFG_DBG0W { w: self } } #[doc = "Bit 1 - Debug Control 1"] #[inline(always)] pub fn flash_bootcfg_dbg1(&mut self) -> _FLASH_BOOTCFG_DBG1W { _FLASH_BOOTCFG_DBG1W { w: self } } #[doc = "Bit 4 - KEY Select"] #[inline(always)] pub fn flash_bootcfg_key(&mut self) -> _FLASH_BOOTCFG_KEYW { _FLASH_BOOTCFG_KEYW { w: self } } #[doc = "Bit 8 - Boot GPIO Enable"] #[inline(always)] pub fn flash_bootcfg_en(&mut self) -> _FLASH_BOOTCFG_ENW { _FLASH_BOOTCFG_ENW { w: self } } #[doc = "Bit 9 - Boot GPIO Polarity"] #[inline(always)] pub fn flash_bootcfg_pol(&mut self) -> _FLASH_BOOTCFG_POLW { _FLASH_BOOTCFG_POLW { w: self } } #[doc = "Bits 10:12 - Boot GPIO Pin"] #[inline(always)] pub fn flash_bootcfg_pin(&mut self) -> _FLASH_BOOTCFG_PINW { _FLASH_BOOTCFG_PINW { w: self } } #[doc = "Bits 13:15 - Boot GPIO Port"] #[inline(always)] pub fn flash_bootcfg_port(&mut self) -> _FLASH_BOOTCFG_PORTW { _FLASH_BOOTCFG_PORTW { w: self } } #[doc = "Bit 31 - Not Written"] #[inline(always)] pub fn flash_bootcfg_nw(&mut self) -> _FLASH_BOOTCFG_NWW { _FLASH_BOOTCFG_NWW { w: self } } }
#[macro_use] extern crate criterion; extern crate threads_pool; use criterion::{black_box, Criterion}; use std::sync::atomic; use threads_pool::prelude::*; fn pool_base(size: usize, bound: usize) { let mut pool = ThreadPool::new(size); for num in 1..bound { pool.exec( move || { for _ in 1..num % 4 { atomic::spin_loop_hint(); } }, false, ) .unwrap_or_default(); } pool.close(); } fn pool_bench(c: &mut Criterion) { c.bench_function("base pool measurement", |b| { b.iter(|| pool_base(black_box(16), black_box(400))) }); } fn single_bench(c: &mut Criterion) { shared_mode::initialize(black_box(16)); let bound = black_box(400); c.bench_function("base single mode measurement", move |b| { b.iter(|| { for num in 1..bound { shared_mode::run(move || { for _ in 1..num % 16 { atomic::spin_loop_hint(); } }); } }) }); shared_mode::close(); } criterion_group!(benches, pool_bench, single_bench); criterion_main!(benches);
//! Independent traits //! //! This implements `Rng` for any `CryptoRng` implicitly. //! //! Note: this *only* considers the next_u32 member function //! //! Thoughts: this is basically equivalent to extends_Rng2. // ——— traits ——— #[derive(Debug)] struct CryptoError; trait CryptoRng { fn try_next_u32(&mut self) -> Result<u32, CryptoError>; } trait Rng { fn next_u32(&mut self) -> u32; } // ——— impls ——— impl<CR: CryptoRng+?Sized> Rng for CR { fn next_u32(&mut self) -> u32 { self.try_next_u32().unwrap() } } // Required for `as_rng(&mut rng)` and `as_rng_ref` definition. impl<'a, R: Rng+?Sized> CryptoRng for &'a mut R { fn try_next_u32(&mut self) -> Result<u32, CryptoError> { Ok((*self).next_u32()) } } // ——— adaptor ——— // Given `rng` of type `T` where `T: Rng`, this can consume // `rng` (`as_rng(rng)`) fn as_crng<R: Rng>(rng: R) -> AsCRng<R> { AsCRng { rng } } struct AsCRng<R: Rng+?Sized> { rng: R } impl<R: Rng+?Sized> CryptoRng for AsCRng<R> { fn try_next_u32(&mut self) -> Result<u32, CryptoError> { Ok(self.rng.next_u32()) } } // ——— test RNGs ——— // A non-crypto Rng #[derive(Debug)] struct TestRng(u32); impl Rng for TestRng { fn next_u32(&mut self) -> u32 { self.0 } } // A CryptoRng #[derive(Debug)] struct TestCRng(u32); impl CryptoRng for TestCRng { fn try_next_u32(&mut self) -> Result<u32, CryptoError> { Ok(self.0) } } // ——— usage ——— fn main() { let mut t = TestRng(13); let mut c = TestCRng(42); println!("t: {:?} impls Rng", t); println!("c: {:?} impls CryptoRng", c); { // Do both traits support both functions via static dispatch? println!("t, static dispatch, using CryptoRng: {:?}", (&mut t).try_next_u32()); println!("t, static dispatch, using Rng: {:?}", t.next_u32()); println!("c, static dispatch, using CryptoRng: {:?}", c.try_next_u32()); println!("c, static dispatch, using Rng: {:?}", c.next_u32()); } { // Can both types be used via CryptoRng with dynamic dispatch? let cr = &mut c as &mut CryptoRng; println!("c, dynamic dispatch, using CryptoRng: {:?}", cr.try_next_u32()); let mut tr = as_crng(&mut t as &mut Rng); println!("t, dynamic dispatch, using CryptoRng: {:?}", tr.try_next_u32()); } { // Can both types be used via Rng with dynamic dispatch? let cr = &mut c as &mut Rng; let tr = &mut t as &mut Rng; println!("c, dynamic dispatch, using Rng: {:?}", cr.next_u32()); println!("t, dynamic dispatch, using Rng: {:?}", tr.next_u32()); } }
fn naive(s: &mut Vec<char>) { s.sort(); if s.iter().collect::<String>().parse::<i32>().unwrap() % 8 == 0 { println!("Yes"); return; } while s.next_permutation() { if s.iter().collect::<String>().parse::<i32>().unwrap() % 8 == 0 { println!("Yes"); return; } } println!("No"); } fn main() { let stdin = std::io::stdin(); let mut rd = ProconReader::new(stdin.lock()); let s: String = rd.get(); let mut s: Vec<char> = s.chars().collect(); if s.len() <= 3 { naive(&mut s); return; } let s = s .iter() .map(|&c| c as usize - '0' as usize) .collect::<Vec<_>>(); let mut freq = vec![0; 10]; for &d in &s { freq[d] += 1; } for k in 100..=999 { if k % 8 != 0 { continue; } let mut f = vec![0; 10]; f[k % 10] += 1; f[(k / 10) % 10] += 1; f[(k / 100) % 10] += 1; let ok = (0..10).all(|d| f[d] <= freq[d]); if ok { println!("Yes"); return; } } println!("No"); } pub trait NextPermutation { fn next_permutation(&mut self) -> bool; } impl<T: Ord> NextPermutation for [T] { /// 数列を辞書順でひとつ進めます。進めなかったら false を返します。 /// /// # Examples /// ``` /// use next_permutation::NextPermutation; /// let mut a = vec![1, 2, 3]; /// a.next_permutation(); /// assert_eq!(a, vec![1, 3, 2]); /// a.next_permutation(); /// assert_eq!(a, vec![2, 1, 3]); /// let mut a = vec![3, 2, 1]; /// assert!(!a.next_permutation()); /// ``` fn next_permutation(&mut self) -> bool { if self.len() <= 0 { return false; } let mut i = self.len() - 1; while i > 0 && self[i - 1] >= self[i] { i -= 1; } if i == 0 { return false; } let mut j = self.len() - 1; while self[i - 1] >= self[j] { j -= 1; } self.swap(i - 1, j); self[i..].reverse(); return true; } } pub struct ProconReader<R: std::io::Read> { reader: R, } impl<R: std::io::Read> ProconReader<R> { pub fn new(reader: R) -> Self { Self { reader } } pub fn get<T: std::str::FromStr>(&mut self) -> T { use std::io::Read; let buf = self .reader .by_ref() .bytes() .map(|b| b.unwrap()) .skip_while(|&byte| byte == b' ' || byte == b'\n' || byte == b'\r') .take_while(|&byte| byte != b' ' && byte != b'\n' && byte != b'\r') .collect::<Vec<_>>(); std::str::from_utf8(&buf) .unwrap() .parse() .ok() .expect("Parse Error.") } }
//! Checks that fields on interface fragment spreads resolve okay. //! See [#922](https://github.com/graphql-rust/juniper/issues/922) for details. use juniper::{ graphql_interface, graphql_object, graphql_value, graphql_vars, EmptyMutation, EmptySubscription, GraphQLObject, }; struct Query; #[graphql_object] impl Query { fn characters() -> Vec<CharacterValue> { vec![ Into::into(Human { id: 0, name: "human-32".into(), }), Into::into(Droid { id: 1, name: "R2-D2".into(), }), ] } } #[graphql_interface(for = [Human, Droid])] trait Character { fn id(&self) -> i32; fn name(&self) -> String; } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Human { pub id: i32, pub name: String, } #[derive(GraphQLObject)] #[graphql(impl = CharacterValue)] struct Droid { pub id: i32, pub name: String, } type Schema = juniper::RootNode<'static, Query, EmptyMutation, EmptySubscription>; #[tokio::test] async fn fragment_on_interface() { let query = r#" query Query { characters { ...CharacterFragment } } fragment CharacterFragment on Character { __typename ... on Human { id name } ... on Droid { id name } } "#; let schema = Schema::new(Query, EmptyMutation::new(), EmptySubscription::new()); let (res, errors) = juniper::execute(query, None, &schema, &graphql_vars! {}, &()) .await .unwrap(); assert_eq!(errors.len(), 0); assert_eq!( res, graphql_value!({ "characters": [ {"__typename": "Human", "id": 0, "name": "human-32"}, {"__typename": "Droid", "id": 1, "name": "R2-D2"}, ], }), ); let (res, errors) = juniper::execute_sync(query, None, &schema, &graphql_vars! {}, &()).unwrap(); assert_eq!(errors.len(), 0); assert_eq!( res, graphql_value!({ "characters": [ {"__typename": "Human", "id": 0, "name": "human-32"}, {"__typename": "Droid", "id": 1, "name": "R2-D2"}, ], }), ); }
// https://leetcode.com/problems/find-n-unique-integers-sum-up-to-zero/submissions/ impl Solution { pub fn sum_zero(n: i32) -> Vec<i32> { let mut unique_array = Vec::with_capacity(n as usize); for i in 1..n { unique_array.push(i); } unique_array.push(-(n * (n - 1)) / 2); unique_array } }
/* origin: FreeBSD /usr/src/lib/msun/src/s_sin.c */ /* * ==================================================== * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunPro, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ==================================================== */ use super::{get_high_word, k_cos, k_sin, rem_pio2}; #[cfg_attr(all(test, assert_no_panic), no_panic::no_panic)] pub fn sincos(x: f64) -> (f64, f64) { let s: f64; let c: f64; let mut ix: u32; ix = get_high_word(x); ix &= 0x7fffffff; /* |x| ~< pi/4 */ if ix <= 0x3fe921fb { /* if |x| < 2**-27 * sqrt(2) */ if ix < 0x3e46a09e { /* raise inexact if x!=0 and underflow if subnormal */ let x1p120 = f64::from_bits(0x4770000000000000); // 0x1p120 == 2^120 if ix < 0x00100000 { force_eval!(x / x1p120); } else { force_eval!(x + x1p120); } return (x, 1.0); } return (k_sin(x, 0.0, 0), k_cos(x, 0.0)); } /* sincos(Inf or NaN) is NaN */ if ix >= 0x7ff00000 { let rv = x - x; return (rv, rv); } /* argument reduction needed */ let (n, y0, y1) = rem_pio2(x); s = k_sin(y0, y1, 1); c = k_cos(y0, y1); match n & 3 { 0 => (s, c), 1 => (c, -s), 2 => (-s, -c), 3 => (-c, s), #[cfg(debug_assertions)] _ => unreachable!(), #[cfg(not(debug_assertions))] _ => (0.0, 1.0), } } // These tests are based on those from sincosf.rs #[cfg(test)] mod tests { use super::sincos; const TOLERANCE: f64 = 1e-6; #[test] fn with_pi() { let (s, c) = sincos(core::f64::consts::PI); assert!( (s - 0.0).abs() < TOLERANCE, "|{} - {}| = {} >= {}", s, 0.0, (s - 0.0).abs(), TOLERANCE ); assert!( (c + 1.0).abs() < TOLERANCE, "|{} + {}| = {} >= {}", c, 1.0, (s + 1.0).abs(), TOLERANCE ); } #[test] fn rotational_symmetry() { use core::f64::consts::PI; const N: usize = 24; for n in 0..N { let theta = 2. * PI * (n as f64) / (N as f64); let (s, c) = sincos(theta); let (s_plus, c_plus) = sincos(theta + 2. * PI); let (s_minus, c_minus) = sincos(theta - 2. * PI); assert!( (s - s_plus).abs() < TOLERANCE, "|{} - {}| = {} >= {}", s, s_plus, (s - s_plus).abs(), TOLERANCE ); assert!( (s - s_minus).abs() < TOLERANCE, "|{} - {}| = {} >= {}", s, s_minus, (s - s_minus).abs(), TOLERANCE ); assert!( (c - c_plus).abs() < TOLERANCE, "|{} - {}| = {} >= {}", c, c_plus, (c - c_plus).abs(), TOLERANCE ); assert!( (c - c_minus).abs() < TOLERANCE, "|{} - {}| = {} >= {}", c, c_minus, (c - c_minus).abs(), TOLERANCE ); } } }
use dirs::data_dir; use std::path::PathBuf; pub fn get_assets_path() -> PathBuf { PathBuf::from(std::env::var("ASSET_PATH").unwrap_or("assets/".to_string())) } pub fn get_save_path() -> PathBuf { if let Some(mut save_dir) = data_dir() { save_dir.push("everfight"); if let Err(err) = std::fs::create_dir_all(save_dir.clone()) { error!("Failed to create save directory {}: {}", save_dir.to_string_lossy(), err); } save_dir } else { get_assets_path() } }
use std::error; use std::error::Error; use std::io; use std::fmt; use std::num; #[derive(Debug)] pub enum WalletError { WalletUnknownType(String), WalletTypeAlreadyRegistered(String), WalletNotFound(String), WalletInvalidDataFormat(String), WalletIncorrectPool(String), WalletInvalidConfig(String), WalletIOError(io::Error), } impl fmt::Display for WalletError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { WalletError::WalletUnknownType(ref description) => write!(f, "Unknown wallet type: {}", description), WalletError::WalletTypeAlreadyRegistered(ref description) => write!(f, "Wallet type already registered: {}", description), WalletError::WalletNotFound(ref description) => write!(f, "Wallet not found: {}", description), WalletError::WalletInvalidDataFormat(ref description) => write!(f, "Invalid format of wallet data: {}", description), WalletError::WalletIncorrectPool(ref description) => write!(f, "Wallet used with different pool: {}", description), WalletError::WalletInvalidConfig(ref description) => write!(f, "Invalid wallet config: {}", description), WalletError::WalletIOError(ref err) => err.fmt(f) } } } impl error::Error for WalletError { fn description(&self) -> &str { match *self { WalletError::WalletUnknownType(ref description) => description, WalletError::WalletTypeAlreadyRegistered(ref description) => description, WalletError::WalletNotFound(ref description) => description, WalletError::WalletInvalidDataFormat(ref description) => description, WalletError::WalletIncorrectPool(ref description) => description, WalletError::WalletInvalidConfig(ref description) => description, WalletError::WalletIOError(ref err) => err.description() } } fn cause(&self) -> Option<&error::Error> { match *self { WalletError::WalletUnknownType(ref description) => None, WalletError::WalletTypeAlreadyRegistered(ref description) => None, WalletError::WalletNotFound(ref description) => None, WalletError::WalletInvalidDataFormat(ref description) => None, WalletError::WalletIncorrectPool(ref description) => None, WalletError::WalletInvalidConfig(ref description) => None, WalletError::WalletIOError(ref err) => Some(err) } } }
// Builds prefix-suffix array. // query_vec: a string of query // pfxsfx: the output pub fn build_pfxsfx(query_vec: &Vec<u16>, pfxsfx: &mut Vec<usize>) { // pfxsfx:The length of longest prefix-suffix match assert!( pfxsfx.len() == query_vec.len(), "pfxsfx.len() == query_vec.len()" ); pfxsfx[0] = 0; for idx in 1..(query_vec.len()) { let mut common_prefix_len = pfxsfx[idx - 1]; loop { if query_vec[common_prefix_len] == query_vec[idx] { // found. pfxsfx[idx] = common_prefix_len + 1; break; } else { if common_prefix_len == 0 { pfxsfx[idx] = 0; break; } common_prefix_len = pfxsfx[common_prefix_len - 1]; } } } } pub fn run( text_vec: &Vec<u16>, query_vec: &Vec<u16>, pfxsfx: &Vec<usize>, result: &mut Vec<usize>, ) { // Now, find the match let mut qidx = 0; for idx in 0..(text_vec.len()) { loop { if text_vec[idx] == query_vec[qidx] { qidx = qidx + 1; if qidx == query_vec.len() { result.push(idx + 1 - qidx); qidx = pfxsfx[qidx - 1]; } break; } else { if qidx == 0 { break; }; qidx = pfxsfx[qidx - 1]; } } } }
fn main() { let mut old = 1; let mut curr = 1; let mut sum = 0; while curr < 4000000 { let tmp = old + curr; old = curr; curr = tmp; sum += if curr % 2 == 0 { curr } else { 0 } } print!("{}", sum) }
use errors::crypto::CryptoError; extern crate openssl; use self::openssl::bn::{BigNum, BigNumRef, BigNumContext, MSB_MAYBE_ZERO}; use self::openssl::error::ErrorStack; use self::openssl::hash::{hash, MessageDigest}; use std::error::Error; pub struct BigNumberContext { openssl_bn_context: BigNumContext } #[derive(Debug)] pub struct BigNumber { openssl_bn: BigNum } impl BigNumber { pub fn new_context() -> Result<BigNumberContext, CryptoError> { let ctx = try!(BigNumContext::new()); Ok(BigNumberContext { openssl_bn_context: ctx }) } pub fn new() -> Result<BigNumber, CryptoError> { let bn = try!(BigNum::new()); Ok(BigNumber { openssl_bn: bn }) } pub fn safe_prime(&self, size: usize) -> Result<BigNumber, CryptoError> { let mut bn = try!(BigNumber::new()); try!(BigNumRef::generate_prime(&mut bn.openssl_bn, size as i32, true, None, None)); Ok(bn) } pub fn rand(&self, size: usize) -> Result<BigNumber, CryptoError> { let mut bn = try!(BigNumber::new()); try!(BigNumRef::rand(&mut bn.openssl_bn, size as i32, MSB_MAYBE_ZERO, false)); Ok(bn) } pub fn rand_range(&self) -> Result<BigNumber, CryptoError> { let mut bn = try!(BigNumber::new()); try!(BigNumRef::rand_range(&self.openssl_bn, &mut bn.openssl_bn)); Ok(bn) } pub fn from_u32(n: u32) -> Result<BigNumber, CryptoError> { let bn = try!(BigNum::from_u32(n)); Ok(BigNumber { openssl_bn: bn }) } pub fn from_dec(dec: &str) -> Result<BigNumber, CryptoError> { let bn = try!(BigNum::from_dec_str(dec)); Ok(BigNumber { openssl_bn: bn }) } pub fn from_hex(hex: &str) -> Result<BigNumber, CryptoError> { let bn = try!(BigNum::from_hex_str(hex)); Ok(BigNumber { openssl_bn: bn }) } pub fn from_bytes(bytes: &[u8]) -> Result<BigNumber, CryptoError> { let bn = try!(BigNum::from_slice(bytes)); Ok(BigNumber { openssl_bn: bn }) } pub fn to_dec(&self) -> Result<String, CryptoError> { let result = try!(self.openssl_bn.to_dec_str()); Ok(result.to_string()) } pub fn to_hex(&self) -> Result<String, CryptoError> { let result = try!(self.openssl_bn.to_hex_str()); Ok(result.to_string()) } pub fn to_bytes(&self) -> Result<Vec<u8>, CryptoError> { Ok(self.openssl_bn.to_vec()) } pub fn add(&self, a: &BigNumber) -> Result<BigNumber, CryptoError> { let mut bn = try!(BigNumber::new()); try!(BigNumRef::checked_add(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn)); Ok(bn) } pub fn sub(&self, a: &BigNumber) -> Result<BigNumber, CryptoError> { let mut bn = try!(BigNumber::new()); try!(BigNumRef::checked_sub(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn)); Ok(bn) } pub fn mul(&self, a: &BigNumber, ctx: Option<&mut BigNumberContext>) -> Result<BigNumber, CryptoError> { let mut bn = try!(BigNumber::new()); match ctx { Some(context) => try!(BigNumRef::checked_mul(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn, &mut context.openssl_bn_context)), None => { let mut ctx = try!(BigNumber::new_context()); try!(BigNumRef::checked_mul(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn, &mut ctx.openssl_bn_context)); } } Ok(bn) } pub fn div(&self, a: &BigNumber, ctx: Option<&mut BigNumberContext>) -> Result<BigNumber, CryptoError> { let mut bn = try!(BigNumber::new()); match ctx { Some(context) => try!(BigNumRef::checked_div(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn, &mut context.openssl_bn_context)), None => { let mut ctx = try!(BigNumber::new_context()); try!(BigNumRef::checked_div(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn, &mut ctx.openssl_bn_context)); } } Ok(bn) } pub fn add_word(&mut self, w: u32) -> Result<&mut BigNumber, CryptoError> { try!(BigNumRef::add_word(&mut self.openssl_bn, w)); Ok(self) } pub fn sub_word(&mut self, w: u32) -> Result<&mut BigNumber, CryptoError> { try!(BigNumRef::sub_word(&mut self.openssl_bn, w)); Ok(self) } pub fn mul_word(&mut self, w: u32) -> Result<&mut BigNumber, CryptoError> { try!(BigNumRef::mul_word(&mut self.openssl_bn, w)); Ok(self) } pub fn div_word(&mut self, w: u32) -> Result<&mut BigNumber, CryptoError> { try!(BigNumRef::div_word(&mut self.openssl_bn, w)); Ok(self) } pub fn mod_exp(&self, a: &BigNumber, b: &BigNumber, ctx: Option<&mut BigNumberContext>) -> Result<BigNumber, CryptoError> { let mut bn = try!(BigNumber::new()); match ctx { Some(context) => try!(BigNumRef::mod_exp(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn, &b.openssl_bn, &mut context.openssl_bn_context)), None => { let mut ctx = try!(BigNumber::new_context()); try!(BigNumRef::mod_exp(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn, &b.openssl_bn, &mut ctx.openssl_bn_context)); } } Ok(bn) } pub fn modulus(&self, a: &BigNumber, ctx: Option<&mut BigNumberContext>) -> Result<BigNumber, CryptoError> { let mut bn = try!(BigNumber::new()); match ctx { Some(context) => try!(BigNumRef::nnmod(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn, &mut context.openssl_bn_context)), None => { let mut ctx = try!(BigNumber::new_context()); try!(BigNumRef::nnmod(&mut bn.openssl_bn, &self.openssl_bn, &a.openssl_bn, &mut ctx.openssl_bn_context)); } } Ok(bn) } } impl From<ErrorStack> for CryptoError { fn from(err: ErrorStack) -> CryptoError { CryptoError::CryptoBackendError(err.description().to_string()) } }
use crate::{ activity::events as activity_events, lobby::{events as lobby_events, Lobby, LobbyId}, overlay::events as overlay_events, relations::events as relation_events, types::ErrorPayload, user::events as user_events, }; use serde::{Deserialize, Serialize}; /// Events sent from Discord when some action occurs #[derive(Copy, Clone, Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub(crate) enum EventKind { Ready, Error, CurrentUserUpdate, ActivityJoinRequest, ActivityJoin, ActivitySpectate, ActivityInvite, LobbyUpdate, LobbyDelete, LobbyMemberConnect, LobbyMemberUpdate, LobbyMemberDisconnect, LobbyMessage, SpeakingStart, SpeakingStop, OverlayUpdate, RelationshipUpdate, } /// An event sent from Discord to notify us of some kind of state change or /// completed action. /// /// ```json /// { "evt": "ACTIVITY_JOIN", "data": { "secret": "super_sekret" } } /// ``` #[derive(Deserialize, Debug)] #[serde(tag = "evt", content = "data", rename_all = "SCREAMING_SNAKE_CASE")] pub enum Event { /// Fires when we've done something naughty and Discord is telling us to stop. /// /// [API docs](https://discord.com/developers/docs/game-sdk/discord#error-handling) Error(ErrorPayload), /// Sent by Discord upon receipt of our `Handshake` message, the user is /// the current user logged in to the Discord we connected to. Ready(user_events::ConnectEvent), /// Fired when the connection has been interrupted between us and Discord, /// this is a synthesized event as there are can be numerous reasons on /// the client side for this to happen, in addition to Discord itself being /// closed, etc. #[serde(skip)] Disconnected { reason: crate::Error }, /// Fired when any details on the current logged in user are changed. /// /// [API docs](https://discord.com/developers/docs/game-sdk/users#oncurrentuserupdate) CurrentUserUpdate(user_events::UpdateEvent), /// Event fired when a user starts speaking in a lobby voice channel. /// /// [API docs](https://discord.com/developers/docs/game-sdk/lobbies#onspeaking) SpeakingStart(lobby_events::SpeakingEvent), /// Event fired when a user stops speaking in a lobby voice channel. /// /// [API docs](https://discord.com/developers/docs/game-sdk/lobbies#onspeaking) SpeakingStop(lobby_events::SpeakingEvent), /// Event fired when a user connects to a lobby. /// /// [API docs](https://discord.com/developers/docs/game-sdk/lobbies#onmemberconnect) LobbyMemberConnect(lobby_events::MemberEvent), /// Event fired when a user disconnects from a lobby. /// /// [API docs](https://discord.com/developers/docs/game-sdk/lobbies#onmemberdisconnect) LobbyMemberDisconnect(lobby_events::MemberEvent), /// Event fired when a lobby is deleted, or the user disconnects from the lobby. /// /// [API docs](https://discord.com/developers/docs/game-sdk/lobbies#onlobbydelete) LobbyDelete { id: LobbyId }, /// Event fired when a lobby is updated. Note that this is only the metadata /// on the lobby itself, not the `members`. /// /// [API docs](https://discord.com/developers/docs/game-sdk/lobbies#onlobbyupdate) LobbyUpdate(Lobby), /// Event fired when the metadata for a lobby member is changed. /// /// [API docs](https://discord.com/developers/docs/game-sdk/lobbies#onmemberupdate) LobbyMemberUpdate(lobby_events::MemberEvent), /// Event fired when a message is sent to the lobby. /// /// [API docs](https://discord.com/developers/docs/game-sdk/lobbies#onlobbymessage) LobbyMessage(lobby_events::MessageEvent), #[serde(skip)] LobbyCreate(Lobby), #[serde(skip)] LobbyConnect(Lobby), /// Sent by Discord when the local user has requested to join a game, and /// the remote user has accepted their request. /// /// [API docs](https://discord.com/developers/docs/game-sdk/activities#onactivityjoin) ActivityJoin(activity_events::SecretEvent), /// Sent by Discord when the local user has chosen to spectate another user's /// game session. /// /// [API docs](https://discord.com/developers/docs/game-sdk/activities#onactivityspectate) ActivitySpectate(activity_events::SecretEvent), /// Fires when a user asks to join the current user's game. /// /// [API docs](https://discord.com/developers/docs/game-sdk/activities#onactivityjoinrequest) ActivityJoinRequest(activity_events::JoinRequestEvent), /// Fires when the current user is invited by another user to their game. /// /// [API docs](https://discord.com/developers/docs/game-sdk/activities#onactivityinvite) ActivityInvite(activity_events::InviteEvent), /// Event fired when the overlay state changes. /// /// [API docs](https://discord.com/developers/docs/game-sdk/overlay#ontoggle) OverlayUpdate(overlay_events::UpdateEvent), /// Event fired when a relationship with another user changes. /// /// [API docs](https://discord.com/developers/docs/game-sdk/relationships#onrelationshipupdate) RelationshipUpdate(std::sync::Arc<crate::relations::Relationship>), } /// An event sent from Discord as JSON. /// /// ```json /// { /// "cmd": "DISPATCH", /// "evt": "ACTIVITY_JOIN", /// "data": { "secret": "super_sekret" }, /// "nonce": null, /// } /// ``` #[derive(Deserialize, Debug)] pub(crate) struct EventFrame { /// The actual data payload, we don't care about "cmd" or "nonce" since /// nonce is not set for events and cmd is always `DISPATCH`. #[serde(flatten)] pub(crate) inner: Event, } pub enum ClassifiedEvent { Lobby(lobby_events::LobbyEvent), User(user_events::UserEvent), Activity(activity_events::ActivityEvent), Overlay(overlay_events::OverlayEvent), Relations(relation_events::RelationshipEvent), } impl From<Event> for ClassifiedEvent { fn from(eve: Event) -> Self { use activity_events::ActivityEvent as AE; use lobby_events::LobbyEvent as LE; use user_events::UserEvent as UE; match eve { // User/connection Event::Ready(ce) => Self::User(UE::Connect(ce)), Event::Disconnected { reason } => { Self::User(UE::Disconnect(user_events::DisconnectEvent { reason })) } Event::CurrentUserUpdate(user) => Self::User(UE::Update(user)), // Lobby Event::SpeakingStart(se) => Self::Lobby(LE::SpeakingStart(se)), Event::SpeakingStop(se) => Self::Lobby(LE::SpeakingStop(se)), Event::LobbyDelete { id } => Self::Lobby(LE::Delete { id }), Event::LobbyUpdate(lob) => Self::Lobby(LE::Update(lob)), Event::LobbyMemberConnect(me) => Self::Lobby(LE::MemberConnect(me)), Event::LobbyMemberDisconnect(me) => Self::Lobby(LE::MemberDisconnect(me)), Event::LobbyMemberUpdate(me) => Self::Lobby(LE::MemberUpdate(me)), Event::LobbyMessage(msg) => Self::Lobby(LE::Message(msg)), Event::LobbyCreate(lobby) => Self::Lobby(LE::Create(lobby)), Event::LobbyConnect(lobby) => Self::Lobby(LE::Connect(lobby)), // Activity Event::ActivityJoin(secret) => Self::Activity(AE::Join(secret)), Event::ActivitySpectate(secret) => Self::Activity(AE::Spectate(secret)), Event::ActivityJoinRequest(jr) => Self::Activity(AE::JoinRequest(jr)), Event::ActivityInvite(inv) => Self::Activity(AE::Invite(inv)), // Overlay Event::OverlayUpdate(update) => { Self::Overlay(overlay_events::OverlayEvent::Update(update)) } // Relationships Event::RelationshipUpdate(relationship) => { Self::Relations(relation_events::RelationshipEvent::Update(relationship)) } // Errors get converted before this path Event::Error(_) => unreachable!(), } } }
use crate::{DocBase, VarType}; const DESCRIPTION: &'static str = r#" The sin function returns the trigonometric sine of an angle. "#; pub fn gen_doc() -> Vec<DocBase> { let fn_doc = DocBase { var_type: VarType::Function, name: "sin", signatures: vec![], description: DESCRIPTION, example: "", returns: "The trigonometric sine of an angle.", arguments: "**x** Angle, in radians.", remarks: "", links: "", }; vec![fn_doc] }
use image; use memory; /// Image creation error. #[derive(Clone, Copy, Debug, Fail)] pub enum ImageCreationError { /// An unsupported format was attempted to be used. #[fail(display = "Unsupported format")] UnsupportedFormat(image::Format), /// Multi-sampled array textures or cubes are not supported. #[fail(display = "Unsupported kind")] Kind, /// Invalid samples for the device. #[fail(display = "Unsupported amount of samples")] Samples(image::SampleCountFlags), /// Unsupported size in one of the dimensions. #[fail(display = "Unsupported size")] UnsupportedSize(u32), /// The data size provided doesn't match the destination. #[fail(display = "Data size mismatch")] DataSizeMismatch, /// The usage requested isn't supported. #[fail(display = "Unsupported usage")] UnsupportedUsage(image::UsageFlags), /// The memory of the host or device is used up. #[fail(display = "Out of memory")] OutOfMemoryError(memory::OutOfMemoryError), } /// Resource binding error. #[derive(Clone, Copy, Debug, Fail)] pub enum BindError { /// Requested binding to memory that doesn't support the required operations. #[fail(display = "Binding to wrong memory")] WrongMemory, /// Requested binding to an invalid memory. #[fail(display = "Binding to out of bounds memory")] OutOfBounds, /// The memory of the host or device is used up. #[fail(display = "Out of memory")] OutOfMemoryError(memory::OutOfMemoryError), } /// Generic resource error. #[derive(Clone, Copy, Debug, Fail)] pub enum ResourceError { /// Image creation error. #[fail(display = "Image creation error")] ImageCreationError(ImageCreationError), /// Memory error. #[fail(display = "Memory error")] MemoryError(memory::MemoryError), /// Bind error. #[fail(display = "Bind error")] BindError(BindError), } impl From<ImageCreationError> for ResourceError { fn from(error: ImageCreationError) -> Self { ResourceError::ImageCreationError(error) } } impl From<memory::MemoryError> for ResourceError { fn from(error: memory::MemoryError) -> Self { ResourceError::MemoryError(error) } } impl From<BindError> for ResourceError { fn from(error: BindError) -> Self { ResourceError::BindError(error) } }
#[macro_use] extern crate nickel; extern crate regex; extern crate json; mod api; use nickel::{Nickel, StaticFilesHandler, HttpRouter}; fn main() { let mut server = Nickel::new(); server.get("/get_raw_data", middleware!(api::get_raw_data())); server.utilize(StaticFilesHandler::new("static/")); server.listen("127.0.0.1:3000").unwrap(); }
// Copyright (c) 2021 Quark Container Authors / 2018 The gVisor Authors. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use alloc::sync::Arc; use spin::Mutex; use alloc::vec::Vec; use alloc::string::ToString; use super::super::super::super::qlib::common::*; use super::super::super::super::qlib::linux_def::*; use super::super::super::super::qlib::auth::*; use super::super::super::super::kernel::kernel::*; use super::super::super::fsutil::file::readonly_file::*; use super::super::super::fsutil::inode::simple_file_inode::*; use super::super::super::super::task::*; use super::super::super::attr::*; use super::super::super::file::*; use super::super::super::flags::*; use super::super::super::dirent::*; use super::super::super::mount::*; use super::super::super::inode::*; use super::super::super::super::threadmgr::thread::*; use super::super::super::super::threadmgr::pid_namespace::*; use super::super::inode::*; pub fn NewStatus(task: &Task, thread: &Thread, msrc: &Arc<Mutex<MountSource>>) -> Inode { let v = NewStatusSimpleFileInode(task, thread, &ROOT_OWNER, &FilePermissions::FromMode(FileMode(0o400)), FSMagic::PROC_SUPER_MAGIC); return NewProcInode(&Arc::new(v), msrc, InodeType::SpecialFile, Some(thread.clone())) } pub fn NewStatusSimpleFileInode(task: &Task, thread: &Thread, owner: &FileOwner, perms: &FilePermissions, typ: u64) -> SimpleFileInode<StatusData> { let kernel = GetKernel(); let pidns = kernel.RootPIDNamespace(); let status = StatusData { thread: thread.clone(), pidns: pidns, }; return SimpleFileInode::New(task, owner, perms, typ, false, status) } pub struct StatusData { thread: Thread, pidns: PIDNamespace, } impl StatusData { pub fn GenSnapshot(&self, _task: &Task) -> Vec<u8> { let mut ret = "".to_string(); ret += &format!("Name:\t{}\n", self.thread.Name()); // todo: handle thread state //ret += &format!("State:\t{}\n", self.thread.Name()); let tg = self.thread.ThreadGroup(); ret += &format!("Tgid:\t{}\n", self.pidns.IDOfThreadGroup(&tg)); ret += &format!("Pid:\t{}\n", self.pidns.IDOfTask(&self.thread)); let ppid = match self.thread.Parent() { None => 0, Some(parent) => { let tg = parent.ThreadGroup(); self.pidns.IDOfThreadGroup(&tg) }, }; ret += &format!("PPid:\t{}\n", ppid); ret += &format!("TracerPid:\t{}\n", 0); let fds = self.thread.lock().fdTbl.Count(); ret += &format!("FDSize:\t{}\n", fds); let mm = self.thread.lock().memoryMgr.clone(); let ml = mm.MappingLock(); let _ml = ml.read(); let vss = mm.VirtualMemorySizeLocked(); let rss = mm.ResidentSetSizeLocked(); ret += &format!("VmSize:\t{} kB\n", vss>>10); ret += &format!("VmRSS:\t{} kB\n", rss>>10); ret += &format!("Threads:\t{}\n", tg.Count()); let creds = self.thread.Credentials(); ret += &format!("CapInh:\t{:016x}\n", creds.lock().InheritableCaps.0); ret += &format!("CapPrm:\t{:016x}\n", creds.lock().PermittedCaps.0); ret += &format!("CapEff:\t{:016x}\n", creds.lock().EffectiveCaps.0); ret += &format!("CapBnd:\t{:016x}\n", creds.lock().BoundingCaps.0); ret += &format!("Seccomp:\t{}\n", 0); ret += &format!("Mems_allowed:\t{}\n", "00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000000,00000001"); return ret.as_bytes().to_vec(); } } impl SimpleFileTrait for StatusData { fn GetFile(&self, task: &Task, _dir: &Inode, dirent: &Dirent, flags: FileFlags) -> Result<File> { let fops = NewSnapshotReadonlyFileOperations(self.GenSnapshot(task)); let file = File::New(dirent, &flags, fops); return Ok(file); } }
use crate::cell::Cell; use crate::grid::Grid; use crate::row::Row; use crate::automaton::Automaton; use crate::renderer::Renderer; pub struct Lant { n_cols: usize, n_rows: usize, grid: Grid, current_direction: i32, current_position_x: usize, current_position_y: usize, } impl Lant { pub fn new(n_rows: usize, n_cols: usize) -> Lant { let rows = vec![ Row { cells: vec![Cell { value: 0 }; n_cols] }; n_rows ]; Lant { n_cols: n_cols, n_rows: n_rows, grid: Grid { rows }, current_direction: 0, current_position_x: n_cols / 2, current_position_y: n_rows / 2, } } fn next_iteration(&mut self) { let current_cell_value = &mut self.grid.rows[self.current_position_y].cells[self.current_position_x].value; if *current_cell_value != 0{ self.current_direction += 1; } else { self.current_direction -= 1; } self.current_direction = self.current_direction.rem_euclid(4); *current_cell_value = !(*current_cell_value); let mut new_pos_x = self.current_position_x as i32; let mut new_pos_y = self.current_position_y as i32; match self.current_direction { 0 => { new_pos_x += 1; } 1 => { new_pos_y += 1; } 2 => { new_pos_x -= 1; } 3 => { new_pos_y -= 1; } _ => panic!("Invalid direction"), } new_pos_x = new_pos_x.rem_euclid(self.n_cols as i32); new_pos_y = new_pos_y.rem_euclid(self.n_rows as i32); self.current_position_x = new_pos_x as usize; self.current_position_y = new_pos_y as usize; } } impl Automaton for Lant { fn next(&mut self) { self.next_iteration(); } fn render(&self, renderer: &mut dyn Renderer) { renderer.render_grid(&self.grid); } }
use math::primes; pub fn demo(n: u64) { println!("{:?}", primes::primes(n)); }
use vector::Vector; use std::process::exit; use vector::unit; const GRAV_CONST: f64 = 0.00000000006674; pub struct Point { mass: f64, pub cur_pos: Vector, pub prev_pos: Vector, pub accel: Vector, grav_accel: Vector, } impl Point { pub fn new(mass: f64, cur_pos: Vector, prev_pos: Vector, init_accel: Vector) -> Point { Point{ mass: mass, cur_pos: cur_pos, prev_pos: prev_pos, accel: init_accel, grav_accel: Vector::default(), } } pub fn update_verlet(&mut self, step: f64) { let temp = self.cur_pos; let total_accel = self.accel + self.grav_accel; //println!("diff: {}",(self.cur_pos-self.prev_pos).norm()); self.cur_pos = self.cur_pos + (self.cur_pos - self.prev_pos) + total_accel*(step.powi(2)); self.prev_pos = temp; //println!("prev: {}, cur: {}", temp, self.cur_pos) } pub fn update_gravity(&mut self, point: Point) { let diff = point.cur_pos - self.cur_pos; let dist = diff.norm(); if dist == 0.0 { exit(1); } let u = unit(point.cur_pos, self.cur_pos); //println!("{}", self.grav_accel.mul_scalar(GRAV_CONST * point.mass/(dist*dist))); self.grav_accel = self.grav_accel + u*(GRAV_CONST * (point.mass/dist.powi(2))); //println!("dist: {} grav: {}", dist, self.grav_accel); } pub fn current_position(self) -> Vector { self.cur_pos.clone() } } impl Clone for Point { fn clone(&self) -> Point { Point{mass: self.mass, cur_pos: self.cur_pos.clone(), prev_pos: self.prev_pos.clone(), accel: self.accel.clone(), grav_accel: self.grav_accel.clone()} } } impl Copy for Point {}
use crate::archival::libarchive::bb_archive::archive_handle_t; pub unsafe fn data_skip(mut archive_handle: *mut archive_handle_t) { (*archive_handle).seek.expect("non-null function pointer")( (*archive_handle).src_fd, (*(*archive_handle).file_header).size, ); }
use scheme::LispResult; use scheme::error::LispError::*; use scheme::value::Sexp; use scheme::value::Sexp::*; // 标准中只要求对两个操作数进行比较 // 大写字符是有序的 // 小写字符是有序的 // 数码字符是有序的 // 所有的数码字符大于或小于大写字符 // 所有的数码字符大于或小于小写字符 pub fn compare<F>(name: &str, op: F, args: &[Sexp]) -> LispResult<Sexp> where F: Fn(char, char) -> bool { let mut vals = Vec::with_capacity(args.len()); for arg in args { match arg { Char(n) => vals.push(n.clone()), _ => return Err(TypeMismatch("char".to_owned(), format!("{}", arg))), } } let arity = vals.len(); if arity < 2 { return Err(ArityMismatch(name.to_string(), 2, arity)); } let mut acc = true; for i in 0..vals.len() - 1 { acc = acc && op(vals[i], vals[i + 1]) } if acc { Ok(True) } else { Ok(False) } }
use super::UserInput; use async_trait::async_trait; use std::io::Result; pub struct CLIBackend<'a> { shell_trust: &'a super::ShellTrust, } impl<'a> CLIBackend<'a> { pub fn new(shell_trust: &'a super::ShellTrust) -> Self { Self { shell_trust } } } #[async_trait] impl<'a> UserInput for CLIBackend<'a> { async fn prompt(&self, text: &str) -> Result<String> { dialoguer::Input::new() .allow_empty(true) .with_prompt(text) .interact() } async fn shell(&self, command: &str, shell_trust: &super::ShellTrust) -> Result<String> { super::shell(command, shell_trust, &super::Backend::CLI).await } async fn select( &self, prompt: &str, options: &std::collections::BTreeMap<String, super::Option>, ) -> Result<String> { let keys = options.keys().cloned().collect::<Vec<String>>(); let display_vals = options .values() .map(|x| x.display.to_owned()) .collect::<Vec<String>>(); let result_idx = dialoguer::Select::new() .with_prompt(prompt) .items(&display_vals) .default(0) .paged(false) .interact()?; match &options[&keys[result_idx]].value { super::OptionValue::Static(x) => Ok(x.to_owned()), super::OptionValue::Shell(cmd) => self.shell(cmd, &self.shell_trust).await, } } async fn check( &self, prompt: &str, separator: &str, options: &std::collections::BTreeMap<String, super::Option>, ) -> Result<String> { let keys = options.keys().cloned().collect::<Vec<String>>(); let display_vals = options .values() .map(|x| x.display.to_owned()) .collect::<Vec<String>>(); let indices = dialoguer::MultiSelect::new() .with_prompt(prompt) .items(&display_vals) .interact() .unwrap(); match indices.len() { 0usize => Ok("".to_owned()), _ => { let mut d = String::new(); for i in indices { let v = match &options[&keys[i]].value { super::OptionValue::Static(x) => x.to_owned(), super::OptionValue::Shell(cmd) => { self.shell(&cmd, &self.shell_trust).await? } }; d.push_str(&v); d.push_str(separator); } d.truncate(d.len() - 2); Ok(d) } } } }
/* The following is an in-progress adaptation of the Beginner's Guide to PID Controllers algorithm from Brett Beauregard, in a straight-line conversion to Rust. As of 4-20-19 it is not complete. references: https://github.com/japaric/zen/ -- embedded TWIP with PID on stm32 board https://github.com/johsnick/rust_pid/blob/master/src/lib.rs - example rust PID https://github.com/adeschamps/pid-controller/blob/master/src/lib.rs - example rust PID */ #![no_std] #![no_main] /* crates go here */ // extern crate panic_halt; // extern crate chrono; // for the millisecond function /**/ // use cortex_m::asm; // use cortex_m_rt::entry; /*work_ing variables*/ // NOTE: stm32 and i64 variables? // NOTE: preludes? // NOTE: add getters pub struct PIDController { last_time: u32, // unsigned long input: i64, output: i64, setpoint: i64, // doubles i_term: i64, last_input: i64, // doubles k_p: i64, k_i: i64, k_d : i64, // doubles sample_time: u32, //int, 1 sec out_min: i64, out_max: i64, // doubles forward: bool, reverse: bool, controller_direction: bool, } pub trait Controller { fn Compute(&mut self); fn set_tunings(&mut self, k_p: i64, k_i: i64, k_d: i64); fn set_sample_time(&mut self, new_sample_time: i32); fn set_output_limits(&mut self, min: i64, max: i64); fn set_controller_direction(&mut self, direction: bool); } impl PIDController { /// Creates a new PID Controller. pub fn new(k_p: i64, k_i: i64, k_d: i64) -> PIDController { PIDController{ last_time: 0,// unsigned long input : 0, output: 0, setpoint: 0,// doubles i_term: 0, last_input: 0,// doubles k_p: k_p, k_i: k_i, k_d: k_d, // doubles sample_time: 1000, //int, 1 sec out_min: 0, out_max: 0, // doubles forward : true, reverse : false, controller_direction : true, } } } impl Controller for PIDController{ fn Compute(&mut self) { // let mut now: u32 = millis(); Time is tracked externally let mut now: u32 = 0; // THIS IS A BIG OLD PLACEHOLDER let mut time_change: u32 = now - self.last_time; if time_change >= self.sample_time { /*Compute all the work_ing error variables*/ let mut error: i64 = self.setpoint - self.input; if self.i_term > self.out_max { self.i_term = self.out_max; } else if self.i_term < self.out_min { self.i_term = self.out_min; } let mut dinput: i64 = self.input - self.last_input; /*Compute PID output*/ self.output = self.k_p * error + self.i_term - self.k_d * dinput; if self.output > self.out_max { self.output = self.out_max; } else if self.output < self.out_min { self.output = self.out_min; } /*Remember some variables for next time*/ self.last_input = self.input; self.last_time = now; } } fn set_tunings(&mut self, k_p: i64, k_i: i64, k_d: i64) { let sample_time_in_sec: i64 = (self.sample_time as i64) / 1000; self.k_p = k_p; self.k_i = k_i * sample_time_in_sec; self.k_d = k_d / sample_time_in_sec; //The above code is for going forward, the below is for backward if self.controller_direction == self.reverse { self.k_p = 0 - self.k_p; self.k_i = 0 - self.k_i; self.k_d = 0 - self.k_d; } } fn set_sample_time(&mut self, new_sample_time: i32) // this is called externally, rather than tracking time by itself { if new_sample_time > 0 { let mut ratio: i64 = new_sample_time as i64 / self.sample_time as i64; self.k_i *= ratio; self.k_d /= ratio; self.sample_time = new_sample_time as u32; } } fn set_output_limits(&mut self, min: i64, max: i64) // this way the PID won't try values that are impossible for it to achieve { if min > max { return; } self.out_min = min; self.out_max = max; if self.output > self.out_max { self.output = self.out_max; } else if self.output < self.out_min { self.output = self.out_min; } if self.i_term > self.out_max { self.i_term = self.out_max; } else if self.i_term < self.out_min { self.i_term= self.out_min; } } //Going backwards or forwards fn set_controller_direction(&mut self, direction: bool) { self.controller_direction = direction; } }
#![doc = include_str!("notes/mod.md")] #[doc = include_str!("notes/thrun.md")] pub mod thrun {} #[doc = include_str!("notes/ndtmcl.md")] pub mod ndtmcl {} #[doc = include_str!("notes/kld.md")] pub mod kld {} #[doc = include_str!("notes/cddt.md")] pub mod cddt {} #[doc = include_str!("notes/rao.md")] pub mod rao {}
fn tsub_ok(x: i32, y: i32) -> bool { tadd_ok(x, -y) }
extern crate compt; use compt::*; fn main() { // Example that performs dfs in order traversal on the left side, // and bfs order traversal on the right side of a tree. // This demonstrates the composability of the different visitor functions. // // 0 // 1 2 // 3 4 5 6 let mut k = compt::dfs_order::CompleteTreeContainer::from_inorder(vec![3, 1, 4, 0, 5, 2, 6]).unwrap(); let tree = k.as_tree_mut(); let k = tree.vistr_mut(); let (a, rest) = k.next(); let [left, right] = rest.unwrap(); let mut res: Vec<&mut usize> = Vec::new(); res.push(a); left.dfs_inorder(|a| { res.push(a); }); for a in right.dfs_preorder_iter() { res.push(a); } let res: Vec<usize> = res.drain(..).map(|a| *a).collect(); assert_eq!(&res, &[0, 3, 1, 4, 2, 5, 6]); }
extern crate rand; use std::env; use std::io::{self, Write}; use std::ops::AddAssign; use std::fmt; use rand::Rng; #[derive(Copy, Clone)] struct Score { correct: i32, incorrect: i32, } impl Score { fn new() -> Score { Score { correct: 0, incorrect: 0 } } } impl AddAssign for Score { fn add_assign(&mut self, other: Score) { *self = Score { correct: self.correct + other.correct, incorrect: self.incorrect + other.incorrect } } } impl fmt::Display for Score { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { if self.correct + self.incorrect == 0 { write!(f, "no score yet") } else { let pct = 100 * self.correct / (self.correct + self.incorrect); write!(f, "{}, score {}%", self.correct, pct) } } } fn prompt(message: &str) -> String { io::stdout().write(message.as_bytes()).unwrap(); io::stdout().flush().unwrap(); let mut input = String::new(); io::stdin().read_line(&mut input).unwrap(); String::from(input.trim()) } fn exercise<F, T>(count: u32, score: &mut Score, mut get_problem: F) where F: FnMut() -> (String, T), T: std::cmp::Eq + std::str::FromStr { let mut s = Score::new(); println!(); for _ in 0..count { let (problem, answer) = get_problem(); let response: T; loop { let input = prompt(problem.as_ref()); response = match input.parse::<T>() { Ok(s) => s, Err(_) => { println!("Illegal value: {}", input); continue }, }; break } if response == answer { s.correct += 1 } else { s.incorrect += 1 } } println!(); if s.incorrect == 0 { println!("Great job! No errors."); } else { println!("You had {} correct and {} incorrect answers.", s.correct, s.incorrect); } println!(); let _ = prompt("Press ENTER to continue."); *score += s; } fn main() { let name = match env::var("NAME") { Ok(val) => val, Err(_) => String::from("there"), }; println!("Hello, {}! Which excercise do you want to do?", name); let mut score = [Score::new(); 10]; let mut count = 10u32; loop { println!("Enter a number, or 'q' to quit."); println!(); println!("(0) Set number of problems [current: {}]", count); println!("(1) Ten's partners [{}]", score[0]); println!("(2) Partners between five and ten [{}]", score[1]); println!("(3) Addition, up to ten [{}]", score[2]); println!("(4) Addition, between 10 and 20 [{}]", score[3]); println!("(5) Addition, over 20 [{}]", score[4]); println!("(6) Subtraction, up to ten [{}]", score[5]); println!("(7) Subtraction, between 10 and 20 [{}]", score[6]); println!("(8) Subtraction, over 20 [{}]", score[7]); println!("(9) Addition and subraction, up to 100 [{}]", score[8]); println!(); let choice = prompt("Enter your choice: "); let mut rng = rand::thread_rng(); match choice.as_ref() { // Set count "0" => { loop { let input = prompt("Number of problems per exercise: "); match input.parse::<u32>() { Ok(u) => { count = u; break } Err(_) => { println!("Illegal value: {}", input); } } } } // Tens partners "1" => exercise(count, &mut score[0], || { let a = rng.gen_range(0, 11); (format!("10 = {} + ", a), 10-a) }), // Partners between 5 and ten "2" => exercise(count, &mut score[1], || { let a = rng.gen_range(5, 11); let b = rng.gen_range(0, a+1); (format!("{} = {} + ", a, b), a-b) }), // Sum up to 10 "3" => exercise(count, &mut score[2], || { let a = rng.gen_range(0, 11); let b = rng.gen_range(0, 11-a); (format!("{} + {} = ", a, b), a+b) }), // Sum between 10 and 20 "4" => exercise(count, &mut score[3], || { let a = rng.gen_range(0, 11); let b = rng.gen_range(10-a, 11); (format!("{} + {} = ", a, b), a+b) }), // Sum up to 100 "5" => exercise(count, &mut score[4], || { let a = rng.gen_range(0, 101); let b = rng.gen_range(0, 101-a); (format!("{} + {} = ", a, b), a+b) }), // Subtraction, up to 10 "6" => exercise(count, &mut score[5], || { let a = rng.gen_range(0, 11); let b = rng.gen_range(0, a+1); (format!("{} - {} = ", a, b), a-b) }), // Subtraction, between 10 and 20 "7" => exercise(count, &mut score[6], || { let a = rng.gen_range(10, 21); let b = rng.gen_range(a-10, a+1); (format!("{} - {} = ", a, b), a-b) }), // Subtraction, up to 100 "8" => exercise(count, &mut score[7], || { let a = rng.gen_range(0, 101); let b = rng.gen_range(0, a+1); (format!("{} - {} = ", a, b), a-b) }), "9" => exercise(count, &mut score[8], || { match rng.gen_range(0, 2) { 0 => { let a = rng.gen_range(0, 101); let b = rng.gen_range(0, 101-a); (format!("{} + {} = ", a, b), a+b) } 1 => { let a = rng.gen_range(0, 101); let b = rng.gen_range(0, a+1); (format!("{} - {} = ", a, b), a-b) } _ => panic!("Not reached"), } }), "q" => break, _ => (), } } }
use bindings::{ Windows::Win32::Graphics::Direct3D11::*, Windows::Win32::Graphics::Direct3D12::*, Windows::Win32::Graphics::DirectComposition::*, Windows::Win32::Graphics::Dxgi::*, Windows::Win32::Graphics::Gdi::*, Windows::Win32::Graphics::Hlsl::*, Windows::Win32::System::SystemServices::*, Windows::Win32::System::Threading::*, Windows::Win32::UI::DisplayDevices::*, Windows::Win32::UI::MenusAndResources::*, Windows::Win32::UI::WindowsAndMessaging::*, }; use dx12_common::{ cd3dx12_blend_desc_default, cd3dx12_depth_stencil_desc_default, cd3dx12_heap_properties_with_type, cd3dx12_rasterizer_desc_default, cd3dx12_resource_barrier_transition, create_default_buffer, }; use std::ptr::null_mut; use std::{convert::TryInto, ffi::CString}; use windows::Interface; const NUM_OF_FRAMES: usize = 2; #[derive(Debug, PartialEq)] #[repr(C)] struct Vertex { position: [f32; 3], color: [f32; 4], } impl Vertex { const fn new(position: [f32; 3], color: [f32; 4]) -> Self { Self { position, color } } } const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0]; const GREEN: [f32; 4] = [0.0, 1.0, 0.0, 1.0]; const BLUE_TRANSPARENT: [f32; 4] = [0.0, 0.0, 1.0, 0.5]; const MAGENTA: [f32; 4] = [1.0, 0.0, 1.0, 1.0]; #[allow(dead_code)] struct Window { hwnd: HWND, factory: IDXGIFactory4, adapter: IDXGIAdapter1, device: ID3D12Device, queue: ID3D12CommandQueue, allocators: [ID3D12CommandAllocator; NUM_OF_FRAMES], comp_device: IDCompositionDevice, swap_chain: IDXGISwapChain3, current_frame: usize, comp_target: IDCompositionTarget, comp_visual: IDCompositionVisual, rtv_desc_heap: ID3D12DescriptorHeap, rtv_desc_size: usize, back_buffers: [ID3D12Resource; NUM_OF_FRAMES], depth_stencil_heap: ID3D12DescriptorHeap, depth_stencil_buffer: ID3D12Resource, root_signature: ID3D12RootSignature, list: ID3D12GraphicsCommandList, vertex_shader: ID3DBlob, pixel_shader: ID3DBlob, pipeline_state: ID3D12PipelineState, viewport: D3D12_VIEWPORT, scissor: RECT, // Synchronization fence: ID3D12Fence, fence_event: HANDLE, fence_values: [u64; NUM_OF_FRAMES], // Resources vertex_buffer: ID3D12Resource, vertex_buffer_view: D3D12_VERTEX_BUFFER_VIEW, indices_buffer: ID3D12Resource, indices_buffer_view: D3D12_INDEX_BUFFER_VIEW, } impl Window { pub fn new(hwnd: HWND) -> windows::Result<Self> { // Start "DebugView" to listen errors // https://docs.microsoft.com/en-us/sysinternals/downloads/debugview let debug = unsafe { D3D12GetDebugInterface::<ID3D12Debug1>() } .expect("Unable to create debug layer"); unsafe { debug.EnableDebugLayer(); debug.SetEnableGPUBasedValidation(true); debug.SetEnableSynchronizedCommandQueueValidation(true); } let factory = unsafe { CreateDXGIFactory2::<IDXGIFactory4>(0) }?; let adapter = (0..99) .into_iter() .find_map(|i| unsafe { let mut ptr: Option<IDXGIAdapter1> = None; factory.EnumAdapters1(i, &mut ptr).and_some(ptr).ok() }) .expect("Could not find d3d adapter"); let device: ID3D12Device = unsafe { D3D12CreateDevice( &adapter, // None for default adapter D3D_FEATURE_LEVEL::D3D_FEATURE_LEVEL_11_0, ) }?; let queue = unsafe { let desc = D3D12_COMMAND_QUEUE_DESC { Type: D3D12_COMMAND_LIST_TYPE::D3D12_COMMAND_LIST_TYPE_DIRECT, Priority: D3D12_COMMAND_QUEUE_PRIORITY::D3D12_COMMAND_QUEUE_PRIORITY_HIGH.0, Flags: D3D12_COMMAND_QUEUE_FLAGS::D3D12_COMMAND_QUEUE_FLAG_NONE, NodeMask: 0, }; device.CreateCommandQueue::<ID3D12CommandQueue>(&desc) }?; let allocators: [ID3D12CommandAllocator; NUM_OF_FRAMES] = (0..NUM_OF_FRAMES) .map(|_| unsafe { device .CreateCommandAllocator::<ID3D12CommandAllocator>( D3D12_COMMAND_LIST_TYPE::D3D12_COMMAND_LIST_TYPE_DIRECT, ) .expect("Unable to create allocator") }) .collect::<Vec<_>>() .try_into() .expect("Unable to create allocators"); // Composition device let comp_device: IDCompositionDevice = unsafe { DCompositionCreateDevice(None) }?; // Create swap chain for composition let swap_chain = unsafe { let desc = DXGI_SWAP_CHAIN_DESC1 { AlphaMode: DXGI_ALPHA_MODE::DXGI_ALPHA_MODE_PREMULTIPLIED, BufferCount: NUM_OF_FRAMES as _, Width: 1024, Height: 1024, Format: DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM, Flags: 0, BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Scaling: DXGI_SCALING::DXGI_SCALING_STRETCH, Stereo: BOOL(0), SwapEffect: DXGI_SWAP_EFFECT::DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL, }; let mut ptr: Option<IDXGISwapChain1> = None; factory .CreateSwapChainForComposition(&queue, &desc, None, &mut ptr) .and_some(ptr) }? .cast::<IDXGISwapChain3>()?; // Current frame index let current_frame = unsafe { swap_chain.GetCurrentBackBufferIndex() as usize }; // Create IDCompositionTarget for the window let comp_target = unsafe { let mut ptr = None; comp_device .CreateTargetForHwnd(hwnd, BOOL(1), &mut ptr) .and_some(ptr) }?; // Create IDCompositionVisual for the window let comp_visual = unsafe { let mut ptr = None; comp_device.CreateVisual(&mut ptr).and_some(ptr) }?; // Set swap_chain and the root visual and commit unsafe { comp_visual.SetContent(&swap_chain).ok()?; comp_target.SetRoot(&comp_visual).ok()?; comp_device.Commit().ok()?; } // Create descriptor heap for render target views let rtv_desc_heap = unsafe { let desc = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_RTV, NumDescriptors: NUM_OF_FRAMES as _, Flags: D3D12_DESCRIPTOR_HEAP_FLAGS::D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0, }; device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&desc) }?; // Create resource per frame let mut descriptor = unsafe { rtv_desc_heap.GetCPUDescriptorHandleForHeapStart() }; let rtv_desc_size = unsafe { device.GetDescriptorHandleIncrementSize( D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_RTV, ) as usize }; let back_buffers = (0..NUM_OF_FRAMES) .map(|i| { let resource = unsafe { swap_chain.GetBuffer::<ID3D12Resource>(i as _) }?; unsafe { // let desc = D3D12_TEX2D_RTV { // Format: DXGI_FORMAT_R8G8B8A8_UNORM, // u: D3D12_RTV_DIMENSION_UNKNOWN as _, // ViewDimension: 0, // }; device.CreateRenderTargetView(&resource, 0 as _, &descriptor); descriptor.ptr += rtv_desc_size; } Ok(resource) }) .collect::<Result<Vec<_>, windows::Error>>()? .try_into() .expect("Unable to create resources"); // Create depth/stencil heap let depth_stencil_heap = unsafe { let desc = D3D12_DESCRIPTOR_HEAP_DESC { Type: D3D12_DESCRIPTOR_HEAP_TYPE::D3D12_DESCRIPTOR_HEAP_TYPE_DSV, NumDescriptors: 1, Flags: D3D12_DESCRIPTOR_HEAP_FLAGS::D3D12_DESCRIPTOR_HEAP_FLAG_NONE, NodeMask: 0, }; device.CreateDescriptorHeap::<ID3D12DescriptorHeap>(&desc) }?; // Create depth/stencil buffer let depth_stencil_buffer = unsafe { device.CreateCommittedResource::<ID3D12Resource>( &cd3dx12_heap_properties_with_type(D3D12_HEAP_TYPE::D3D12_HEAP_TYPE_DEFAULT), D3D12_HEAP_FLAGS::D3D12_HEAP_FLAG_NONE, &D3D12_RESOURCE_DESC { Alignment: 0, Width: 1024, Height: 1024, // If DXGI_SWAP_CHAIN_DESC1::Stereo is TRUE (3d glasses // support) following array size needs to be 2: DepthOrArraySize: 1, MipLevels: 1, Dimension: D3D12_RESOURCE_DIMENSION::D3D12_RESOURCE_DIMENSION_TEXTURE2D, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Format: DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT, Flags: D3D12_RESOURCE_FLAGS::D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, ..std::mem::zeroed() }, // D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_DEPTH_WRITE, &D3D12_CLEAR_VALUE { Format: DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT, Anonymous: D3D12_CLEAR_VALUE_0 { DepthStencil: D3D12_DEPTH_STENCIL_VALUE { Depth: 1.0, Stencil: 0, }, }, }, ) }?; unsafe { device.CreateDepthStencilView( &depth_stencil_buffer, null_mut(), // &D3D12_DEPTH_STENCIL_VIEW_DESC { // format: DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT, // view_dimension: D3D12_DSV_DIMENSION::D3D12_DSV_DIMENSION_TEXTURE2D, // flags: D3D12_DSV_FLAGS::D3D12_DSV_FLAG_NONE, // ..std::mem::zeroed() // }, depth_stencil_heap.GetCPUDescriptorHandleForHeapStart(), ) } // Create root signature let root_signature = unsafe { let root = { let mut blob: Option<ID3DBlob> = None; let mut error: Option<ID3DBlob> = None; let desc = D3D12_ROOT_SIGNATURE_DESC { NumParameters: 0, pParameters: null_mut() as _, NumStaticSamplers: 0, pStaticSamplers: null_mut() as _, Flags: D3D12_ROOT_SIGNATURE_FLAGS::D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT, }; D3D12SerializeRootSignature( &desc, D3D_ROOT_SIGNATURE_VERSION::D3D_ROOT_SIGNATURE_VERSION_1_0, &mut blob as _, &mut error as _, ) .and_then(|| { if error.is_none() { blob.unwrap() } else { panic!("Root signature failed, error blob contains the error") } }) }?; device.CreateRootSignature::<ID3D12RootSignature>( 0, root.GetBufferPointer(), root.GetBufferSize(), ) }?; let vertex_shader = unsafe { let data = include_bytes!("./01-triangle.hlsl"); let mut err: Option<ID3DBlob> = None; let mut ptr: Option<ID3DBlob> = None; D3DCompile( data.as_ptr() as *mut _, data.len(), PSTR("01-triangle.hlsl\0".as_ptr() as _), null_mut(), None, PSTR("VSMain\0".as_ptr() as _), PSTR("vs_5_0\0".as_ptr() as _), 0, 0, &mut ptr, &mut err, ) .ok()?; match ptr { Some(v) => v, None => { panic!( "Shader creation failed with error {}", CString::from_raw(err.unwrap().GetBufferPointer() as _).to_string_lossy() ) } } }; let pixel_shader = unsafe { let data = include_bytes!("./01-triangle.hlsl"); let mut err: Option<ID3DBlob> = None; let mut ptr: Option<ID3DBlob> = None; D3DCompile( data.as_ptr() as *mut _, data.len(), PSTR("01-triangle.hlsl\0".as_ptr() as _), null_mut(), None, PSTR("PSMain\0".as_ptr() as _), PSTR("ps_5_0\0".as_ptr() as _), 0, 0, &mut ptr, &mut err, ) .ok()?; match ptr { Some(v) => v, None => { panic!( "Shader creation failed with error {}", CString::from_raw(err.unwrap().GetBufferPointer() as _).to_string_lossy() ) } } }; let mut els = [ D3D12_INPUT_ELEMENT_DESC { SemanticName: PSTR("POSITION\0".as_ptr() as _), SemanticIndex: 0, Format: DXGI_FORMAT::DXGI_FORMAT_R32G32B32_FLOAT, InputSlot: 0, InstanceDataStepRate: 0, InputSlotClass: D3D12_INPUT_CLASSIFICATION::D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, AlignedByteOffset: 0, }, D3D12_INPUT_ELEMENT_DESC { SemanticName: PSTR("COLOR\0".as_ptr() as _), SemanticIndex: 0, Format: DXGI_FORMAT::DXGI_FORMAT_R32G32B32A32_FLOAT, InputSlot: 0, InstanceDataStepRate: 0, InputSlotClass: D3D12_INPUT_CLASSIFICATION::D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, AlignedByteOffset: 12, }, ]; let pso_desc = D3D12_GRAPHICS_PIPELINE_STATE_DESC { // TODO: Can I get rid of this clone? Or do I even have to? pRootSignature: Some(root_signature.clone()), // unsafe { std::mem::transmute(root_signature.abi()) }, InputLayout: D3D12_INPUT_LAYOUT_DESC { NumElements: els.len() as u32, pInputElementDescs: els.as_mut_ptr(), }, VS: D3D12_SHADER_BYTECODE { BytecodeLength: unsafe { vertex_shader.GetBufferSize() }, pShaderBytecode: unsafe { vertex_shader.GetBufferPointer() }, }, PS: D3D12_SHADER_BYTECODE { BytecodeLength: unsafe { pixel_shader.GetBufferSize() }, pShaderBytecode: unsafe { pixel_shader.GetBufferPointer() }, }, RasterizerState: cd3dx12_rasterizer_desc_default(), BlendState: cd3dx12_blend_desc_default(), SampleMask: 0xffffffff, PrimitiveTopologyType: D3D12_PRIMITIVE_TOPOLOGY_TYPE::D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE, NumRenderTargets: 1, RTVFormats: (0..D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) .map(|i| { if i == 0 { DXGI_FORMAT::DXGI_FORMAT_B8G8R8A8_UNORM } else { DXGI_FORMAT::DXGI_FORMAT_UNKNOWN } }) .collect::<Vec<_>>() .try_into() .unwrap(), SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, DSVFormat: DXGI_FORMAT::DXGI_FORMAT_D32_FLOAT, DepthStencilState: cd3dx12_depth_stencil_desc_default(), ..D3D12_GRAPHICS_PIPELINE_STATE_DESC::default() }; let pipeline_state = unsafe { device.CreateGraphicsPipelineState::<ID3D12PipelineState>(&pso_desc) } .expect("Unable to create pipeline state"); // Create direct command list let list: ID3D12GraphicsCommandList = unsafe { device.CreateCommandList( 0, D3D12_COMMAND_LIST_TYPE::D3D12_COMMAND_LIST_TYPE_DIRECT, &allocators[current_frame], &pipeline_state, ) }?; unsafe { list.Close().ok()?; } // Create fence let (fence, fence_values, fence_event) = unsafe { let fence = device.CreateFence::<ID3D12Fence>(0, D3D12_FENCE_FLAGS::D3D12_FENCE_FLAG_NONE)?; let fence_event = CreateEventA(null_mut(), false, false, PSTR(null_mut())); if fence_event.0 == 0 { panic!("Unable to create fence event"); } (fence, [1; NUM_OF_FRAMES], fence_event) }; let viewport = D3D12_VIEWPORT { Width: 1024.0, Height: 1024.0, MaxDepth: D3D12_MAX_DEPTH, MinDepth: D3D12_MIN_DEPTH, TopLeftX: 0.0, TopLeftY: 0.0, }; let scissor = RECT { top: 0, left: 0, bottom: 1024, right: 1024, }; // Resource initialization ------------------------------------------ unsafe { // allocators[current_frame].Reset().ok()?; list.Reset(&allocators[current_frame], &pipeline_state) .ok()?; } let (vertex_buffer, vertex_buffer_view, _vertex_buffer_upload) = unsafe { // Coordinate space again as refresher: // // x, y // -1.0, +1.0 +1.0, +1.0 // 0──────────┬──────────1 ◄─── vertex index // │ │ │ // │ │ │ // │ │ │ // │ │ │ // │ 0,│0 │ // ├──────────┼──────────┤ // │ │ │ // │ │ │ // │ │ │ // │ │ │ // │ │ │ // 3──────────┴──────────2 // -1.0, -1.0 +1.0, -1.0 // In order to create quad (that is square), we form two triangles // from the vertices: // // Indices 0, 1, 2 form a first triangle, and // indices 0, 2, 3 form a second triangle. // Vertexes (these don't form the triangle, but the indicies do) let vertices: [Vertex; 8] = [ // First Vertex::new([-0.5, 0.5, 0.8], RED), Vertex::new([0.5, 0.5, 0.8], GREEN), Vertex::new([0.5, -0.5, 0.8], BLUE_TRANSPARENT), Vertex::new([-0.5, -0.5, 0.8], MAGENTA), // Second Vertex::new([-0.5 - 0.2, 0.5 - 0.2, 0.7], RED), Vertex::new([0.5 - 0.2, 0.5 - 0.2, 0.7], GREEN), Vertex::new([0.5 - 0.2, -0.5 - 0.2, 0.7], BLUE_TRANSPARENT), Vertex::new([-0.5 - 0.2, -0.5 - 0.2, 0.7], MAGENTA), ]; let vertices_as_bytes = std::slice::from_raw_parts( (&vertices as *const _) as *const u8, std::mem::size_of_val(&vertices), ); let vertex_buffers = create_default_buffer(&device, &list, vertices_as_bytes)?; let vertex_buffer_view = D3D12_VERTEX_BUFFER_VIEW { BufferLocation: vertex_buffers.gpu_buffer.GetGPUVirtualAddress(), StrideInBytes: std::mem::size_of::<Vertex>() as _, SizeInBytes: vertices_as_bytes.len() as _, }; ( vertex_buffers.gpu_buffer, vertex_buffer_view, vertex_buffers.upload_buffer, ) }; let (indices_buffer, indices_buffer_view, _indicies_upload_buffer) = unsafe { // Vertex indicies which form the two triangles: let indices: [u32; 12] = [ 0, 1, 2, // Upper right triangle 0, 2, 3, // Bottom left triangle 4, 5, 6, // Upper right triangle 4, 6, 7, // Bottom left triangle ]; let indicies_as_bytes = std::slice::from_raw_parts( (&indices as *const _) as *const u8, std::mem::size_of_val(&indices), ); let buffers = create_default_buffer(&device, &list, indicies_as_bytes)?; let view = D3D12_INDEX_BUFFER_VIEW { BufferLocation: buffers.gpu_buffer.GetGPUVirtualAddress(), SizeInBytes: indicies_as_bytes.len() as _, Format: DXGI_FORMAT::DXGI_FORMAT_R32_UINT, }; (buffers.gpu_buffer, view, buffers.upload_buffer) }; unsafe { list.Close().ok()?; let mut lists = [Some(list.cast::<ID3D12CommandList>()?)]; queue.ExecuteCommandLists(lists.len() as _, lists.as_mut_ptr()); } let mut win = Window { hwnd, factory, adapter, device, queue, allocators, comp_device, swap_chain, current_frame, comp_target, comp_visual, rtv_desc_heap, rtv_desc_size, back_buffers, depth_stencil_heap, depth_stencil_buffer, root_signature, list, pipeline_state, vertex_shader, pixel_shader, viewport, scissor, fence, fence_event, fence_values, vertex_buffer, vertex_buffer_view, indices_buffer, indices_buffer_view, }; win.wait_for_gpu()?; // Temporary upload buffers _indicies_upload_buffer, and // _vertex_buffer_upload can now be destroyed. // End of resource initialization ------------------------------- Ok(win) } fn populate_command_list(&mut self) -> ::windows::Result<()> { unsafe { // Get the current backbuffer on which to draw let current_frame = self.swap_chain.GetCurrentBackBufferIndex() as usize; let current_back_buffer = &self.back_buffers[current_frame]; let rtv = { let mut ptr = self.rtv_desc_heap.GetCPUDescriptorHandleForHeapStart(); ptr.ptr += self.rtv_desc_size * current_frame; ptr }; let dsv = self.depth_stencil_heap.GetCPUDescriptorHandleForHeapStart(); // Reset allocator self.allocators[current_frame].Reset().ok()?; // Reset list self.list .Reset(&self.allocators[current_frame], &self.pipeline_state) .ok()?; // Set root signature, viewport and scissor rect self.list.SetGraphicsRootSignature(&self.root_signature); self.list.RSSetViewports(1, &self.viewport); self.list.RSSetScissorRects(1, &self.scissor); // Direct the draw commands to the render target resource self.list.ResourceBarrier( 1, &cd3dx12_resource_barrier_transition( current_back_buffer, D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RENDER_TARGET, None, None, ), ); self.list.ClearDepthStencilView( &dsv, D3D12_CLEAR_FLAGS::from( D3D12_CLEAR_FLAGS::D3D12_CLEAR_FLAG_DEPTH.0 | D3D12_CLEAR_FLAGS::D3D12_CLEAR_FLAG_STENCIL.0, ), 1.0, 0, 0, null_mut(), ); self.list.OMSetRenderTargets(1, &rtv, false, &dsv); self.list .ClearRenderTargetView(rtv, [1.0f32, 0.2, 0.4, 0.5].as_ptr(), 0, null_mut()); self.list.IASetPrimitiveTopology( D3D_PRIMITIVE_TOPOLOGY::D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, ); self.list.IASetIndexBuffer(&self.indices_buffer_view); self.list.IASetVertexBuffers(0, 1, &self.vertex_buffer_view); self.list.DrawIndexedInstanced(12, 1, 0, 0, 0); // Set render target to be presentable self.list.ResourceBarrier( 1, &cd3dx12_resource_barrier_transition( current_back_buffer, D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATES::D3D12_RESOURCE_STATE_PRESENT, None, None, ), ); // Close list self.list.Close().ok()?; Ok(()) } } pub fn wait_for_gpu(&mut self) -> windows::Result<()> { unsafe { let fence_value = self.fence_values[self.current_frame]; self.queue.Signal(&self.fence, fence_value).ok()?; self.fence .SetEventOnCompletion(fence_value, self.fence_event) .ok()?; WaitForSingleObjectEx(self.fence_event, 0xFFFFFFFF, false); self.fence_values[self.current_frame] += 1; Ok(()) } } pub fn move_to_next_frame(&mut self) -> windows::Result<()> { unsafe { let current_fence_value = self.fence_values[self.current_frame]; self.queue.Signal(&self.fence, current_fence_value).ok()?; // Update current frame self.current_frame = self.swap_chain.GetCurrentBackBufferIndex() as usize; let wait_fence_value = self.fence_values[self.current_frame]; // If the next frame is not ready to be rendered yet, wait until it is ready. if self.fence.GetCompletedValue() < wait_fence_value { self.fence .SetEventOnCompletion(wait_fence_value, self.fence_event) .ok()?; WaitForSingleObjectEx(self.fence_event, 0xFFFFFFFF, false); } // Update the fence value self.fence_values[self.current_frame] = current_fence_value + 1; Ok(()) } } pub fn render(&mut self) -> windows::Result<()> { self.populate_command_list()?; unsafe { let mut lists = [Some(self.list.cast::<ID3D12CommandList>()?)]; self.queue .ExecuteCommandLists(lists.len() as _, lists.as_mut_ptr()); self.swap_chain.Present(1, 0).ok()?; } self.move_to_next_frame()?; Ok(()) } } /// Main message loop for the window extern "system" fn wndproc(hwnd: HWND, msg: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT { unsafe { static mut WINDOW: Option<Window> = None; match msg { WM_CREATE => { let win = Window::new(hwnd).unwrap(); WINDOW = Some(win); DefWindowProcA(hwnd, msg, wparam, lparam) } WM_PAINT => { if let Some(window) = WINDOW.as_mut() { window.render().unwrap(); } ValidateRect(hwnd, std::ptr::null()); LRESULT(0) } WM_DESTROY => { WINDOW = None; PostQuitMessage(0); LRESULT(0) } _ => DefWindowProcA(hwnd, msg, wparam, lparam), } } } fn main() { unsafe { let instance = GetModuleHandleA(None); let cursor = LoadCursorW(HINSTANCE(0), IDC_ARROW); let cls = WNDCLASSA { style: WNDCLASS_STYLES::CS_HREDRAW | WNDCLASS_STYLES::CS_VREDRAW, lpfnWndProc: Some(wndproc), hInstance: instance, lpszClassName: PSTR(b"Dx12LearningCls\0".as_ptr() as _), cbClsExtra: 0, cbWndExtra: 0, hIcon: HICON(0), hCursor: cursor, hbrBackground: HBRUSH(0), lpszMenuName: PSTR(null_mut()), }; RegisterClassA(&cls); let hwnd = CreateWindowExA( WINDOW_EX_STYLE::WS_EX_NOREDIRECTIONBITMAP as _, PSTR(b"Dx12LearningCls\0".as_ptr() as _), PSTR(b"Depth testing example\0".as_ptr() as _), WINDOW_STYLE::WS_OVERLAPPEDWINDOW | WINDOW_STYLE::WS_VISIBLE, -2147483648 as _, // Where is CW_USEDEFAULT? I just hardcoded the value -2147483648 as _, -2147483648 as _, -2147483648 as _, HWND(0), HMENU(0), instance, 0 as _, ); if hwnd == HWND(0) { panic!("Failed to create window"); } let mut message = MSG::default(); while GetMessageA(&mut message, HWND(0), 0, 0).into() { TranslateMessage(&mut message); DispatchMessageA(&mut message); } } }
use crate::{ math::{Size, Vector2}, widgets::TypedWidget, Backend, }; pub struct EventStep<E, R> { pub size: Size, event_queue: Vec<E>, reaction_queue: Vec<R>, } impl<E, R> Default for EventStep<E, R> { fn default() -> Self { EventStep { size: Size::default(), event_queue: Vec::default(), reaction_queue: Vec::default(), } } } impl<E, R> EventStep<E, R> { pub fn queue_event(&mut self, event: E) { self.event_queue.push(event) } } impl<E, R> EventStep<E, R> { pub fn apply<T, B, TW: TypedWidget<T, B>>(&mut self, visitable: &mut TW, data: &mut T) where B: Backend<Event = E, EventReaction = R>, { let size = self.size; let mut reactions: Vec<B::EventReaction> = self .event_queue .drain(0..) .filter_map(|event| { <TW as TypedWidget<T, B>>::event(visitable, Vector2::ZERO, size, data, event) }) .collect(); self.reaction_queue.append(&mut reactions); } }
//! A nul-terminated string,which is just a pointer to the string data, //! it doesn't know the length of the string. #[cfg(test)] mod tests; use crate::std_types::RStr; use const_panic::{concat_assert, concat_panic}; use std::{ cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}, fmt::{self, Debug, Display}, marker::PhantomData, ptr::NonNull, }; /// A utf8 nul-terminated immutable borrowed string. /// /// For the purpose of passing `NulStr`s to C, /// this has the same ABI as a `std::ptr::NonNull<u8>`, /// and an `Option<NulStr<'_>>` has the same ABI as `*const u8`. /// /// # Safety /// /// `NulStr` has these safety requirement: /// - the string must be valid to read for the `'a` lifetime /// - the string must be utf8 encoded /// - the string must be nul terminated /// - the string must not be mutated while this is alive /// (the same semantics as `&` references) /// /// # Example /// /// ### Passing to extern function /// /// You can pass `NulStr` to C functions expecting a nul-terminated string. /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// /// extern "C" { /// // the signature in the C side is `uint64_t add_digits(const char*)` /// fn add_digits(_: NulStr<'_>) -> u64; /// } /// # #[export_name = "add_digits"] /// # pub extern "C" fn add_digits___(str: NulStr<'_>) -> u64 { /// # str.to_str().bytes() /// # .filter_map(|x|{ /// # match x { /// # b'0'..=b'9' => Some(u64::from(x - b'0')), /// # _ => None, /// # } /// # }) /// # .sum() /// # } /// /// # fn main() { /// const FOO: NulStr<'_> = NulStr::from_str("1.2.3\0"); /// const BAR: NulStr<'_> = NulStr::from_str("12|34\0"); /// const QUX: NulStr<'_> = NulStr::from_str("123_abcd_45\0"); /// /// assert_eq!(unsafe { add_digits(FOO) }, 6); /// assert_eq!(unsafe { add_digits(BAR) }, 10); /// assert_eq!(unsafe { add_digits(QUX) }, 15); /// # } /// ``` #[repr(transparent)] #[derive(Copy, Clone, StableAbi)] pub struct NulStr<'a> { ptr: NonNull<u8>, _marker: PhantomData<&'a u8>, } unsafe impl Sync for NulStr<'_> {} unsafe impl Send for NulStr<'_> {} impl NulStr<'static> { /// An empty string. pub const EMPTY: Self = NulStr::from_str("\0"); } impl<'a> NulStr<'a> { /// Constructs an `NulStr` from a string slice. /// /// # Correctness /// /// If the string contains interior nuls, /// the first nul will be considered the string terminator. /// /// # Panics /// /// This panics when the string does not end with `'\0'`. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// /// const FOO: NulStr<'_> = NulStr::from_str("foo\0"); /// // `NulStr`s can be compared with `str`s /// assert_eq!(FOO, "foo"); /// /// const BAR: NulStr<'_> = NulStr::from_str("bar\0"); /// assert_eq!(BAR, "bar"); /// /// const HEWWO: NulStr<'_> = NulStr::from_str("Hello, world!\0"); /// assert_eq!(HEWWO, "Hello, world!"); /// /// const TRUNCATED: NulStr<'_> = NulStr::from_str("baz\0world!\0"); /// assert_eq!(TRUNCATED, "baz"); /// /// ``` pub const fn from_str(str: &'a str) -> Self { let this = Self { ptr: crate::utils::ref_as_nonnull(str).cast::<u8>(), _marker: PhantomData, }; let last_byte = str.as_bytes()[str.len() - 1] as usize; concat_assert! { last_byte == 0, "expected a nul terminator, found:", last_byte, }; this } /// Constructs an NulStr from a string slice. /// /// # Errors /// /// This returns a [`NulStrError::NoNulTerminator`] when the string does not end /// with `'\0'`. /// /// This returns a [`NulStrError::InnerNul`] when the string contains a /// `'\0'` before the `'\0'` terminator. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::{NulStr, NulStrError}; /// /// // `NulStr`s can be compared with `str`s /// assert_eq!(NulStr::try_from_str("hello\0").unwrap(), "hello"); /// /// assert_eq!( /// NulStr::try_from_str("hello\0world\0"), /// Err(NulStrError::InnerNul { pos: 5 }), /// ); /// /// ``` /// /// [`NulStrError::InnerNul`]: enum.NulStrError.html#variant.InnerNul /// [`NulStrError::NoNulTerminator`]: enum.NulStrError.html#variant.NoNulTerminator pub const fn try_from_str(string: &'a str) -> Result<Self, NulStrError> { let mut i = 0; let mut bytes = string.as_bytes(); bytes = match bytes { [rem @ .., 0] => rem, _ => return Err(NulStrError::NoNulTerminator), }; while let [b, ref rem @ ..] = *bytes { if b == 0 { return Err(NulStrError::InnerNul { pos: i }); } i += 1; bytes = rem; } unsafe { Ok(NulStr::from_ptr(string.as_ptr())) } } #[doc(hidden)] #[track_caller] pub const fn __try_from_str_unwrapping(s: &'a str) -> Self { match Self::try_from_str(s) { Ok(x) => x, Err(NulStrError::InnerNul { pos }) => { concat_panic!("encountered inner nul byte at position: ", pos) } Err(NulStrError::NoNulTerminator) => concat_panic!("found no nul-terminator"), } } /// Constructs an NulStr from a pointer. /// /// # Safety /// /// [The same as the type-level safety docs](#safety) /// /// # Correctness /// /// If the string contains interior nuls, /// the first nul will be considered the string terminator. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// /// const FOO: NulStr<'_> = unsafe { NulStr::from_ptr("foo\0".as_ptr()) }; /// assert_eq!(FOO, "foo"); /// /// const BAR: NulStr<'_> = unsafe { NulStr::from_ptr("bar\0".as_ptr()) }; /// assert_eq!(BAR, "bar"); /// /// const HEWWO: NulStr<'_> = unsafe { NulStr::from_ptr("Hello, world!\0".as_ptr()) }; /// assert_eq!(HEWWO, "Hello, world!"); /// /// const TRUNCATED: NulStr<'_> = unsafe { NulStr::from_ptr("baz\0world!\0".as_ptr()) }; /// assert_eq!(TRUNCATED, "baz"); /// /// ``` pub const unsafe fn from_ptr(ptr: *const u8) -> Self { Self { ptr: unsafe { NonNull::new_unchecked(ptr as *mut u8) }, _marker: PhantomData, } } /// Gets a pointer to the start of this nul-terminated string. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// /// let foo_str = "foo\0"; /// let foo = NulStr::from_str(foo_str); /// assert_eq!(foo.as_ptr(), foo_str.as_ptr()); /// /// ``` pub const fn as_ptr(self) -> *const u8 { self.ptr.as_ptr() } /// Converts this `NulStr<'a>` to a `&'a str`,including the nul byte. /// /// # Performance /// /// This conversion requires traversing through the entire string to /// find the nul byte. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// /// const FOO: NulStr<'_> = NulStr::from_str("foo bar\0"); /// let foo: &str = FOO.to_str_with_nul(); /// assert_eq!(&foo[..3], "foo"); /// assert_eq!(&foo[4..], "bar\0"); /// /// ``` pub fn to_str_with_nul(&self) -> &'a str { unsafe { let bytes = std::ffi::CStr::from_ptr(self.ptr.as_ptr() as *const _).to_bytes_with_nul(); std::str::from_utf8_unchecked(bytes) } } /// Computes the length of the string, NOT including the nul terminator. #[cfg(feature = "rust_1_64")] const fn compute_length(self) -> usize { let start: *const u8 = self.ptr.as_ptr(); let mut ptr = start; let mut len = 0; unsafe { while *ptr != 0 { ptr = ptr.offset(1); len += 1; } len } } /// Converts this `NulStr<'a>` to a `&'a str`,including the nul byte. /// /// # Performance /// /// To make this function const-callable, /// this uses a potentially less efficient approach than /// [`to_str_with_nul`](Self::to_str_with_nul). /// /// This conversion requires traversing through the entire string to /// find the nul byte. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// /// const FOO: NulStr<'_> = NulStr::from_str("foo bar\0"); /// const FOO_S: &str = FOO.const_to_str_with_nul(); /// assert_eq!(&FOO_S[..3], "foo"); /// assert_eq!(&FOO_S[4..], "bar\0"); /// /// ``` #[cfg(feature = "rust_1_64")] #[cfg_attr(feature = "docsrs", doc(cfg(feature = "rust_1_64")))] pub const fn const_to_str_with_nul(&self) -> &'a str { unsafe { let len = self.compute_length(); std::str::from_utf8_unchecked(std::slice::from_raw_parts(self.as_ptr(), len + 1)) } } /// Converts this `NulStr<'a>` to a `RStr<'a>`,including the nul byte. /// /// # Performance /// /// This conversion requires traversing through the entire string to /// find the nul byte. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// use abi_stable::std_types::RStr; /// /// const BAZ: NulStr<'_> = NulStr::from_str("baz qux\0"); /// let baz: RStr<'_> = BAZ.to_rstr_with_nul(); /// assert_eq!(&baz[..3], "baz"); /// assert_eq!(&baz[4..], "qux\0"); /// /// ``` pub fn to_rstr_with_nul(&self) -> RStr<'a> { self.to_str_with_nul().into() } /// Converts this `NulStr<'a>` to a `&'a str`,not including the nul byte. /// /// # Performance /// /// This conversion requires traversing through the entire string to /// find the nul byte. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// /// const FOO: NulStr<'_> = NulStr::from_str("foo bar\0"); /// let foo: &str = FOO.to_str(); /// assert_eq!(&foo[..3], "foo"); /// assert_eq!(&foo[4..], "bar"); /// /// ``` pub fn to_str(self) -> &'a str { unsafe { let bytes = std::ffi::CStr::from_ptr(self.ptr.as_ptr() as *const _).to_bytes(); std::str::from_utf8_unchecked(bytes) } } /// Converts this `NulStr<'a>` to a `&'a str`,not including the nul byte. /// /// # Performance /// /// To make this function const-callable, /// this uses a potentially less efficient approach than [`to_str`](Self::to_str). /// /// This conversion requires traversing through the entire string to /// find the nul byte. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// /// const FOO: NulStr<'_> = NulStr::from_str("foo bar\0"); /// const FOO_S: &str = FOO.const_to_str(); /// assert_eq!(&FOO_S[..3], "foo"); /// assert_eq!(&FOO_S[4..], "bar"); /// /// ``` #[cfg(feature = "rust_1_64")] #[cfg_attr(feature = "docsrs", doc(cfg(feature = "rust_1_64")))] pub const fn const_to_str(self) -> &'a str { unsafe { let len = self.compute_length(); std::str::from_utf8_unchecked(std::slice::from_raw_parts(self.as_ptr(), len)) } } /// Converts this `NulStr<'a>` to a `RStr<'a>`,not including the nul byte. /// /// # Performance /// /// This conversion requires traversing through the entire string to /// find the nul byte. /// /// # Example /// /// ```rust /// use abi_stable::sabi_types::NulStr; /// use abi_stable::std_types::RStr; /// /// const BAZ: NulStr<'_> = NulStr::from_str("baz qux\0"); /// let baz: RStr<'_> = BAZ.to_rstr(); /// assert_eq!(&baz[..3], "baz"); /// assert_eq!(&baz[4..], "qux"); /// /// ``` pub fn to_rstr(self) -> RStr<'a> { self.to_str().into() } } impl<'a> PartialEq<NulStr<'a>> for &str { fn eq(&self, other: &NulStr<'a>) -> bool { self.as_ptr() == other.as_ptr() || *self == other.to_str() } } impl<'a> PartialEq<&str> for NulStr<'a> { fn eq(&self, other: &&str) -> bool { self.as_ptr() == other.as_ptr() || self.to_str() == *other } } impl<'a> PartialEq<NulStr<'a>> for str { fn eq(&self, other: &NulStr<'a>) -> bool { self.as_ptr() == other.as_ptr() || self == other.to_str() } } impl<'a> PartialEq<str> for NulStr<'a> { fn eq(&self, other: &str) -> bool { self.as_ptr() == other.as_ptr() || self.to_str() == other } } impl<'a> PartialEq for NulStr<'a> { fn eq(&self, other: &Self) -> bool { self.ptr == other.ptr || self.to_str() == other.to_str() } } impl<'a> Eq for NulStr<'a> {} impl<'a> PartialOrd for NulStr<'a> { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) } } impl<'a> Ord for NulStr<'a> { fn cmp(&self, other: &Self) -> Ordering { if self.ptr == other.ptr { Ordering::Equal } else { self.to_str().cmp(other.to_str()) } } } impl Default for NulStr<'_> { fn default() -> Self { NulStr::EMPTY } } impl Display for NulStr<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Display::fmt(self.to_str(), f) } } impl Debug for NulStr<'_> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { Debug::fmt(self.to_str(), f) } } /// Error from trying to convert a `&str` to a [`NulStr`] /// /// [`NulStr`]: ./struct.NulStr.html #[derive(Debug, PartialEq, Eq, Clone)] #[non_exhaustive] pub enum NulStrError { /// When the string has a `'\0'` before the end. InnerNul { /// the position of the first '\0' character. pos: usize, }, /// When the string doesn't end with `'\0'` NoNulTerminator, } impl Display for NulStrError { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::InnerNul { pos } => { write!(f, "there is an internal nul at the {} byte offset", pos) } Self::NoNulTerminator => f.write_str("there is no nul terminator in the string"), } } } impl std::error::Error for NulStrError {}
use proconio::input; #[allow(unused_imports)] use proconio::marker::*; #[allow(unused_imports)] use std::cmp::{max, min}; #[allow(unused_imports)] use std::collections::*; #[allow(unused_imports)] use std::f64::consts::*; #[allow(unused)] const INF: usize = std::usize::MAX / 4; #[allow(unused)] const M: usize = 1000000007; fn main() { input! { n: usize, p: [usize; n], } let mut indices = BTreeSet::new(); indices.insert(0); indices.insert(1); indices.insert(n + 2); indices.insert(n + 3); let mut p = p .into_iter() .enumerate() .map(|(i, pi)| (pi, i + 2)) .collect::<BinaryHeap<_>>(); let mut s = 0; while let Some((pi, i)) = p.pop() { let mut left = indices.range(..i).rev(); let mut right = indices.range(i..); let &l1 = left.next().unwrap(); let &l2 = left.next().unwrap(); let &r1 = right.next().unwrap(); let &r2 = right.next().unwrap(); // eprintln!("{}", pi); // eprintln!("{} {} {} {} {}", l2, l1, i, r1, r2); if 1 < l1 { s += pi * (l1 - l2) * (r1 - i); } if r1 < n + 2 { s += pi * (r2 - r1) * (i - l1); } // eprintln!(" {}", s); indices.insert(i); } println!("{}", s); }
extern crate pretty_env_logger; #[macro_use] extern crate log; extern crate config; extern crate dirs; use std::env; //use std::path::PathBuf; use structopt::StructOpt; use log::{info, warn, error}; use config::*; #[derive(StructOpt, Debug)] struct Params { /// Verbose mode (-v, -vv, -vvv are possible) #[structopt(short, long, parse(from_occurrences))] verbose: u8, } fn main() { let params = Params::from_args(); set_env_log(params); pretty_env_logger::init_custom_env("RUST_APP_LOG"); let mut config = Config::default(); //let mut config_dir: PathBuf = dirs::config_dir(); //println!("{:?}", dirs::config_dir()); println!("Nothing to see for now, whoopsie!"); info!("such information"); warn!("o_O"); error!("boom"); debug!("deboogging"); // cleanup before exiting env::remove_var("RUST_APP_LOG"); } /// depending on the amount of --verbose, this sets the level of logging to console fn set_env_log(params: Params) { let envlevel; println!("{}", params.verbose); match params.verbose { 0 => envlevel = "error", 1 => envlevel = "warn", 2 => envlevel = "info", 3 | _ => envlevel = "trace", } env::set_var("RUST_APP_LOG", envlevel); }
use crate::*; /// Open a sqlite3 connection and insert or replace a meeting /// We use the SQL commands `INSERT OR REPLACE` in order to overwrite any existing values. pub fn insert_meeting(meeting: Meeting) -> rusqlite::Result<()> { let conn = Connection::open("meetings.sql3")?; conn.execute( "CREATE TABLE IF NOT EXISTS [meetings] ( [uuid] VARCHAR PRIMARY KEY NOT NULL, [duration] VARCHAR NOT NULL, [email] VARCHAR NULL, [end_time] VARCHAR NOT NULL, [has_3rd_party_audio] BOOL NOT NULL, [has_pstn] BOOL NOT NULL, [has_recording] BOOL NOT NULL, [has_screen_share] BOOL NOT NULL, [has_sip] BOOL NOT NULL, [has_video] BOOL NOT NULL, [has_voip] BOOL NOT NULL, [host] VARCHAR NOT NULL, [id] INT NOT NULL, [participants] INT NOT NULL, [start_time] VARCHAR NOT NULL, [topic] VARCHAR NOT NULL, [user_type] VARCHAR NOT NULL );", params![], )?; conn.execute( "INSERT OR REPLACE INTO meetings VALUES (?1,?2,?3,?4,?5,?6,?7,?8,?9,?10,?11,?12,?13,?14,?15,?16,?17);", params![ meeting.uuid, meeting.duration, meeting.email, meeting.end_time, meeting.has_3rd_party_audio, meeting.has_pstn, meeting.has_recording, meeting.has_screen_share, meeting.has_sip, meeting.has_video, meeting.has_voip, meeting.host, meeting.id, meeting.participants, meeting.start_time, meeting.topic, meeting.user_type, ], )?; Ok(()) } /// WARNING: this function is not used currently /// and the same logic is implemented by the Python sctipt /// that consumes the data from the DB. /// Over time that Python script may be ported to this repo /// Open a sqlite3 connection and drop the table /// we also need to vacuum up the freed space pub fn _drop_table_and_clear_memory() -> rusqlite::Result<()> { let conn = Connection::open("meetings.sql3")?; // lets drop the table conn.execute("DROP TABLE meetings;", params![])?; // we need to clean up the space conn.execute("VACUUM;", params![])?; Ok(()) }
// This file was generated by gir (https://github.com/gtk-rs/gir) // from ../gir-files // DO NOT EDIT use crate::CacheType; use crate::SessionFeature; use glib::object::IsA; use glib::translate::*; use glib::StaticType; use std::fmt; glib::wrapper! { #[doc(alias = "SoupCache")] pub struct Cache(Object<ffi::SoupCache, ffi::SoupCacheClass>) @implements SessionFeature; match fn { type_ => || ffi::soup_cache_get_type(), } } impl Cache { #[doc(alias = "soup_cache_new")] pub fn new(cache_dir: Option<&str>, cache_type: CacheType) -> Cache { assert_initialized_main_thread!(); unsafe { from_glib_full(ffi::soup_cache_new(cache_dir.to_glib_none().0, cache_type.into_glib())) } } } pub const NONE_CACHE: Option<&Cache> = None; pub trait CacheExt: 'static { #[doc(alias = "soup_cache_clear")] fn clear(&self); #[doc(alias = "soup_cache_dump")] fn dump(&self); #[doc(alias = "soup_cache_flush")] fn flush(&self); #[doc(alias = "soup_cache_get_max_size")] #[doc(alias = "get_max_size")] fn max_size(&self) -> u32; #[doc(alias = "soup_cache_load")] fn load(&self); #[doc(alias = "soup_cache_set_max_size")] fn set_max_size(&self, max_size: u32); #[doc(alias = "cache-dir")] fn cache_dir(&self) -> Option<glib::GString>; #[doc(alias = "cache-type")] fn cache_type(&self) -> CacheType; } impl<O: IsA<Cache>> CacheExt for O { fn clear(&self) { unsafe { ffi::soup_cache_clear(self.as_ref().to_glib_none().0); } } fn dump(&self) { unsafe { ffi::soup_cache_dump(self.as_ref().to_glib_none().0); } } fn flush(&self) { unsafe { ffi::soup_cache_flush(self.as_ref().to_glib_none().0); } } fn max_size(&self) -> u32 { unsafe { ffi::soup_cache_get_max_size(self.as_ref().to_glib_none().0) } } fn load(&self) { unsafe { ffi::soup_cache_load(self.as_ref().to_glib_none().0); } } fn set_max_size(&self, max_size: u32) { unsafe { ffi::soup_cache_set_max_size(self.as_ref().to_glib_none().0, max_size); } } fn cache_dir(&self) -> Option<glib::GString> { unsafe { let mut value = glib::Value::from_type(<glib::GString as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"cache-dir\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `cache-dir` getter") } } fn cache_type(&self) -> CacheType { unsafe { let mut value = glib::Value::from_type(<CacheType as StaticType>::static_type()); glib::gobject_ffi::g_object_get_property(self.to_glib_none().0 as *mut glib::gobject_ffi::GObject, b"cache-type\0".as_ptr() as *const _, value.to_glib_none_mut().0); value.get().expect("Return Value for property `cache-type` getter") } } } impl fmt::Display for Cache { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.write_str("Cache") } }
# ! [ doc = "General-purpose I/Os" ] # [ doc = r" Register block" ] # [ repr ( C ) ] pub struct Gpio { # [ doc = "0x00 - GPIO port mode register" ] pub moder: Moder, # [ doc = "0x04 - GPIO port output type register" ] pub otyper: Otyper, # [ doc = "0x08 - GPIO port output speed register" ] pub ospeedr: Ospeedr, # [ doc = "0x0c - GPIO port pull-up/pull-down register" ] pub pupdr: Pupdr, # [ doc = "0x10 - GPIO port input data register" ] pub idr: Idr, # [ doc = "0x14 - GPIO port output data register" ] pub odr: Odr, # [ doc = "0x18 - GPIO port bit set/reset register" ] pub bsrr: Bsrr, # [ doc = "0x1c - GPIO port configuration lock register" ] pub lckr: Lckr, # [ doc = "0x20 - GPIO alternate function low register" ] pub afrl: Afrl, # [ doc = "0x24 - GPIO alternate function high register" ] pub afrh: Afrh, # [ doc = "0x28 - Port bit reset register" ] pub brr: Brr, } # [ doc = "GPIO port mode register" ] # [ repr ( C ) ] pub struct Moder { register: ::volatile_register::RW<u32>, } # [ doc = "GPIO port mode register" ] pub mod moder { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Moder { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field MODER15" ] pub struct Moder15R { bits: u8, } impl Moder15R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER14" ] pub struct Moder14R { bits: u8, } impl Moder14R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER13" ] pub struct Moder13R { bits: u8, } impl Moder13R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER12" ] pub struct Moder12R { bits: u8, } impl Moder12R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER11" ] pub struct Moder11R { bits: u8, } impl Moder11R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER10" ] pub struct Moder10R { bits: u8, } impl Moder10R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER9" ] pub struct Moder9R { bits: u8, } impl Moder9R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER8" ] pub struct Moder8R { bits: u8, } impl Moder8R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER7" ] pub struct Moder7R { bits: u8, } impl Moder7R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER6" ] pub struct Moder6R { bits: u8, } impl Moder6R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER5" ] pub struct Moder5R { bits: u8, } impl Moder5R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER4" ] pub struct Moder4R { bits: u8, } impl Moder4R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER3" ] pub struct Moder3R { bits: u8, } impl Moder3R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER2" ] pub struct Moder2R { bits: u8, } impl Moder2R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER1" ] pub struct Moder1R { bits: u8, } impl Moder1R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field MODER0" ] pub struct Moder0R { bits: u8, } impl Moder0R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _Moder15W<'a> { register: &'a mut W, } impl<'a> _Moder15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 30; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder14W<'a> { register: &'a mut W, } impl<'a> _Moder14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 28; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder13W<'a> { register: &'a mut W, } impl<'a> _Moder13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 26; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder12W<'a> { register: &'a mut W, } impl<'a> _Moder12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 24; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder11W<'a> { register: &'a mut W, } impl<'a> _Moder11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 22; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder10W<'a> { register: &'a mut W, } impl<'a> _Moder10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 20; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder9W<'a> { register: &'a mut W, } impl<'a> _Moder9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 18; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder8W<'a> { register: &'a mut W, } impl<'a> _Moder8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 16; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder7W<'a> { register: &'a mut W, } impl<'a> _Moder7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 14; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder6W<'a> { register: &'a mut W, } impl<'a> _Moder6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder5W<'a> { register: &'a mut W, } impl<'a> _Moder5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 10; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder4W<'a> { register: &'a mut W, } impl<'a> _Moder4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder3W<'a> { register: &'a mut W, } impl<'a> _Moder3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 6; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder2W<'a> { register: &'a mut W, } impl<'a> _Moder2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder1W<'a> { register: &'a mut W, } impl<'a> _Moder1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 2; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Moder0W<'a> { register: &'a mut W, } impl<'a> _Moder0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _moder15(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 30:31 - Port x configuration bits (y = 0..15)" ] pub fn moder15(&self) -> Moder15R { Moder15R { bits: self._moder15() } } fn _moder14(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 28:29 - Port x configuration bits (y = 0..15)" ] pub fn moder14(&self) -> Moder14R { Moder14R { bits: self._moder14() } } fn _moder13(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 26; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 26:27 - Port x configuration bits (y = 0..15)" ] pub fn moder13(&self) -> Moder13R { Moder13R { bits: self._moder13() } } fn _moder12(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 24:25 - Port x configuration bits (y = 0..15)" ] pub fn moder12(&self) -> Moder12R { Moder12R { bits: self._moder12() } } fn _moder11(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 22:23 - Port x configuration bits (y = 0..15)" ] pub fn moder11(&self) -> Moder11R { Moder11R { bits: self._moder11() } } fn _moder10(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 20:21 - Port x configuration bits (y = 0..15)" ] pub fn moder10(&self) -> Moder10R { Moder10R { bits: self._moder10() } } fn _moder9(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 18:19 - Port x configuration bits (y = 0..15)" ] pub fn moder9(&self) -> Moder9R { Moder9R { bits: self._moder9() } } fn _moder8(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 16:17 - Port x configuration bits (y = 0..15)" ] pub fn moder8(&self) -> Moder8R { Moder8R { bits: self._moder8() } } fn _moder7(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 14:15 - Port x configuration bits (y = 0..15)" ] pub fn moder7(&self) -> Moder7R { Moder7R { bits: self._moder7() } } fn _moder6(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 12:13 - Port x configuration bits (y = 0..15)" ] pub fn moder6(&self) -> Moder6R { Moder6R { bits: self._moder6() } } fn _moder5(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 10:11 - Port x configuration bits (y = 0..15)" ] pub fn moder5(&self) -> Moder5R { Moder5R { bits: self._moder5() } } fn _moder4(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 8:9 - Port x configuration bits (y = 0..15)" ] pub fn moder4(&self) -> Moder4R { Moder4R { bits: self._moder4() } } fn _moder3(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 6:7 - Port x configuration bits (y = 0..15)" ] pub fn moder3(&self) -> Moder3R { Moder3R { bits: self._moder3() } } fn _moder2(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 4:5 - Port x configuration bits (y = 0..15)" ] pub fn moder2(&self) -> Moder2R { Moder2R { bits: self._moder2() } } fn _moder1(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 2:3 - Port x configuration bits (y = 0..15)" ] pub fn moder1(&self) -> Moder1R { Moder1R { bits: self._moder1() } } fn _moder0(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 0:1 - Port x configuration bits (y = 0..15)" ] pub fn moder0(&self) -> Moder0R { Moder0R { bits: self._moder0() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 671088640 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bits 30:31 - Port x configuration bits (y = 0..15)" ] pub fn moder15(&mut self) -> _Moder15W { _Moder15W { register: self } } # [ doc = "Bits 28:29 - Port x configuration bits (y = 0..15)" ] pub fn moder14(&mut self) -> _Moder14W { _Moder14W { register: self } } # [ doc = "Bits 26:27 - Port x configuration bits (y = 0..15)" ] pub fn moder13(&mut self) -> _Moder13W { _Moder13W { register: self } } # [ doc = "Bits 24:25 - Port x configuration bits (y = 0..15)" ] pub fn moder12(&mut self) -> _Moder12W { _Moder12W { register: self } } # [ doc = "Bits 22:23 - Port x configuration bits (y = 0..15)" ] pub fn moder11(&mut self) -> _Moder11W { _Moder11W { register: self } } # [ doc = "Bits 20:21 - Port x configuration bits (y = 0..15)" ] pub fn moder10(&mut self) -> _Moder10W { _Moder10W { register: self } } # [ doc = "Bits 18:19 - Port x configuration bits (y = 0..15)" ] pub fn moder9(&mut self) -> _Moder9W { _Moder9W { register: self } } # [ doc = "Bits 16:17 - Port x configuration bits (y = 0..15)" ] pub fn moder8(&mut self) -> _Moder8W { _Moder8W { register: self } } # [ doc = "Bits 14:15 - Port x configuration bits (y = 0..15)" ] pub fn moder7(&mut self) -> _Moder7W { _Moder7W { register: self } } # [ doc = "Bits 12:13 - Port x configuration bits (y = 0..15)" ] pub fn moder6(&mut self) -> _Moder6W { _Moder6W { register: self } } # [ doc = "Bits 10:11 - Port x configuration bits (y = 0..15)" ] pub fn moder5(&mut self) -> _Moder5W { _Moder5W { register: self } } # [ doc = "Bits 8:9 - Port x configuration bits (y = 0..15)" ] pub fn moder4(&mut self) -> _Moder4W { _Moder4W { register: self } } # [ doc = "Bits 6:7 - Port x configuration bits (y = 0..15)" ] pub fn moder3(&mut self) -> _Moder3W { _Moder3W { register: self } } # [ doc = "Bits 4:5 - Port x configuration bits (y = 0..15)" ] pub fn moder2(&mut self) -> _Moder2W { _Moder2W { register: self } } # [ doc = "Bits 2:3 - Port x configuration bits (y = 0..15)" ] pub fn moder1(&mut self) -> _Moder1W { _Moder1W { register: self } } # [ doc = "Bits 0:1 - Port x configuration bits (y = 0..15)" ] pub fn moder0(&mut self) -> _Moder0W { _Moder0W { register: self } } } } # [ doc = "GPIO port output type register" ] # [ repr ( C ) ] pub struct Otyper { register: ::volatile_register::RW<u32>, } # [ doc = "GPIO port output type register" ] pub mod otyper { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Otyper { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field OT15" ] pub struct Ot15R { bits: u8, } impl Ot15R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT14" ] pub struct Ot14R { bits: u8, } impl Ot14R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT13" ] pub struct Ot13R { bits: u8, } impl Ot13R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT12" ] pub struct Ot12R { bits: u8, } impl Ot12R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT11" ] pub struct Ot11R { bits: u8, } impl Ot11R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT10" ] pub struct Ot10R { bits: u8, } impl Ot10R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT9" ] pub struct Ot9R { bits: u8, } impl Ot9R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT8" ] pub struct Ot8R { bits: u8, } impl Ot8R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT7" ] pub struct Ot7R { bits: u8, } impl Ot7R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT6" ] pub struct Ot6R { bits: u8, } impl Ot6R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT5" ] pub struct Ot5R { bits: u8, } impl Ot5R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT4" ] pub struct Ot4R { bits: u8, } impl Ot4R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT3" ] pub struct Ot3R { bits: u8, } impl Ot3R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT2" ] pub struct Ot2R { bits: u8, } impl Ot2R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT1" ] pub struct Ot1R { bits: u8, } impl Ot1R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OT0" ] pub struct Ot0R { bits: u8, } impl Ot0R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _Ot15W<'a> { register: &'a mut W, } impl<'a> _Ot15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 15; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot14W<'a> { register: &'a mut W, } impl<'a> _Ot14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 14; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot13W<'a> { register: &'a mut W, } impl<'a> _Ot13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 13; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot12W<'a> { register: &'a mut W, } impl<'a> _Ot12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot11W<'a> { register: &'a mut W, } impl<'a> _Ot11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 11; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot10W<'a> { register: &'a mut W, } impl<'a> _Ot10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 10; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot9W<'a> { register: &'a mut W, } impl<'a> _Ot9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 9; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot8W<'a> { register: &'a mut W, } impl<'a> _Ot8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot7W<'a> { register: &'a mut W, } impl<'a> _Ot7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 7; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot6W<'a> { register: &'a mut W, } impl<'a> _Ot6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 6; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot5W<'a> { register: &'a mut W, } impl<'a> _Ot5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 5; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot4W<'a> { register: &'a mut W, } impl<'a> _Ot4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot3W<'a> { register: &'a mut W, } impl<'a> _Ot3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 3; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot2W<'a> { register: &'a mut W, } impl<'a> _Ot2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 2; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot1W<'a> { register: &'a mut W, } impl<'a> _Ot1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 1; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ot0W<'a> { register: &'a mut W, } impl<'a> _Ot0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _ot15(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 15 - Port x configuration bits (y = 0..15)" ] pub fn ot15(&self) -> Ot15R { Ot15R { bits: self._ot15() } } fn _ot14(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 14 - Port x configuration bits (y = 0..15)" ] pub fn ot14(&self) -> Ot14R { Ot14R { bits: self._ot14() } } fn _ot13(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 13; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 13 - Port x configuration bits (y = 0..15)" ] pub fn ot13(&self) -> Ot13R { Ot13R { bits: self._ot13() } } fn _ot12(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 12 - Port x configuration bits (y = 0..15)" ] pub fn ot12(&self) -> Ot12R { Ot12R { bits: self._ot12() } } fn _ot11(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 11 - Port x configuration bits (y = 0..15)" ] pub fn ot11(&self) -> Ot11R { Ot11R { bits: self._ot11() } } fn _ot10(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 10 - Port x configuration bits (y = 0..15)" ] pub fn ot10(&self) -> Ot10R { Ot10R { bits: self._ot10() } } fn _ot9(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 9 - Port x configuration bits (y = 0..15)" ] pub fn ot9(&self) -> Ot9R { Ot9R { bits: self._ot9() } } fn _ot8(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 8 - Port x configuration bits (y = 0..15)" ] pub fn ot8(&self) -> Ot8R { Ot8R { bits: self._ot8() } } fn _ot7(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 7 - Port x configuration bits (y = 0..15)" ] pub fn ot7(&self) -> Ot7R { Ot7R { bits: self._ot7() } } fn _ot6(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 6 - Port x configuration bits (y = 0..15)" ] pub fn ot6(&self) -> Ot6R { Ot6R { bits: self._ot6() } } fn _ot5(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 5 - Port x configuration bits (y = 0..15)" ] pub fn ot5(&self) -> Ot5R { Ot5R { bits: self._ot5() } } fn _ot4(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 4 - Port x configuration bits (y = 0..15)" ] pub fn ot4(&self) -> Ot4R { Ot4R { bits: self._ot4() } } fn _ot3(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 3 - Port x configuration bits (y = 0..15)" ] pub fn ot3(&self) -> Ot3R { Ot3R { bits: self._ot3() } } fn _ot2(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 2 - Port x configuration bits (y = 0..15)" ] pub fn ot2(&self) -> Ot2R { Ot2R { bits: self._ot2() } } fn _ot1(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 1 - Port x configuration bits (y = 0..15)" ] pub fn ot1(&self) -> Ot1R { Ot1R { bits: self._ot1() } } fn _ot0(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 0 - Port x configuration bits (y = 0..15)" ] pub fn ot0(&self) -> Ot0R { Ot0R { bits: self._ot0() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bit 15 - Port x configuration bits (y = 0..15)" ] pub fn ot15(&mut self) -> _Ot15W { _Ot15W { register: self } } # [ doc = "Bit 14 - Port x configuration bits (y = 0..15)" ] pub fn ot14(&mut self) -> _Ot14W { _Ot14W { register: self } } # [ doc = "Bit 13 - Port x configuration bits (y = 0..15)" ] pub fn ot13(&mut self) -> _Ot13W { _Ot13W { register: self } } # [ doc = "Bit 12 - Port x configuration bits (y = 0..15)" ] pub fn ot12(&mut self) -> _Ot12W { _Ot12W { register: self } } # [ doc = "Bit 11 - Port x configuration bits (y = 0..15)" ] pub fn ot11(&mut self) -> _Ot11W { _Ot11W { register: self } } # [ doc = "Bit 10 - Port x configuration bits (y = 0..15)" ] pub fn ot10(&mut self) -> _Ot10W { _Ot10W { register: self } } # [ doc = "Bit 9 - Port x configuration bits (y = 0..15)" ] pub fn ot9(&mut self) -> _Ot9W { _Ot9W { register: self } } # [ doc = "Bit 8 - Port x configuration bits (y = 0..15)" ] pub fn ot8(&mut self) -> _Ot8W { _Ot8W { register: self } } # [ doc = "Bit 7 - Port x configuration bits (y = 0..15)" ] pub fn ot7(&mut self) -> _Ot7W { _Ot7W { register: self } } # [ doc = "Bit 6 - Port x configuration bits (y = 0..15)" ] pub fn ot6(&mut self) -> _Ot6W { _Ot6W { register: self } } # [ doc = "Bit 5 - Port x configuration bits (y = 0..15)" ] pub fn ot5(&mut self) -> _Ot5W { _Ot5W { register: self } } # [ doc = "Bit 4 - Port x configuration bits (y = 0..15)" ] pub fn ot4(&mut self) -> _Ot4W { _Ot4W { register: self } } # [ doc = "Bit 3 - Port x configuration bits (y = 0..15)" ] pub fn ot3(&mut self) -> _Ot3W { _Ot3W { register: self } } # [ doc = "Bit 2 - Port x configuration bits (y = 0..15)" ] pub fn ot2(&mut self) -> _Ot2W { _Ot2W { register: self } } # [ doc = "Bit 1 - Port x configuration bits (y = 0..15)" ] pub fn ot1(&mut self) -> _Ot1W { _Ot1W { register: self } } # [ doc = "Bit 0 - Port x configuration bits (y = 0..15)" ] pub fn ot0(&mut self) -> _Ot0W { _Ot0W { register: self } } } } # [ doc = "GPIO port output speed register" ] # [ repr ( C ) ] pub struct Ospeedr { register: ::volatile_register::RW<u32>, } # [ doc = "GPIO port output speed register" ] pub mod ospeedr { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Ospeedr { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field OSPEEDR15" ] pub struct Ospeedr15R { bits: u8, } impl Ospeedr15R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR14" ] pub struct Ospeedr14R { bits: u8, } impl Ospeedr14R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR13" ] pub struct Ospeedr13R { bits: u8, } impl Ospeedr13R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR12" ] pub struct Ospeedr12R { bits: u8, } impl Ospeedr12R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR11" ] pub struct Ospeedr11R { bits: u8, } impl Ospeedr11R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR10" ] pub struct Ospeedr10R { bits: u8, } impl Ospeedr10R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR9" ] pub struct Ospeedr9R { bits: u8, } impl Ospeedr9R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR8" ] pub struct Ospeedr8R { bits: u8, } impl Ospeedr8R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR7" ] pub struct Ospeedr7R { bits: u8, } impl Ospeedr7R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR6" ] pub struct Ospeedr6R { bits: u8, } impl Ospeedr6R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR5" ] pub struct Ospeedr5R { bits: u8, } impl Ospeedr5R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR4" ] pub struct Ospeedr4R { bits: u8, } impl Ospeedr4R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR3" ] pub struct Ospeedr3R { bits: u8, } impl Ospeedr3R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR2" ] pub struct Ospeedr2R { bits: u8, } impl Ospeedr2R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR1" ] pub struct Ospeedr1R { bits: u8, } impl Ospeedr1R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field OSPEEDR0" ] pub struct Ospeedr0R { bits: u8, } impl Ospeedr0R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _Ospeedr15W<'a> { register: &'a mut W, } impl<'a> _Ospeedr15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 30; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr14W<'a> { register: &'a mut W, } impl<'a> _Ospeedr14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 28; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr13W<'a> { register: &'a mut W, } impl<'a> _Ospeedr13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 26; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr12W<'a> { register: &'a mut W, } impl<'a> _Ospeedr12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 24; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr11W<'a> { register: &'a mut W, } impl<'a> _Ospeedr11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 22; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr10W<'a> { register: &'a mut W, } impl<'a> _Ospeedr10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 20; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr9W<'a> { register: &'a mut W, } impl<'a> _Ospeedr9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 18; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr8W<'a> { register: &'a mut W, } impl<'a> _Ospeedr8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 16; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr7W<'a> { register: &'a mut W, } impl<'a> _Ospeedr7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 14; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr6W<'a> { register: &'a mut W, } impl<'a> _Ospeedr6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr5W<'a> { register: &'a mut W, } impl<'a> _Ospeedr5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 10; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr4W<'a> { register: &'a mut W, } impl<'a> _Ospeedr4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr3W<'a> { register: &'a mut W, } impl<'a> _Ospeedr3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 6; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr2W<'a> { register: &'a mut W, } impl<'a> _Ospeedr2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr1W<'a> { register: &'a mut W, } impl<'a> _Ospeedr1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 2; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Ospeedr0W<'a> { register: &'a mut W, } impl<'a> _Ospeedr0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _ospeedr15(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 30:31 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr15(&self) -> Ospeedr15R { Ospeedr15R { bits: self._ospeedr15() } } fn _ospeedr14(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 28:29 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr14(&self) -> Ospeedr14R { Ospeedr14R { bits: self._ospeedr14() } } fn _ospeedr13(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 26; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 26:27 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr13(&self) -> Ospeedr13R { Ospeedr13R { bits: self._ospeedr13() } } fn _ospeedr12(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 24:25 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr12(&self) -> Ospeedr12R { Ospeedr12R { bits: self._ospeedr12() } } fn _ospeedr11(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 22:23 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr11(&self) -> Ospeedr11R { Ospeedr11R { bits: self._ospeedr11() } } fn _ospeedr10(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 20:21 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr10(&self) -> Ospeedr10R { Ospeedr10R { bits: self._ospeedr10() } } fn _ospeedr9(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 18:19 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr9(&self) -> Ospeedr9R { Ospeedr9R { bits: self._ospeedr9() } } fn _ospeedr8(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 16:17 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr8(&self) -> Ospeedr8R { Ospeedr8R { bits: self._ospeedr8() } } fn _ospeedr7(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 14:15 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr7(&self) -> Ospeedr7R { Ospeedr7R { bits: self._ospeedr7() } } fn _ospeedr6(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 12:13 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr6(&self) -> Ospeedr6R { Ospeedr6R { bits: self._ospeedr6() } } fn _ospeedr5(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 10:11 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr5(&self) -> Ospeedr5R { Ospeedr5R { bits: self._ospeedr5() } } fn _ospeedr4(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 8:9 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr4(&self) -> Ospeedr4R { Ospeedr4R { bits: self._ospeedr4() } } fn _ospeedr3(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 6:7 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr3(&self) -> Ospeedr3R { Ospeedr3R { bits: self._ospeedr3() } } fn _ospeedr2(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 4:5 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr2(&self) -> Ospeedr2R { Ospeedr2R { bits: self._ospeedr2() } } fn _ospeedr1(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 2:3 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr1(&self) -> Ospeedr1R { Ospeedr1R { bits: self._ospeedr1() } } fn _ospeedr0(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 0:1 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr0(&self) -> Ospeedr0R { Ospeedr0R { bits: self._ospeedr0() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bits 30:31 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr15(&mut self) -> _Ospeedr15W { _Ospeedr15W { register: self } } # [ doc = "Bits 28:29 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr14(&mut self) -> _Ospeedr14W { _Ospeedr14W { register: self } } # [ doc = "Bits 26:27 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr13(&mut self) -> _Ospeedr13W { _Ospeedr13W { register: self } } # [ doc = "Bits 24:25 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr12(&mut self) -> _Ospeedr12W { _Ospeedr12W { register: self } } # [ doc = "Bits 22:23 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr11(&mut self) -> _Ospeedr11W { _Ospeedr11W { register: self } } # [ doc = "Bits 20:21 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr10(&mut self) -> _Ospeedr10W { _Ospeedr10W { register: self } } # [ doc = "Bits 18:19 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr9(&mut self) -> _Ospeedr9W { _Ospeedr9W { register: self } } # [ doc = "Bits 16:17 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr8(&mut self) -> _Ospeedr8W { _Ospeedr8W { register: self } } # [ doc = "Bits 14:15 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr7(&mut self) -> _Ospeedr7W { _Ospeedr7W { register: self } } # [ doc = "Bits 12:13 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr6(&mut self) -> _Ospeedr6W { _Ospeedr6W { register: self } } # [ doc = "Bits 10:11 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr5(&mut self) -> _Ospeedr5W { _Ospeedr5W { register: self } } # [ doc = "Bits 8:9 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr4(&mut self) -> _Ospeedr4W { _Ospeedr4W { register: self } } # [ doc = "Bits 6:7 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr3(&mut self) -> _Ospeedr3W { _Ospeedr3W { register: self } } # [ doc = "Bits 4:5 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr2(&mut self) -> _Ospeedr2W { _Ospeedr2W { register: self } } # [ doc = "Bits 2:3 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr1(&mut self) -> _Ospeedr1W { _Ospeedr1W { register: self } } # [ doc = "Bits 0:1 - Port x configuration bits (y = 0..15)" ] pub fn ospeedr0(&mut self) -> _Ospeedr0W { _Ospeedr0W { register: self } } } } # [ doc = "GPIO port pull-up/pull-down register" ] # [ repr ( C ) ] pub struct Pupdr { register: ::volatile_register::RW<u32>, } # [ doc = "GPIO port pull-up/pull-down register" ] pub mod pupdr { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Pupdr { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field PUPDR15" ] pub struct Pupdr15R { bits: u8, } impl Pupdr15R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR14" ] pub struct Pupdr14R { bits: u8, } impl Pupdr14R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR13" ] pub struct Pupdr13R { bits: u8, } impl Pupdr13R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR12" ] pub struct Pupdr12R { bits: u8, } impl Pupdr12R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR11" ] pub struct Pupdr11R { bits: u8, } impl Pupdr11R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR10" ] pub struct Pupdr10R { bits: u8, } impl Pupdr10R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR9" ] pub struct Pupdr9R { bits: u8, } impl Pupdr9R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR8" ] pub struct Pupdr8R { bits: u8, } impl Pupdr8R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR7" ] pub struct Pupdr7R { bits: u8, } impl Pupdr7R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR6" ] pub struct Pupdr6R { bits: u8, } impl Pupdr6R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR5" ] pub struct Pupdr5R { bits: u8, } impl Pupdr5R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR4" ] pub struct Pupdr4R { bits: u8, } impl Pupdr4R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR3" ] pub struct Pupdr3R { bits: u8, } impl Pupdr3R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR2" ] pub struct Pupdr2R { bits: u8, } impl Pupdr2R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR1" ] pub struct Pupdr1R { bits: u8, } impl Pupdr1R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field PUPDR0" ] pub struct Pupdr0R { bits: u8, } impl Pupdr0R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _Pupdr15W<'a> { register: &'a mut W, } impl<'a> _Pupdr15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 30; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr14W<'a> { register: &'a mut W, } impl<'a> _Pupdr14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 28; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr13W<'a> { register: &'a mut W, } impl<'a> _Pupdr13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 26; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr12W<'a> { register: &'a mut W, } impl<'a> _Pupdr12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 24; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr11W<'a> { register: &'a mut W, } impl<'a> _Pupdr11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 22; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr10W<'a> { register: &'a mut W, } impl<'a> _Pupdr10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 20; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr9W<'a> { register: &'a mut W, } impl<'a> _Pupdr9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 18; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr8W<'a> { register: &'a mut W, } impl<'a> _Pupdr8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 16; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr7W<'a> { register: &'a mut W, } impl<'a> _Pupdr7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 14; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr6W<'a> { register: &'a mut W, } impl<'a> _Pupdr6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr5W<'a> { register: &'a mut W, } impl<'a> _Pupdr5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 10; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr4W<'a> { register: &'a mut W, } impl<'a> _Pupdr4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr3W<'a> { register: &'a mut W, } impl<'a> _Pupdr3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 6; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr2W<'a> { register: &'a mut W, } impl<'a> _Pupdr2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr1W<'a> { register: &'a mut W, } impl<'a> _Pupdr1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 2; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Pupdr0W<'a> { register: &'a mut W, } impl<'a> _Pupdr0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 3; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _pupdr15(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 30; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 30:31 - Port x configuration bits (y = 0..15)" ] pub fn pupdr15(&self) -> Pupdr15R { Pupdr15R { bits: self._pupdr15() } } fn _pupdr14(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 28:29 - Port x configuration bits (y = 0..15)" ] pub fn pupdr14(&self) -> Pupdr14R { Pupdr14R { bits: self._pupdr14() } } fn _pupdr13(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 26; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 26:27 - Port x configuration bits (y = 0..15)" ] pub fn pupdr13(&self) -> Pupdr13R { Pupdr13R { bits: self._pupdr13() } } fn _pupdr12(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 24:25 - Port x configuration bits (y = 0..15)" ] pub fn pupdr12(&self) -> Pupdr12R { Pupdr12R { bits: self._pupdr12() } } fn _pupdr11(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 22; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 22:23 - Port x configuration bits (y = 0..15)" ] pub fn pupdr11(&self) -> Pupdr11R { Pupdr11R { bits: self._pupdr11() } } fn _pupdr10(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 20:21 - Port x configuration bits (y = 0..15)" ] pub fn pupdr10(&self) -> Pupdr10R { Pupdr10R { bits: self._pupdr10() } } fn _pupdr9(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 18; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 18:19 - Port x configuration bits (y = 0..15)" ] pub fn pupdr9(&self) -> Pupdr9R { Pupdr9R { bits: self._pupdr9() } } fn _pupdr8(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 16:17 - Port x configuration bits (y = 0..15)" ] pub fn pupdr8(&self) -> Pupdr8R { Pupdr8R { bits: self._pupdr8() } } fn _pupdr7(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 14:15 - Port x configuration bits (y = 0..15)" ] pub fn pupdr7(&self) -> Pupdr7R { Pupdr7R { bits: self._pupdr7() } } fn _pupdr6(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 12:13 - Port x configuration bits (y = 0..15)" ] pub fn pupdr6(&self) -> Pupdr6R { Pupdr6R { bits: self._pupdr6() } } fn _pupdr5(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 10:11 - Port x configuration bits (y = 0..15)" ] pub fn pupdr5(&self) -> Pupdr5R { Pupdr5R { bits: self._pupdr5() } } fn _pupdr4(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 8:9 - Port x configuration bits (y = 0..15)" ] pub fn pupdr4(&self) -> Pupdr4R { Pupdr4R { bits: self._pupdr4() } } fn _pupdr3(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 6:7 - Port x configuration bits (y = 0..15)" ] pub fn pupdr3(&self) -> Pupdr3R { Pupdr3R { bits: self._pupdr3() } } fn _pupdr2(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 4:5 - Port x configuration bits (y = 0..15)" ] pub fn pupdr2(&self) -> Pupdr2R { Pupdr2R { bits: self._pupdr2() } } fn _pupdr1(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 2:3 - Port x configuration bits (y = 0..15)" ] pub fn pupdr1(&self) -> Pupdr1R { Pupdr1R { bits: self._pupdr1() } } fn _pupdr0(&self) -> u8 { const MASK: u8 = 3; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 0:1 - Port x configuration bits (y = 0..15)" ] pub fn pupdr0(&self) -> Pupdr0R { Pupdr0R { bits: self._pupdr0() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 603979776 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bits 30:31 - Port x configuration bits (y = 0..15)" ] pub fn pupdr15(&mut self) -> _Pupdr15W { _Pupdr15W { register: self } } # [ doc = "Bits 28:29 - Port x configuration bits (y = 0..15)" ] pub fn pupdr14(&mut self) -> _Pupdr14W { _Pupdr14W { register: self } } # [ doc = "Bits 26:27 - Port x configuration bits (y = 0..15)" ] pub fn pupdr13(&mut self) -> _Pupdr13W { _Pupdr13W { register: self } } # [ doc = "Bits 24:25 - Port x configuration bits (y = 0..15)" ] pub fn pupdr12(&mut self) -> _Pupdr12W { _Pupdr12W { register: self } } # [ doc = "Bits 22:23 - Port x configuration bits (y = 0..15)" ] pub fn pupdr11(&mut self) -> _Pupdr11W { _Pupdr11W { register: self } } # [ doc = "Bits 20:21 - Port x configuration bits (y = 0..15)" ] pub fn pupdr10(&mut self) -> _Pupdr10W { _Pupdr10W { register: self } } # [ doc = "Bits 18:19 - Port x configuration bits (y = 0..15)" ] pub fn pupdr9(&mut self) -> _Pupdr9W { _Pupdr9W { register: self } } # [ doc = "Bits 16:17 - Port x configuration bits (y = 0..15)" ] pub fn pupdr8(&mut self) -> _Pupdr8W { _Pupdr8W { register: self } } # [ doc = "Bits 14:15 - Port x configuration bits (y = 0..15)" ] pub fn pupdr7(&mut self) -> _Pupdr7W { _Pupdr7W { register: self } } # [ doc = "Bits 12:13 - Port x configuration bits (y = 0..15)" ] pub fn pupdr6(&mut self) -> _Pupdr6W { _Pupdr6W { register: self } } # [ doc = "Bits 10:11 - Port x configuration bits (y = 0..15)" ] pub fn pupdr5(&mut self) -> _Pupdr5W { _Pupdr5W { register: self } } # [ doc = "Bits 8:9 - Port x configuration bits (y = 0..15)" ] pub fn pupdr4(&mut self) -> _Pupdr4W { _Pupdr4W { register: self } } # [ doc = "Bits 6:7 - Port x configuration bits (y = 0..15)" ] pub fn pupdr3(&mut self) -> _Pupdr3W { _Pupdr3W { register: self } } # [ doc = "Bits 4:5 - Port x configuration bits (y = 0..15)" ] pub fn pupdr2(&mut self) -> _Pupdr2W { _Pupdr2W { register: self } } # [ doc = "Bits 2:3 - Port x configuration bits (y = 0..15)" ] pub fn pupdr1(&mut self) -> _Pupdr1W { _Pupdr1W { register: self } } # [ doc = "Bits 0:1 - Port x configuration bits (y = 0..15)" ] pub fn pupdr0(&mut self) -> _Pupdr0W { _Pupdr0W { register: self } } } } # [ doc = "GPIO port input data register" ] # [ repr ( C ) ] pub struct Idr { register: ::volatile_register::RO<u32>, } # [ doc = "GPIO port input data register" ] pub mod idr { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } impl super::Idr { # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } } # [ doc = "Value of the field IDR15" ] pub struct Idr15R { bits: u8, } impl Idr15R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR14" ] pub struct Idr14R { bits: u8, } impl Idr14R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR13" ] pub struct Idr13R { bits: u8, } impl Idr13R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR12" ] pub struct Idr12R { bits: u8, } impl Idr12R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR11" ] pub struct Idr11R { bits: u8, } impl Idr11R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR10" ] pub struct Idr10R { bits: u8, } impl Idr10R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR9" ] pub struct Idr9R { bits: u8, } impl Idr9R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR8" ] pub struct Idr8R { bits: u8, } impl Idr8R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR7" ] pub struct Idr7R { bits: u8, } impl Idr7R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR6" ] pub struct Idr6R { bits: u8, } impl Idr6R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR5" ] pub struct Idr5R { bits: u8, } impl Idr5R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR4" ] pub struct Idr4R { bits: u8, } impl Idr4R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR3" ] pub struct Idr3R { bits: u8, } impl Idr3R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR2" ] pub struct Idr2R { bits: u8, } impl Idr2R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR1" ] pub struct Idr1R { bits: u8, } impl Idr1R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field IDR0" ] pub struct Idr0R { bits: u8, } impl Idr0R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _idr15(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 15 - Port input data (y = 0..15)" ] pub fn idr15(&self) -> Idr15R { Idr15R { bits: self._idr15() } } fn _idr14(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 14 - Port input data (y = 0..15)" ] pub fn idr14(&self) -> Idr14R { Idr14R { bits: self._idr14() } } fn _idr13(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 13; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 13 - Port input data (y = 0..15)" ] pub fn idr13(&self) -> Idr13R { Idr13R { bits: self._idr13() } } fn _idr12(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 12 - Port input data (y = 0..15)" ] pub fn idr12(&self) -> Idr12R { Idr12R { bits: self._idr12() } } fn _idr11(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 11 - Port input data (y = 0..15)" ] pub fn idr11(&self) -> Idr11R { Idr11R { bits: self._idr11() } } fn _idr10(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 10 - Port input data (y = 0..15)" ] pub fn idr10(&self) -> Idr10R { Idr10R { bits: self._idr10() } } fn _idr9(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 9 - Port input data (y = 0..15)" ] pub fn idr9(&self) -> Idr9R { Idr9R { bits: self._idr9() } } fn _idr8(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 8 - Port input data (y = 0..15)" ] pub fn idr8(&self) -> Idr8R { Idr8R { bits: self._idr8() } } fn _idr7(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 7 - Port input data (y = 0..15)" ] pub fn idr7(&self) -> Idr7R { Idr7R { bits: self._idr7() } } fn _idr6(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 6 - Port input data (y = 0..15)" ] pub fn idr6(&self) -> Idr6R { Idr6R { bits: self._idr6() } } fn _idr5(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 5 - Port input data (y = 0..15)" ] pub fn idr5(&self) -> Idr5R { Idr5R { bits: self._idr5() } } fn _idr4(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 4 - Port input data (y = 0..15)" ] pub fn idr4(&self) -> Idr4R { Idr4R { bits: self._idr4() } } fn _idr3(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 3 - Port input data (y = 0..15)" ] pub fn idr3(&self) -> Idr3R { Idr3R { bits: self._idr3() } } fn _idr2(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 2 - Port input data (y = 0..15)" ] pub fn idr2(&self) -> Idr2R { Idr2R { bits: self._idr2() } } fn _idr1(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 1 - Port input data (y = 0..15)" ] pub fn idr1(&self) -> Idr1R { Idr1R { bits: self._idr1() } } fn _idr0(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 0 - Port input data (y = 0..15)" ] pub fn idr0(&self) -> Idr0R { Idr0R { bits: self._idr0() } } } } # [ doc = "GPIO port output data register" ] # [ repr ( C ) ] pub struct Odr { register: ::volatile_register::RW<u32>, } # [ doc = "GPIO port output data register" ] pub mod odr { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Odr { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field ODR15" ] pub struct Odr15R { bits: u8, } impl Odr15R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR14" ] pub struct Odr14R { bits: u8, } impl Odr14R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR13" ] pub struct Odr13R { bits: u8, } impl Odr13R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR12" ] pub struct Odr12R { bits: u8, } impl Odr12R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR11" ] pub struct Odr11R { bits: u8, } impl Odr11R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR10" ] pub struct Odr10R { bits: u8, } impl Odr10R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR9" ] pub struct Odr9R { bits: u8, } impl Odr9R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR8" ] pub struct Odr8R { bits: u8, } impl Odr8R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR7" ] pub struct Odr7R { bits: u8, } impl Odr7R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR6" ] pub struct Odr6R { bits: u8, } impl Odr6R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR5" ] pub struct Odr5R { bits: u8, } impl Odr5R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR4" ] pub struct Odr4R { bits: u8, } impl Odr4R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR3" ] pub struct Odr3R { bits: u8, } impl Odr3R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR2" ] pub struct Odr2R { bits: u8, } impl Odr2R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR1" ] pub struct Odr1R { bits: u8, } impl Odr1R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field ODR0" ] pub struct Odr0R { bits: u8, } impl Odr0R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _Odr15W<'a> { register: &'a mut W, } impl<'a> _Odr15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 15; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr14W<'a> { register: &'a mut W, } impl<'a> _Odr14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 14; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr13W<'a> { register: &'a mut W, } impl<'a> _Odr13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 13; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr12W<'a> { register: &'a mut W, } impl<'a> _Odr12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr11W<'a> { register: &'a mut W, } impl<'a> _Odr11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 11; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr10W<'a> { register: &'a mut W, } impl<'a> _Odr10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 10; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr9W<'a> { register: &'a mut W, } impl<'a> _Odr9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 9; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr8W<'a> { register: &'a mut W, } impl<'a> _Odr8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr7W<'a> { register: &'a mut W, } impl<'a> _Odr7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 7; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr6W<'a> { register: &'a mut W, } impl<'a> _Odr6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 6; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr5W<'a> { register: &'a mut W, } impl<'a> _Odr5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 5; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr4W<'a> { register: &'a mut W, } impl<'a> _Odr4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr3W<'a> { register: &'a mut W, } impl<'a> _Odr3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 3; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr2W<'a> { register: &'a mut W, } impl<'a> _Odr2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 2; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr1W<'a> { register: &'a mut W, } impl<'a> _Odr1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 1; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Odr0W<'a> { register: &'a mut W, } impl<'a> _Odr0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _odr15(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 15 - Port output data (y = 0..15)" ] pub fn odr15(&self) -> Odr15R { Odr15R { bits: self._odr15() } } fn _odr14(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 14 - Port output data (y = 0..15)" ] pub fn odr14(&self) -> Odr14R { Odr14R { bits: self._odr14() } } fn _odr13(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 13; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 13 - Port output data (y = 0..15)" ] pub fn odr13(&self) -> Odr13R { Odr13R { bits: self._odr13() } } fn _odr12(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 12 - Port output data (y = 0..15)" ] pub fn odr12(&self) -> Odr12R { Odr12R { bits: self._odr12() } } fn _odr11(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 11 - Port output data (y = 0..15)" ] pub fn odr11(&self) -> Odr11R { Odr11R { bits: self._odr11() } } fn _odr10(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 10 - Port output data (y = 0..15)" ] pub fn odr10(&self) -> Odr10R { Odr10R { bits: self._odr10() } } fn _odr9(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 9 - Port output data (y = 0..15)" ] pub fn odr9(&self) -> Odr9R { Odr9R { bits: self._odr9() } } fn _odr8(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 8 - Port output data (y = 0..15)" ] pub fn odr8(&self) -> Odr8R { Odr8R { bits: self._odr8() } } fn _odr7(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 7 - Port output data (y = 0..15)" ] pub fn odr7(&self) -> Odr7R { Odr7R { bits: self._odr7() } } fn _odr6(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 6 - Port output data (y = 0..15)" ] pub fn odr6(&self) -> Odr6R { Odr6R { bits: self._odr6() } } fn _odr5(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 5 - Port output data (y = 0..15)" ] pub fn odr5(&self) -> Odr5R { Odr5R { bits: self._odr5() } } fn _odr4(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 4 - Port output data (y = 0..15)" ] pub fn odr4(&self) -> Odr4R { Odr4R { bits: self._odr4() } } fn _odr3(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 3 - Port output data (y = 0..15)" ] pub fn odr3(&self) -> Odr3R { Odr3R { bits: self._odr3() } } fn _odr2(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 2 - Port output data (y = 0..15)" ] pub fn odr2(&self) -> Odr2R { Odr2R { bits: self._odr2() } } fn _odr1(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 1 - Port output data (y = 0..15)" ] pub fn odr1(&self) -> Odr1R { Odr1R { bits: self._odr1() } } fn _odr0(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 0 - Port output data (y = 0..15)" ] pub fn odr0(&self) -> Odr0R { Odr0R { bits: self._odr0() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bit 15 - Port output data (y = 0..15)" ] pub fn odr15(&mut self) -> _Odr15W { _Odr15W { register: self } } # [ doc = "Bit 14 - Port output data (y = 0..15)" ] pub fn odr14(&mut self) -> _Odr14W { _Odr14W { register: self } } # [ doc = "Bit 13 - Port output data (y = 0..15)" ] pub fn odr13(&mut self) -> _Odr13W { _Odr13W { register: self } } # [ doc = "Bit 12 - Port output data (y = 0..15)" ] pub fn odr12(&mut self) -> _Odr12W { _Odr12W { register: self } } # [ doc = "Bit 11 - Port output data (y = 0..15)" ] pub fn odr11(&mut self) -> _Odr11W { _Odr11W { register: self } } # [ doc = "Bit 10 - Port output data (y = 0..15)" ] pub fn odr10(&mut self) -> _Odr10W { _Odr10W { register: self } } # [ doc = "Bit 9 - Port output data (y = 0..15)" ] pub fn odr9(&mut self) -> _Odr9W { _Odr9W { register: self } } # [ doc = "Bit 8 - Port output data (y = 0..15)" ] pub fn odr8(&mut self) -> _Odr8W { _Odr8W { register: self } } # [ doc = "Bit 7 - Port output data (y = 0..15)" ] pub fn odr7(&mut self) -> _Odr7W { _Odr7W { register: self } } # [ doc = "Bit 6 - Port output data (y = 0..15)" ] pub fn odr6(&mut self) -> _Odr6W { _Odr6W { register: self } } # [ doc = "Bit 5 - Port output data (y = 0..15)" ] pub fn odr5(&mut self) -> _Odr5W { _Odr5W { register: self } } # [ doc = "Bit 4 - Port output data (y = 0..15)" ] pub fn odr4(&mut self) -> _Odr4W { _Odr4W { register: self } } # [ doc = "Bit 3 - Port output data (y = 0..15)" ] pub fn odr3(&mut self) -> _Odr3W { _Odr3W { register: self } } # [ doc = "Bit 2 - Port output data (y = 0..15)" ] pub fn odr2(&mut self) -> _Odr2W { _Odr2W { register: self } } # [ doc = "Bit 1 - Port output data (y = 0..15)" ] pub fn odr1(&mut self) -> _Odr1W { _Odr1W { register: self } } # [ doc = "Bit 0 - Port output data (y = 0..15)" ] pub fn odr0(&mut self) -> _Odr0W { _Odr0W { register: self } } } } # [ doc = "GPIO port bit set/reset register" ] # [ repr ( C ) ] pub struct Bsrr { register: ::volatile_register::WO<u32>, } # [ doc = "GPIO port bit set/reset register" ] pub mod bsrr { # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Bsrr { # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = r" Proxy" ] pub struct _Br15W<'a> { register: &'a mut W, } impl<'a> _Br15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 31; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br14W<'a> { register: &'a mut W, } impl<'a> _Br14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 30; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br13W<'a> { register: &'a mut W, } impl<'a> _Br13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 29; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br12W<'a> { register: &'a mut W, } impl<'a> _Br12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 28; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br11W<'a> { register: &'a mut W, } impl<'a> _Br11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 27; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br10W<'a> { register: &'a mut W, } impl<'a> _Br10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 26; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br9W<'a> { register: &'a mut W, } impl<'a> _Br9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 25; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br8W<'a> { register: &'a mut W, } impl<'a> _Br8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 24; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br7W<'a> { register: &'a mut W, } impl<'a> _Br7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 23; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br6W<'a> { register: &'a mut W, } impl<'a> _Br6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 22; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br5W<'a> { register: &'a mut W, } impl<'a> _Br5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 21; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br4W<'a> { register: &'a mut W, } impl<'a> _Br4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 20; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br3W<'a> { register: &'a mut W, } impl<'a> _Br3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 19; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br2W<'a> { register: &'a mut W, } impl<'a> _Br2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 18; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br1W<'a> { register: &'a mut W, } impl<'a> _Br1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 17; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br0W<'a> { register: &'a mut W, } impl<'a> _Br0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 16; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs15W<'a> { register: &'a mut W, } impl<'a> _Bs15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 15; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs14W<'a> { register: &'a mut W, } impl<'a> _Bs14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 14; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs13W<'a> { register: &'a mut W, } impl<'a> _Bs13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 13; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs12W<'a> { register: &'a mut W, } impl<'a> _Bs12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs11W<'a> { register: &'a mut W, } impl<'a> _Bs11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 11; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs10W<'a> { register: &'a mut W, } impl<'a> _Bs10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 10; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs9W<'a> { register: &'a mut W, } impl<'a> _Bs9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 9; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs8W<'a> { register: &'a mut W, } impl<'a> _Bs8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs7W<'a> { register: &'a mut W, } impl<'a> _Bs7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 7; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs6W<'a> { register: &'a mut W, } impl<'a> _Bs6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 6; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs5W<'a> { register: &'a mut W, } impl<'a> _Bs5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 5; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs4W<'a> { register: &'a mut W, } impl<'a> _Bs4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs3W<'a> { register: &'a mut W, } impl<'a> _Bs3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 3; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs2W<'a> { register: &'a mut W, } impl<'a> _Bs2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 2; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs1W<'a> { register: &'a mut W, } impl<'a> _Bs1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 1; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Bs0W<'a> { register: &'a mut W, } impl<'a> _Bs0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bit 31 - Port x reset bit y (y = 0..15)" ] pub fn br15(&mut self) -> _Br15W { _Br15W { register: self } } # [ doc = "Bit 30 - Port x reset bit y (y = 0..15)" ] pub fn br14(&mut self) -> _Br14W { _Br14W { register: self } } # [ doc = "Bit 29 - Port x reset bit y (y = 0..15)" ] pub fn br13(&mut self) -> _Br13W { _Br13W { register: self } } # [ doc = "Bit 28 - Port x reset bit y (y = 0..15)" ] pub fn br12(&mut self) -> _Br12W { _Br12W { register: self } } # [ doc = "Bit 27 - Port x reset bit y (y = 0..15)" ] pub fn br11(&mut self) -> _Br11W { _Br11W { register: self } } # [ doc = "Bit 26 - Port x reset bit y (y = 0..15)" ] pub fn br10(&mut self) -> _Br10W { _Br10W { register: self } } # [ doc = "Bit 25 - Port x reset bit y (y = 0..15)" ] pub fn br9(&mut self) -> _Br9W { _Br9W { register: self } } # [ doc = "Bit 24 - Port x reset bit y (y = 0..15)" ] pub fn br8(&mut self) -> _Br8W { _Br8W { register: self } } # [ doc = "Bit 23 - Port x reset bit y (y = 0..15)" ] pub fn br7(&mut self) -> _Br7W { _Br7W { register: self } } # [ doc = "Bit 22 - Port x reset bit y (y = 0..15)" ] pub fn br6(&mut self) -> _Br6W { _Br6W { register: self } } # [ doc = "Bit 21 - Port x reset bit y (y = 0..15)" ] pub fn br5(&mut self) -> _Br5W { _Br5W { register: self } } # [ doc = "Bit 20 - Port x reset bit y (y = 0..15)" ] pub fn br4(&mut self) -> _Br4W { _Br4W { register: self } } # [ doc = "Bit 19 - Port x reset bit y (y = 0..15)" ] pub fn br3(&mut self) -> _Br3W { _Br3W { register: self } } # [ doc = "Bit 18 - Port x reset bit y (y = 0..15)" ] pub fn br2(&mut self) -> _Br2W { _Br2W { register: self } } # [ doc = "Bit 17 - Port x reset bit y (y = 0..15)" ] pub fn br1(&mut self) -> _Br1W { _Br1W { register: self } } # [ doc = "Bit 16 - Port x set bit y (y= 0..15)" ] pub fn br0(&mut self) -> _Br0W { _Br0W { register: self } } # [ doc = "Bit 15 - Port x set bit y (y= 0..15)" ] pub fn bs15(&mut self) -> _Bs15W { _Bs15W { register: self } } # [ doc = "Bit 14 - Port x set bit y (y= 0..15)" ] pub fn bs14(&mut self) -> _Bs14W { _Bs14W { register: self } } # [ doc = "Bit 13 - Port x set bit y (y= 0..15)" ] pub fn bs13(&mut self) -> _Bs13W { _Bs13W { register: self } } # [ doc = "Bit 12 - Port x set bit y (y= 0..15)" ] pub fn bs12(&mut self) -> _Bs12W { _Bs12W { register: self } } # [ doc = "Bit 11 - Port x set bit y (y= 0..15)" ] pub fn bs11(&mut self) -> _Bs11W { _Bs11W { register: self } } # [ doc = "Bit 10 - Port x set bit y (y= 0..15)" ] pub fn bs10(&mut self) -> _Bs10W { _Bs10W { register: self } } # [ doc = "Bit 9 - Port x set bit y (y= 0..15)" ] pub fn bs9(&mut self) -> _Bs9W { _Bs9W { register: self } } # [ doc = "Bit 8 - Port x set bit y (y= 0..15)" ] pub fn bs8(&mut self) -> _Bs8W { _Bs8W { register: self } } # [ doc = "Bit 7 - Port x set bit y (y= 0..15)" ] pub fn bs7(&mut self) -> _Bs7W { _Bs7W { register: self } } # [ doc = "Bit 6 - Port x set bit y (y= 0..15)" ] pub fn bs6(&mut self) -> _Bs6W { _Bs6W { register: self } } # [ doc = "Bit 5 - Port x set bit y (y= 0..15)" ] pub fn bs5(&mut self) -> _Bs5W { _Bs5W { register: self } } # [ doc = "Bit 4 - Port x set bit y (y= 0..15)" ] pub fn bs4(&mut self) -> _Bs4W { _Bs4W { register: self } } # [ doc = "Bit 3 - Port x set bit y (y= 0..15)" ] pub fn bs3(&mut self) -> _Bs3W { _Bs3W { register: self } } # [ doc = "Bit 2 - Port x set bit y (y= 0..15)" ] pub fn bs2(&mut self) -> _Bs2W { _Bs2W { register: self } } # [ doc = "Bit 1 - Port x set bit y (y= 0..15)" ] pub fn bs1(&mut self) -> _Bs1W { _Bs1W { register: self } } # [ doc = "Bit 0 - Port x set bit y (y= 0..15)" ] pub fn bs0(&mut self) -> _Bs0W { _Bs0W { register: self } } } } # [ doc = "GPIO port configuration lock register" ] # [ repr ( C ) ] pub struct Lckr { register: ::volatile_register::RW<u32>, } # [ doc = "GPIO port configuration lock register" ] pub mod lckr { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Lckr { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field LCKK" ] pub struct LckkR { bits: u8, } impl LckkR { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK15" ] pub struct Lck15R { bits: u8, } impl Lck15R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK14" ] pub struct Lck14R { bits: u8, } impl Lck14R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK13" ] pub struct Lck13R { bits: u8, } impl Lck13R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK12" ] pub struct Lck12R { bits: u8, } impl Lck12R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK11" ] pub struct Lck11R { bits: u8, } impl Lck11R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK10" ] pub struct Lck10R { bits: u8, } impl Lck10R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK9" ] pub struct Lck9R { bits: u8, } impl Lck9R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK8" ] pub struct Lck8R { bits: u8, } impl Lck8R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK7" ] pub struct Lck7R { bits: u8, } impl Lck7R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK6" ] pub struct Lck6R { bits: u8, } impl Lck6R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK5" ] pub struct Lck5R { bits: u8, } impl Lck5R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK4" ] pub struct Lck4R { bits: u8, } impl Lck4R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK3" ] pub struct Lck3R { bits: u8, } impl Lck3R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK2" ] pub struct Lck2R { bits: u8, } impl Lck2R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK1" ] pub struct Lck1R { bits: u8, } impl Lck1R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field LCK0" ] pub struct Lck0R { bits: u8, } impl Lck0R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _LckkW<'a> { register: &'a mut W, } impl<'a> _LckkW<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 16; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck15W<'a> { register: &'a mut W, } impl<'a> _Lck15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 15; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck14W<'a> { register: &'a mut W, } impl<'a> _Lck14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 14; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck13W<'a> { register: &'a mut W, } impl<'a> _Lck13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 13; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck12W<'a> { register: &'a mut W, } impl<'a> _Lck12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck11W<'a> { register: &'a mut W, } impl<'a> _Lck11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 11; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck10W<'a> { register: &'a mut W, } impl<'a> _Lck10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 10; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck9W<'a> { register: &'a mut W, } impl<'a> _Lck9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 9; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck8W<'a> { register: &'a mut W, } impl<'a> _Lck8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck7W<'a> { register: &'a mut W, } impl<'a> _Lck7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 7; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck6W<'a> { register: &'a mut W, } impl<'a> _Lck6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 6; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck5W<'a> { register: &'a mut W, } impl<'a> _Lck5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 5; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck4W<'a> { register: &'a mut W, } impl<'a> _Lck4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck3W<'a> { register: &'a mut W, } impl<'a> _Lck3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 3; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck2W<'a> { register: &'a mut W, } impl<'a> _Lck2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 2; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck1W<'a> { register: &'a mut W, } impl<'a> _Lck1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 1; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Lck0W<'a> { register: &'a mut W, } impl<'a> _Lck0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _lckk(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 16 - Port x lock bit y (y= 0..15)" ] pub fn lckk(&self) -> LckkR { LckkR { bits: self._lckk() } } fn _lck15(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 15; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 15 - Port x lock bit y (y= 0..15)" ] pub fn lck15(&self) -> Lck15R { Lck15R { bits: self._lck15() } } fn _lck14(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 14; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 14 - Port x lock bit y (y= 0..15)" ] pub fn lck14(&self) -> Lck14R { Lck14R { bits: self._lck14() } } fn _lck13(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 13; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 13 - Port x lock bit y (y= 0..15)" ] pub fn lck13(&self) -> Lck13R { Lck13R { bits: self._lck13() } } fn _lck12(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 12 - Port x lock bit y (y= 0..15)" ] pub fn lck12(&self) -> Lck12R { Lck12R { bits: self._lck12() } } fn _lck11(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 11; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 11 - Port x lock bit y (y= 0..15)" ] pub fn lck11(&self) -> Lck11R { Lck11R { bits: self._lck11() } } fn _lck10(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 10; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 10 - Port x lock bit y (y= 0..15)" ] pub fn lck10(&self) -> Lck10R { Lck10R { bits: self._lck10() } } fn _lck9(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 9; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 9 - Port x lock bit y (y= 0..15)" ] pub fn lck9(&self) -> Lck9R { Lck9R { bits: self._lck9() } } fn _lck8(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 8 - Port x lock bit y (y= 0..15)" ] pub fn lck8(&self) -> Lck8R { Lck8R { bits: self._lck8() } } fn _lck7(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 7; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 7 - Port x lock bit y (y= 0..15)" ] pub fn lck7(&self) -> Lck7R { Lck7R { bits: self._lck7() } } fn _lck6(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 6; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 6 - Port x lock bit y (y= 0..15)" ] pub fn lck6(&self) -> Lck6R { Lck6R { bits: self._lck6() } } fn _lck5(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 5; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 5 - Port x lock bit y (y= 0..15)" ] pub fn lck5(&self) -> Lck5R { Lck5R { bits: self._lck5() } } fn _lck4(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 4 - Port x lock bit y (y= 0..15)" ] pub fn lck4(&self) -> Lck4R { Lck4R { bits: self._lck4() } } fn _lck3(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 3; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 3 - Port x lock bit y (y= 0..15)" ] pub fn lck3(&self) -> Lck3R { Lck3R { bits: self._lck3() } } fn _lck2(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 2; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 2 - Port x lock bit y (y= 0..15)" ] pub fn lck2(&self) -> Lck2R { Lck2R { bits: self._lck2() } } fn _lck1(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 1; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 1 - Port x lock bit y (y= 0..15)" ] pub fn lck1(&self) -> Lck1R { Lck1R { bits: self._lck1() } } fn _lck0(&self) -> u8 { const MASK: u8 = 1; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bit 0 - Port x lock bit y (y= 0..15)" ] pub fn lck0(&self) -> Lck0R { Lck0R { bits: self._lck0() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bit 16 - Port x lock bit y (y= 0..15)" ] pub fn lckk(&mut self) -> _LckkW { _LckkW { register: self } } # [ doc = "Bit 15 - Port x lock bit y (y= 0..15)" ] pub fn lck15(&mut self) -> _Lck15W { _Lck15W { register: self } } # [ doc = "Bit 14 - Port x lock bit y (y= 0..15)" ] pub fn lck14(&mut self) -> _Lck14W { _Lck14W { register: self } } # [ doc = "Bit 13 - Port x lock bit y (y= 0..15)" ] pub fn lck13(&mut self) -> _Lck13W { _Lck13W { register: self } } # [ doc = "Bit 12 - Port x lock bit y (y= 0..15)" ] pub fn lck12(&mut self) -> _Lck12W { _Lck12W { register: self } } # [ doc = "Bit 11 - Port x lock bit y (y= 0..15)" ] pub fn lck11(&mut self) -> _Lck11W { _Lck11W { register: self } } # [ doc = "Bit 10 - Port x lock bit y (y= 0..15)" ] pub fn lck10(&mut self) -> _Lck10W { _Lck10W { register: self } } # [ doc = "Bit 9 - Port x lock bit y (y= 0..15)" ] pub fn lck9(&mut self) -> _Lck9W { _Lck9W { register: self } } # [ doc = "Bit 8 - Port x lock bit y (y= 0..15)" ] pub fn lck8(&mut self) -> _Lck8W { _Lck8W { register: self } } # [ doc = "Bit 7 - Port x lock bit y (y= 0..15)" ] pub fn lck7(&mut self) -> _Lck7W { _Lck7W { register: self } } # [ doc = "Bit 6 - Port x lock bit y (y= 0..15)" ] pub fn lck6(&mut self) -> _Lck6W { _Lck6W { register: self } } # [ doc = "Bit 5 - Port x lock bit y (y= 0..15)" ] pub fn lck5(&mut self) -> _Lck5W { _Lck5W { register: self } } # [ doc = "Bit 4 - Port x lock bit y (y= 0..15)" ] pub fn lck4(&mut self) -> _Lck4W { _Lck4W { register: self } } # [ doc = "Bit 3 - Port x lock bit y (y= 0..15)" ] pub fn lck3(&mut self) -> _Lck3W { _Lck3W { register: self } } # [ doc = "Bit 2 - Port x lock bit y (y= 0..15)" ] pub fn lck2(&mut self) -> _Lck2W { _Lck2W { register: self } } # [ doc = "Bit 1 - Port x lock bit y (y= 0..15)" ] pub fn lck1(&mut self) -> _Lck1W { _Lck1W { register: self } } # [ doc = "Bit 0 - Port x lock bit y (y= 0..15)" ] pub fn lck0(&mut self) -> _Lck0W { _Lck0W { register: self } } } } # [ doc = "GPIO alternate function low register" ] # [ repr ( C ) ] pub struct Afrl { register: ::volatile_register::RW<u32>, } # [ doc = "GPIO alternate function low register" ] pub mod afrl { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Afrl { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field AFRL7" ] pub struct Afrl7R { bits: u8, } impl Afrl7R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRL6" ] pub struct Afrl6R { bits: u8, } impl Afrl6R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRL5" ] pub struct Afrl5R { bits: u8, } impl Afrl5R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRL4" ] pub struct Afrl4R { bits: u8, } impl Afrl4R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRL3" ] pub struct Afrl3R { bits: u8, } impl Afrl3R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRL2" ] pub struct Afrl2R { bits: u8, } impl Afrl2R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRL1" ] pub struct Afrl1R { bits: u8, } impl Afrl1R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRL0" ] pub struct Afrl0R { bits: u8, } impl Afrl0R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _Afrl7W<'a> { register: &'a mut W, } impl<'a> _Afrl7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 28; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrl6W<'a> { register: &'a mut W, } impl<'a> _Afrl6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 24; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrl5W<'a> { register: &'a mut W, } impl<'a> _Afrl5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 20; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrl4W<'a> { register: &'a mut W, } impl<'a> _Afrl4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 16; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrl3W<'a> { register: &'a mut W, } impl<'a> _Afrl3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrl2W<'a> { register: &'a mut W, } impl<'a> _Afrl2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrl1W<'a> { register: &'a mut W, } impl<'a> _Afrl1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrl0W<'a> { register: &'a mut W, } impl<'a> _Afrl0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _afrl7(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 28:31 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl7(&self) -> Afrl7R { Afrl7R { bits: self._afrl7() } } fn _afrl6(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 24:27 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl6(&self) -> Afrl6R { Afrl6R { bits: self._afrl6() } } fn _afrl5(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 20:23 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl5(&self) -> Afrl5R { Afrl5R { bits: self._afrl5() } } fn _afrl4(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 16:19 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl4(&self) -> Afrl4R { Afrl4R { bits: self._afrl4() } } fn _afrl3(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 12:15 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl3(&self) -> Afrl3R { Afrl3R { bits: self._afrl3() } } fn _afrl2(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 8:11 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl2(&self) -> Afrl2R { Afrl2R { bits: self._afrl2() } } fn _afrl1(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 4:7 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl1(&self) -> Afrl1R { Afrl1R { bits: self._afrl1() } } fn _afrl0(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 0:3 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl0(&self) -> Afrl0R { Afrl0R { bits: self._afrl0() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bits 28:31 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl7(&mut self) -> _Afrl7W { _Afrl7W { register: self } } # [ doc = "Bits 24:27 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl6(&mut self) -> _Afrl6W { _Afrl6W { register: self } } # [ doc = "Bits 20:23 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl5(&mut self) -> _Afrl5W { _Afrl5W { register: self } } # [ doc = "Bits 16:19 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl4(&mut self) -> _Afrl4W { _Afrl4W { register: self } } # [ doc = "Bits 12:15 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl3(&mut self) -> _Afrl3W { _Afrl3W { register: self } } # [ doc = "Bits 8:11 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl2(&mut self) -> _Afrl2W { _Afrl2W { register: self } } # [ doc = "Bits 4:7 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl1(&mut self) -> _Afrl1W { _Afrl1W { register: self } } # [ doc = "Bits 0:3 - Alternate function selection for port x bit y (y = 0..7)" ] pub fn afrl0(&mut self) -> _Afrl0W { _Afrl0W { register: self } } } } # [ doc = "GPIO alternate function high register" ] # [ repr ( C ) ] pub struct Afrh { register: ::volatile_register::RW<u32>, } # [ doc = "GPIO alternate function high register" ] pub mod afrh { # [ doc = r" Value read from the register" ] pub struct R { bits: u32, } # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Afrh { # [ doc = r" Modifies the contents of the register" ] pub fn modify<F>(&mut self, f: F) where for<'w> F: FnOnce(&R, &'w mut W) -> &'w mut W { let bits = self.register.read(); let r = R { bits: bits }; let mut w = W { bits: bits }; f(&r, &mut w); self.register.write(w.bits); } # [ doc = r" Reads the contents of the register" ] pub fn read(&self) -> R { R { bits: self.register.read() } } # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = "Value of the field AFRH15" ] pub struct Afrh15R { bits: u8, } impl Afrh15R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRH14" ] pub struct Afrh14R { bits: u8, } impl Afrh14R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRH13" ] pub struct Afrh13R { bits: u8, } impl Afrh13R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRH12" ] pub struct Afrh12R { bits: u8, } impl Afrh12R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRH11" ] pub struct Afrh11R { bits: u8, } impl Afrh11R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRH10" ] pub struct Afrh10R { bits: u8, } impl Afrh10R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRH9" ] pub struct Afrh9R { bits: u8, } impl Afrh9R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = "Value of the field AFRH8" ] pub struct Afrh8R { bits: u8, } impl Afrh8R { # [ doc = r" Value of the field as raw bits" ] pub fn bits(&self) -> u8 { self.bits } } # [ doc = r" Proxy" ] pub struct _Afrh15W<'a> { register: &'a mut W, } impl<'a> _Afrh15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 28; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrh14W<'a> { register: &'a mut W, } impl<'a> _Afrh14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 24; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrh13W<'a> { register: &'a mut W, } impl<'a> _Afrh13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 20; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrh12W<'a> { register: &'a mut W, } impl<'a> _Afrh12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 16; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrh11W<'a> { register: &'a mut W, } impl<'a> _Afrh11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrh10W<'a> { register: &'a mut W, } impl<'a> _Afrh10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrh9W<'a> { register: &'a mut W, } impl<'a> _Afrh9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Afrh8W<'a> { register: &'a mut W, } impl<'a> _Afrh8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 15; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl R { # [ doc = r" Value of the register as raw bits" ] pub fn bits(&self) -> u32 { self.bits } fn _afrh15(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 28; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 28:31 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh15(&self) -> Afrh15R { Afrh15R { bits: self._afrh15() } } fn _afrh14(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 24; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 24:27 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh14(&self) -> Afrh14R { Afrh14R { bits: self._afrh14() } } fn _afrh13(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 20; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 20:23 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh13(&self) -> Afrh13R { Afrh13R { bits: self._afrh13() } } fn _afrh12(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 16; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 16:19 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh12(&self) -> Afrh12R { Afrh12R { bits: self._afrh12() } } fn _afrh11(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 12; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 12:15 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh11(&self) -> Afrh11R { Afrh11R { bits: self._afrh11() } } fn _afrh10(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 8; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 8:11 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh10(&self) -> Afrh10R { Afrh10R { bits: self._afrh10() } } fn _afrh9(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 4; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 4:7 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh9(&self) -> Afrh9R { Afrh9R { bits: self._afrh9() } } fn _afrh8(&self) -> u8 { const MASK: u8 = 15; const OFFSET: u8 = 0; ((self.bits >> OFFSET) & MASK as u32) as u8 } # [ doc = "Bits 0:3 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh8(&self) -> Afrh8R { Afrh8R { bits: self._afrh8() } } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bits 28:31 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh15(&mut self) -> _Afrh15W { _Afrh15W { register: self } } # [ doc = "Bits 24:27 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh14(&mut self) -> _Afrh14W { _Afrh14W { register: self } } # [ doc = "Bits 20:23 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh13(&mut self) -> _Afrh13W { _Afrh13W { register: self } } # [ doc = "Bits 16:19 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh12(&mut self) -> _Afrh12W { _Afrh12W { register: self } } # [ doc = "Bits 12:15 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh11(&mut self) -> _Afrh11W { _Afrh11W { register: self } } # [ doc = "Bits 8:11 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh10(&mut self) -> _Afrh10W { _Afrh10W { register: self } } # [ doc = "Bits 4:7 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh9(&mut self) -> _Afrh9W { _Afrh9W { register: self } } # [ doc = "Bits 0:3 - Alternate function selection for port x bit y (y = 8..15)" ] pub fn afrh8(&mut self) -> _Afrh8W { _Afrh8W { register: self } } } } # [ doc = "Port bit reset register" ] # [ repr ( C ) ] pub struct Brr { register: ::volatile_register::WO<u32>, } # [ doc = "Port bit reset register" ] pub mod brr { # [ doc = r" Value to write to the register" ] pub struct W { bits: u32, } impl super::Brr { # [ doc = r" Writes to the register" ] pub fn write<F>(&mut self, f: F) where F: FnOnce(&mut W) -> &mut W { let mut w = W::reset_value(); f(&mut w); self.register.write(w.bits); } } # [ doc = r" Proxy" ] pub struct _Br0W<'a> { register: &'a mut W, } impl<'a> _Br0W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 0; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br1W<'a> { register: &'a mut W, } impl<'a> _Br1W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 1; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br2W<'a> { register: &'a mut W, } impl<'a> _Br2W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 2; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br3W<'a> { register: &'a mut W, } impl<'a> _Br3W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 3; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br4W<'a> { register: &'a mut W, } impl<'a> _Br4W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 4; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br5W<'a> { register: &'a mut W, } impl<'a> _Br5W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 5; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br6W<'a> { register: &'a mut W, } impl<'a> _Br6W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 6; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br7W<'a> { register: &'a mut W, } impl<'a> _Br7W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 7; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br8W<'a> { register: &'a mut W, } impl<'a> _Br8W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 8; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br9W<'a> { register: &'a mut W, } impl<'a> _Br9W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 9; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br10W<'a> { register: &'a mut W, } impl<'a> _Br10W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 10; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br11W<'a> { register: &'a mut W, } impl<'a> _Br11W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 11; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br12W<'a> { register: &'a mut W, } impl<'a> _Br12W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 12; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br13W<'a> { register: &'a mut W, } impl<'a> _Br13W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 13; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br14W<'a> { register: &'a mut W, } impl<'a> _Br14W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 14; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } # [ doc = r" Proxy" ] pub struct _Br15W<'a> { register: &'a mut W, } impl<'a> _Br15W<'a> { # [ doc = r" Writes raw `bits` to the field" ] pub unsafe fn bits(self, bits: u8) -> &'a mut W { const MASK: u8 = 1; const OFFSET: u8 = 15; self.register.bits &= !((MASK as u32) << OFFSET); self.register.bits |= ((bits & MASK) as u32) << OFFSET; self.register } } impl W { # [ doc = r" Reset value of the register" ] pub fn reset_value() -> W { W { bits: 0 } } # [ doc = r" Writes raw `bits` to the register" ] pub unsafe fn bits(&mut self, bits: u32) -> &mut Self { self.bits = bits; self } # [ doc = "Bit 0 - Port x Reset bit y" ] pub fn br0(&mut self) -> _Br0W { _Br0W { register: self } } # [ doc = "Bit 1 - Port x Reset bit y" ] pub fn br1(&mut self) -> _Br1W { _Br1W { register: self } } # [ doc = "Bit 2 - Port x Reset bit y" ] pub fn br2(&mut self) -> _Br2W { _Br2W { register: self } } # [ doc = "Bit 3 - Port x Reset bit y" ] pub fn br3(&mut self) -> _Br3W { _Br3W { register: self } } # [ doc = "Bit 4 - Port x Reset bit y" ] pub fn br4(&mut self) -> _Br4W { _Br4W { register: self } } # [ doc = "Bit 5 - Port x Reset bit y" ] pub fn br5(&mut self) -> _Br5W { _Br5W { register: self } } # [ doc = "Bit 6 - Port x Reset bit y" ] pub fn br6(&mut self) -> _Br6W { _Br6W { register: self } } # [ doc = "Bit 7 - Port x Reset bit y" ] pub fn br7(&mut self) -> _Br7W { _Br7W { register: self } } # [ doc = "Bit 8 - Port x Reset bit y" ] pub fn br8(&mut self) -> _Br8W { _Br8W { register: self } } # [ doc = "Bit 9 - Port x Reset bit y" ] pub fn br9(&mut self) -> _Br9W { _Br9W { register: self } } # [ doc = "Bit 10 - Port x Reset bit y" ] pub fn br10(&mut self) -> _Br10W { _Br10W { register: self } } # [ doc = "Bit 11 - Port x Reset bit y" ] pub fn br11(&mut self) -> _Br11W { _Br11W { register: self } } # [ doc = "Bit 12 - Port x Reset bit y" ] pub fn br12(&mut self) -> _Br12W { _Br12W { register: self } } # [ doc = "Bit 13 - Port x Reset bit y" ] pub fn br13(&mut self) -> _Br13W { _Br13W { register: self } } # [ doc = "Bit 14 - Port x Reset bit y" ] pub fn br14(&mut self) -> _Br14W { _Br14W { register: self } } # [ doc = "Bit 15 - Port x Reset bit y" ] pub fn br15(&mut self) -> _Br15W { _Br15W { register: self } } } }
use crate::token_type::TokenType; #[derive(Debug, Eq, PartialEq, Default, Clone)] pub struct Token { pub token_type: TokenType, pub literal: String, } impl Token { pub fn new(token_type: TokenType, literal: String) -> Self { Self { token_type, literal, } } } impl std::fmt::Display for Token { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { write!(f, "[Type:{}, Literal: {}]", self.token_type, self.literal) } }
use proconio::input; fn cross(x: i64, y: i64, xx: i64, yy: i64) -> i64 { x * yy - y * xx } fn ok(x1: i64, y1: i64, x2: i64, y2: i64, x3: i64, y3: i64) -> bool { cross(x3 - x2, y3 - y2, x1 - x2, y1 - y2) > 0 } fn main() { input! { ax: i64, ay: i64, bx: i64, by: i64, cx: i64, cy: i64, dx: i64, dy: i64, }; if ok(ax, ay, bx, by, cx, cy) && ok(bx, by, cx, cy, dx, dy) && ok(cx, cy, dx, dy, ax, ay) && ok(dx, dy, ax, ay, bx, by) { println!("Yes"); } else { println!("No"); } }
use rustviz_lib::data::{ExternalEvent, LifetimeTrait, ResourceAccessPoint, Owner, MutRef, StaticRef, Function, VisualizationData, Visualizable}; use rustviz_lib::svg_frontend::svg_generation; use std::collections::BTreeMap; fn main() { let s1 = ResourceAccessPoint::Owner(Owner { hash: 1, name: String::from("s1"), is_mut: true, lifetime_trait: LifetimeTrait::Move, }); let s2 = ResourceAccessPoint::Owner(Owner { hash: 2, name: String::from("s2"), is_mut: false, lifetime_trait: LifetimeTrait::Move, }); let string_ctor = Some(ResourceAccessPoint::Function(Function { hash: 5, name: String::from("String::from()"), })); let push1_func = Some(ResourceAccessPoint::Function(Function { hash: 6, name: String::from("String::push_str()"), })); let push2_func = Some(ResourceAccessPoint::Function(Function { hash: 7, name: String::from("push_str()"), })); let print_func = Some(ResourceAccessPoint::Function(Function { hash: 8, name: String::from("println!()"), })); let mut vd = VisualizationData { timelines: BTreeMap::new(), external_events: Vec::new(), preprocess_external_events: Vec::new(), event_line_map: BTreeMap::new() }; vd.append_external_event(ExternalEvent::Move{from: string_ctor.clone(), to: Some(s1.clone())}, &(2 as usize)); vd.append_external_event(ExternalEvent::Move{from: string_ctor.clone(), to: Some(s2.clone())}, &(3 as usize)); vd.append_external_event(ExternalEvent::PassByMutableReference{from: Some(s1.clone()), to: push1_func.clone()}, &(4 as usize)); vd.append_external_event(ExternalEvent::PassByStaticReference{from: Some(s2.clone()), to: push1_func.clone()}, &(4 as usize)); vd.append_external_event(ExternalEvent::PassByMutableReference{from: Some(s1.clone()), to: push2_func.clone()}, &(5 as usize)); vd.append_external_event(ExternalEvent::PassByStaticReference{from: Some(s2.clone()), to: push2_func.clone()}, &(5 as usize)); vd.append_external_event(ExternalEvent::PassByStaticReference{from: Some(s1.clone()), to: print_func.clone()}, &(6 as usize)); vd.append_external_event(ExternalEvent::GoOutOfScope{ ro : s1.clone() }, &(7 as usize)); vd.append_external_event(ExternalEvent::GoOutOfScope{ ro : s2.clone() }, &(7 as usize)); //rendering image svg_generation::render_svg(&"examples/mutable_borrow_method_call/input/".to_owned(), &"examples/mutable_borrow_method_call/".to_owned(), &mut vd); }
use byteorder::LittleEndian; use crate::io::Buf; use crate::mysql::protocol::{AuthPlugin, Capabilities, Status}; // https://dev.mysql.com/doc/dev/mysql-server/8.0.12/page_protocol_connection_phase_packets_protocol_handshake_v10.html // https://mariadb.com/kb/en/connection/#initial-handshake-packet #[derive(Debug)] pub(crate) struct Handshake { pub(crate) protocol_version: u8, pub(crate) server_version: Box<str>, pub(crate) connection_id: u32, pub(crate) server_capabilities: Capabilities, pub(crate) server_default_collation: u8, pub(crate) status: Status, pub(crate) auth_plugin: AuthPlugin, pub(crate) auth_plugin_data: Box<[u8]>, } impl Handshake { pub(crate) fn read(mut buf: &[u8]) -> crate::Result<Self> where Self: Sized, { let protocol_version = buf.get_u8()?; let server_version = buf.get_str_nul()?.into(); let connection_id = buf.get_u32::<LittleEndian>()?; let mut scramble = Vec::with_capacity(8); // scramble first part : string<8> scramble.extend_from_slice(&buf[..8]); buf.advance(8); // reserved : string<1> buf.advance(1); // capability_flags_1 : int<2> let capabilities_1 = buf.get_u16::<LittleEndian>()?; let mut capabilities = Capabilities::from_bits_truncate(capabilities_1.into()); // character_set : int<1> let char_set = buf.get_u8()?; // status_flags : int<2> let status = buf.get_u16::<LittleEndian>()?; let status = Status::from_bits_truncate(status); // capability_flags_2 : int<2> let capabilities_2 = buf.get_u16::<LittleEndian>()?; capabilities |= Capabilities::from_bits_truncate(((capabilities_2 as u32) << 16).into()); let auth_plugin_data_len = if capabilities.contains(Capabilities::PLUGIN_AUTH) { // plugin data length : int<1> buf.get_u8()? } else { // 0x00 : int<1> buf.advance(0); 0 }; // reserved: string<6> buf.advance(6); if capabilities.contains(Capabilities::MYSQL) { // reserved: string<4> buf.advance(4); } else { // capability_flags_3 : int<4> let capabilities_3 = buf.get_u32::<LittleEndian>()?; capabilities |= Capabilities::from_bits_truncate((capabilities_3 as u64) << 32); } if capabilities.contains(Capabilities::SECURE_CONNECTION) { // scramble 2nd part : string<n> ( Length = max(12, plugin data length - 9) ) let len = ((auth_plugin_data_len as isize) - 9).max(12) as usize; scramble.extend_from_slice(&buf[..len]); buf.advance(len); // reserved : string<1> buf.advance(1); } let auth_plugin = if capabilities.contains(Capabilities::PLUGIN_AUTH) { AuthPlugin::from_opt_str(Some(buf.get_str_nul()?))? } else { AuthPlugin::from_opt_str(None)? }; Ok(Self { protocol_version, server_capabilities: capabilities, server_version, server_default_collation: char_set, connection_id, auth_plugin_data: scramble.into_boxed_slice(), auth_plugin, status, }) } } #[cfg(test)] mod tests { use super::{AuthPlugin, Capabilities, Handshake, Status}; const HANDSHAKE_MARIA_DB_10_4_7: &[u8] = b"\n5.5.5-10.4.7-MariaDB-1:10.4.7+maria~bionic\x00\x0b\x00\x00\x00t6L\\j\"dS\x00\xfe\xf7\x08\x02\x00\xff\x81\x15\x00\x00\x00\x00\x00\x00\x07\x00\x00\x00U14Oph9\"<H5n\x00mysql_native_password\x00"; const HANDSHAKE_MYSQL_8_0_18: &[u8] = b"\n8.0.18\x00\x19\x00\x00\x00\x114aB0c\x06g\x00\xff\xff\xff\x02\x00\xff\xc7\x15\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00tL\x03s\x0f[4\rl4. \x00caching_sha2_password\x00"; #[test] fn it_reads_handshake_mysql_8_0_18() { let mut p = Handshake::read(HANDSHAKE_MYSQL_8_0_18).unwrap(); assert_eq!(p.protocol_version, 10); p.server_capabilities.toggle( Capabilities::MYSQL | Capabilities::FOUND_ROWS | Capabilities::LONG_FLAG | Capabilities::CONNECT_WITH_DB | Capabilities::NO_SCHEMA | Capabilities::COMPRESS | Capabilities::ODBC | Capabilities::LOCAL_FILES | Capabilities::IGNORE_SPACE | Capabilities::PROTOCOL_41 | Capabilities::INTERACTIVE | Capabilities::SSL | Capabilities::TRANSACTIONS | Capabilities::SECURE_CONNECTION | Capabilities::MULTI_STATEMENTS | Capabilities::MULTI_RESULTS | Capabilities::PS_MULTI_RESULTS | Capabilities::PLUGIN_AUTH | Capabilities::CONNECT_ATTRS | Capabilities::PLUGIN_AUTH_LENENC_DATA | Capabilities::CAN_HANDLE_EXPIRED_PASSWORDS | Capabilities::SESSION_TRACK | Capabilities::DEPRECATE_EOF | Capabilities::ZSTD_COMPRESSION_ALGORITHM | Capabilities::SSL_VERIFY_SERVER_CERT | Capabilities::OPTIONAL_RESULTSET_METADATA | Capabilities::REMEMBER_OPTIONS, ); assert!(p.server_capabilities.is_empty()); assert_eq!(p.server_default_collation, 255); assert!(p.status.contains(Status::SERVER_STATUS_AUTOCOMMIT)); assert!(matches!(p.auth_plugin, AuthPlugin::CachingSha2Password)); assert_eq!( &*p.auth_plugin_data, &[17, 52, 97, 66, 48, 99, 6, 103, 116, 76, 3, 115, 15, 91, 52, 13, 108, 52, 46, 32,] ); } #[test] fn it_reads_handshake_mariadb_10_4_7() { let mut p = Handshake::read(HANDSHAKE_MARIA_DB_10_4_7).unwrap(); assert_eq!(p.protocol_version, 10); assert_eq!( &*p.server_version, "5.5.5-10.4.7-MariaDB-1:10.4.7+maria~bionic" ); p.server_capabilities.toggle( Capabilities::FOUND_ROWS | Capabilities::LONG_FLAG | Capabilities::CONNECT_WITH_DB | Capabilities::NO_SCHEMA | Capabilities::COMPRESS | Capabilities::ODBC | Capabilities::LOCAL_FILES | Capabilities::IGNORE_SPACE | Capabilities::PROTOCOL_41 | Capabilities::INTERACTIVE | Capabilities::TRANSACTIONS | Capabilities::SECURE_CONNECTION | Capabilities::MULTI_STATEMENTS | Capabilities::MULTI_RESULTS | Capabilities::PS_MULTI_RESULTS | Capabilities::PLUGIN_AUTH | Capabilities::CONNECT_ATTRS | Capabilities::PLUGIN_AUTH_LENENC_DATA | Capabilities::CAN_HANDLE_EXPIRED_PASSWORDS | Capabilities::SESSION_TRACK | Capabilities::DEPRECATE_EOF | Capabilities::REMEMBER_OPTIONS, ); assert!(p.server_capabilities.is_empty()); assert_eq!(p.server_default_collation, 8); assert!(p.status.contains(Status::SERVER_STATUS_AUTOCOMMIT)); assert!(matches!(p.auth_plugin, AuthPlugin::MySqlNativePassword)); assert_eq!( &*p.auth_plugin_data, &[ 116, 54, 76, 92, 106, 34, 100, 83, 85, 49, 52, 79, 112, 104, 57, 34, 60, 72, 53, 110, ] ); } }
extern crate svmon_parser; extern crate regex; use svmon_parser::svmon::Svmon; use regex::Regex; use std::fs::File; use std::io::{self, BufReader}; use std::io::prelude::*; use std::env; use std::process; use std::error::Error; fn main() { let stdin = io::stdin(); let args: Vec<String> = env::args().collect(); //まだUTF-8だけに対応 //引数を渡して、BufReadトレイトオブジェクトを受け取る。 //中身はファイルか標準入力のどちらか。 //エラーの場合はここで終了 let mut f = get_buf(&args, &stdin).unwrap_or_else(|err| { println!("Error: {}", err); process::exit(1); }); // ### 解析部分 ### let mut buf = String::new(); let mut svmon_list: Vec<Svmon> = Vec::new(); loop { match f.read_line(&mut buf) { Ok(ret) => { if ret == 0 { break } }, Err(_) => { break }, }; if Regex::new(r"^\s+size").unwrap().is_match(&buf) { for _ in 0..10 { match f.read_line(&mut buf) { Ok(ret) => { if ret == 0 { break } }, Err(_) => { break }, }; } svmon_list.push(Svmon::from(&buf)); } buf.clear(); } // 読み取ったデータで何かするはず for svmon in &svmon_list { println!("{}", svmon.memory.free) } } fn get_buf<'a>(args: &[String], stdin: &'a io::Stdin) -> Result<Box<BufRead + 'a>, String> { //引数が与えられてなければ、標準入力を返す if args.len() < 2 { return Ok(Box::new(stdin.lock())) } //1つ目の引数をファイル名として扱う let filename = &args[1]; let f = match File::open(filename) { Ok(file) => file, Err(err) => { return Err(String::from(err.description())) }, }; Ok(Box::new(BufReader::new(f))) }
use std::collections::BTreeMap; use super::crt_objects::CrtObjectsFallback; use super::{LinkerFlavor, LldFlavor, PanicStrategy, RelocModel, TargetOptions, TlsModel}; pub fn options() -> TargetOptions { let mut lld_args = Vec::new(); let mut clang_args = Vec::new(); let mut arg = |arg: &'static str| { lld_args.push(arg.into()); clang_args.push(format!("-Wl,{}", arg).into()); }; // By default LLD only gives us one page of stack (64k) which is a // little small. Default to a larger stack closer to other PC platforms // (1MB) and users can always inject their own link-args to override this. arg("-z"); arg("stack-size=1048576"); // By default LLD's memory layout is: // // 1. First, a blank page // 2. Next, all static data // 3. Finally, the main stack (which grows down) // // This has the unfortunate consequence that on stack overflows you // corrupt static data and can cause some exceedingly weird bugs. To // help detect this a little sooner we instead request that the stack is // placed before static data. // // This means that we'll generate slightly larger binaries as references // to static data will take more bytes in the ULEB128 encoding, but // stack overflow will be guaranteed to trap as it underflows instead of // corrupting static data. arg("--stack-first"); // FIXME we probably shouldn't pass this but instead pass an explicit list // of symbols we'll allow to be undefined. We don't currently have a // mechanism of knowing, however, which symbols are intended to be imported // from the environment and which are intended to be imported from other // objects linked elsewhere. This is a coarse approximation but is sure to // hide some bugs and frustrate someone at some point, so we should ideally // work towards a world where we can explicitly list symbols that are // supposed to be imported and have all other symbols generate errors if // they remain undefined. arg("--allow-undefined"); // Rust code should never have warnings, and warnings are often // indicative of bugs, let's prevent them. arg("--fatal-warnings"); // LLD only implements C++-like demangling, which doesn't match our own // mangling scheme. Tell LLD to not demangle anything and leave it up to // us to demangle these symbols later. Currently rustc does not perform // further demangling, but tools like twiggy and wasm-bindgen are intended // to do so. arg("--no-demangle"); let mut pre_link_args = BTreeMap::new(); pre_link_args.insert(LinkerFlavor::Lld(LldFlavor::Wasm), lld_args); pre_link_args.insert(LinkerFlavor::Gcc, clang_args); TargetOptions { is_like_wasm: true, families: vec!["wasm".into()], // we allow dynamic linking, but only cdylibs. Basically we allow a // final library artifact that exports some symbols (a wasm module) but // we don't allow intermediate `dylib` crate types dynamic_linking: true, only_cdylib: true, // relatively self-explanatory! exe_suffix: ".wasm".into(), dll_prefix: "".into(), dll_suffix: ".wasm".into(), eh_frame_header: false, max_atomic_width: Some(64), // Unwinding doesn't work right now, so the whole target unconditionally // defaults to panic=abort. Note that this is guaranteed to change in // the future once unwinding is implemented. Don't rely on this as we're // basically guaranteed to change it once WebAssembly supports // exceptions. panic_strategy: PanicStrategy::Abort, // Wasm doesn't have atomics yet, so tell LLVM that we're in a single // threaded model which will legalize atomics to normal operations. singlethread: true, // no dynamic linking, no need for default visibility! default_hidden_visibility: true, // Symbol visibility takes care of this for the WebAssembly. // Additionally the only known linker, LLD, doesn't support the script // arguments just yet limit_rdylib_exports: false, // we use the LLD shipped with our toolchain by default linker: Some("firefly-lld".into()), lld_flavor: LldFlavor::Wasm, linker_is_gnu: false, pre_link_args, crt_objects_fallback: Some(CrtObjectsFallback::Wasm), // This has no effect in LLVM 8 or prior, but in LLVM 9 and later when // PIC code is implemented this has quite a drastic effect if it stays // at the default, `pic`. In an effort to keep wasm binaries as minimal // as possible we're defaulting to `static` for now, but the hope is // that eventually we can ship a `pic`-compatible standard library which // works with `static` as well (or works with some method of generating // non-relative calls and such later on). relocation_model: RelocModel::Static, // When the atomics feature is activated then these two keys matter, // otherwise they're basically ignored by the standard library. In this // mode, however, the `#[thread_local]` attribute works (i.e. // `has_thread_local`) and we need to get it to work by specifying // `local-exec` as that's all that's implemented in LLVM today for wasm. has_thread_local: true, tls_model: TlsModel::LocalExec, // gdb scripts don't work on wasm blobs emit_debug_gdb_scripts: false, // There's more discussion of this at // https://bugs.llvm.org/show_bug.cgi?id=52442 but the general result is // that this isn't useful for wasm and has tricky issues with // representation, so this is disabled. generate_arange_section: false, ..Default::default() } }
type Card = u32; type Deck = Vec<Card>; enum Players { Player1(Deck), Player2(Deck), } pub fn run() { let mut iter = include_str!("../day22.txt").split("\n\n"); let mut player1 = iter .next() .unwrap() .split("\n") .skip(1) .map(|str| str.parse::<Card>().unwrap()) .collect::<Deck>(); let mut player2 = iter .next() .unwrap() .split("\n") .skip(1) .map(|str| str.parse::<Card>().unwrap()) .collect::<Deck>(); while player1.len() != 0 && player2.len() != 0 { let first_card1 = player1.remove(0); let first_card2 = player2.remove(0); if first_card1 > first_card2 { player1.push(first_card1); player1.push(first_card2); } else { player2.push(first_card2); player2.push(first_card1); } } let n: u32 = player1 .iter() .rev() .enumerate() .map(|(i, &v)| (i + 1) as u32 * v) .sum(); println!("Player 1 {:?}", player1); println!(" {}", n); }
#[allow(dead_code)] pub static ANSI_RESET : &'static str = "\u{1B}[0m"; #[allow(dead_code)] pub static ANSI_YELLOW : &'static str = "\u{1B}[33m"; #[allow(dead_code)] pub static ANSI_GREEN : &'static str = "\u{1B}[32m";
#[cfg(test)] mod test { use std::cell::RefCell; use std::rc::{Rc, Weak}; #[derive(Debug)] struct Node { value: i32, parent: RefCell<Weak<Node>>, children: Vec<Rc<Node>>, } #[test] fn work() { let leaf = Rc::new(Node { value: 3, parent: RefCell::new(Weak::new()), children: vec![], }); println!( "leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf), ); { let branch = Rc::new(Node { value: 5, parent: RefCell::new(Weak::new()), children: vec![Rc::clone(&leaf)], }); //Rc::downgrade 传递 Rc 实例的引用来创建其值的 弱引用(weak reference) //不同于将 Rc<T> 实例的 strong_count 加一, 调用 Rc::downgrade 会将 weak_count 加一 //weak_count 无需计数为 0 就能使 Rc 实例被清理 *leaf.parent.borrow_mut() = Rc::downgrade(&branch); println!( "branch strong = {}, weak = {}", Rc::strong_count(&branch), Rc::weak_count(&branch), ); println!( "leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf), ); } //调用 Weak<T> 实例的 upgrade 方法,这会返回 Option<Rc<T>> // 如果 Rc<T> 值还未被丢弃则结果是 Some,如果 Rc<T> 已经被丢弃则结果是 None println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); println!( "leaf strong = {}, weak = {}", Rc::strong_count(&leaf), Rc::weak_count(&leaf), ); } }
#[doc = "Reader of register PP"] pub type R = crate::R<u32, super::PP>; #[doc = "Flash Size\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u16)] pub enum SIZE_A { #[doc = "511: 1024 KB of Flash"] _1MB = 511, } impl From<SIZE_A> for u16 { #[inline(always)] fn from(variant: SIZE_A) -> Self { variant as _ } } #[doc = "Reader of field `SIZE`"] pub type SIZE_R = crate::R<u16, SIZE_A>; impl SIZE_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u16, SIZE_A> { use crate::Variant::*; match self.bits { 511 => Val(SIZE_A::_1MB), i => Res(i), } } #[doc = "Checks if the value of the field is `_1MB`"] #[inline(always)] pub fn is_1mb(&self) -> bool { *self == SIZE_A::_1MB } } #[doc = "Flash Sector Size of the physical bank\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum MAINSS_A { #[doc = "0: 1 KB"] _1KB = 0, #[doc = "1: 2 KB"] _2KB = 1, #[doc = "2: 4 KB"] _4KB = 2, #[doc = "3: 8 KB"] _8KB = 3, #[doc = "4: 16 KB"] _16KB = 4, } impl From<MAINSS_A> for u8 { #[inline(always)] fn from(variant: MAINSS_A) -> Self { variant as _ } } #[doc = "Reader of field `MAINSS`"] pub type MAINSS_R = crate::R<u8, MAINSS_A>; impl MAINSS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, MAINSS_A> { use crate::Variant::*; match self.bits { 0 => Val(MAINSS_A::_1KB), 1 => Val(MAINSS_A::_2KB), 2 => Val(MAINSS_A::_4KB), 3 => Val(MAINSS_A::_8KB), 4 => Val(MAINSS_A::_16KB), i => Res(i), } } #[doc = "Checks if the value of the field is `_1KB`"] #[inline(always)] pub fn is_1kb(&self) -> bool { *self == MAINSS_A::_1KB } #[doc = "Checks if the value of the field is `_2KB`"] #[inline(always)] pub fn is_2kb(&self) -> bool { *self == MAINSS_A::_2KB } #[doc = "Checks if the value of the field is `_4KB`"] #[inline(always)] pub fn is_4kb(&self) -> bool { *self == MAINSS_A::_4KB } #[doc = "Checks if the value of the field is `_8KB`"] #[inline(always)] pub fn is_8kb(&self) -> bool { *self == MAINSS_A::_8KB } #[doc = "Checks if the value of the field is `_16KB`"] #[inline(always)] pub fn is_16kb(&self) -> bool { *self == MAINSS_A::_16KB } } #[doc = "EEPROM Sector Size of the physical bank\n\nValue on reset: 0"] #[derive(Clone, Copy, Debug, PartialEq)] #[repr(u8)] pub enum EESS_A { #[doc = "0: 1 KB"] _1KB = 0, #[doc = "1: 2 KB"] _2KB = 1, #[doc = "2: 4 KB"] _4KB = 2, #[doc = "3: 8 KB"] _8KB = 3, } impl From<EESS_A> for u8 { #[inline(always)] fn from(variant: EESS_A) -> Self { variant as _ } } #[doc = "Reader of field `EESS`"] pub type EESS_R = crate::R<u8, EESS_A>; impl EESS_R { #[doc = r"Get enumerated values variant"] #[inline(always)] pub fn variant(&self) -> crate::Variant<u8, EESS_A> { use crate::Variant::*; match self.bits { 0 => Val(EESS_A::_1KB), 1 => Val(EESS_A::_2KB), 2 => Val(EESS_A::_4KB), 3 => Val(EESS_A::_8KB), i => Res(i), } } #[doc = "Checks if the value of the field is `_1KB`"] #[inline(always)] pub fn is_1kb(&self) -> bool { *self == EESS_A::_1KB } #[doc = "Checks if the value of the field is `_2KB`"] #[inline(always)] pub fn is_2kb(&self) -> bool { *self == EESS_A::_2KB } #[doc = "Checks if the value of the field is `_4KB`"] #[inline(always)] pub fn is_4kb(&self) -> bool { *self == EESS_A::_4KB } #[doc = "Checks if the value of the field is `_8KB`"] #[inline(always)] pub fn is_8kb(&self) -> bool { *self == EESS_A::_8KB } } #[doc = "Reader of field `DFA`"] pub type DFA_R = crate::R<bool, bool>; #[doc = "Reader of field `FMM`"] pub type FMM_R = crate::R<bool, bool>; #[doc = "Reader of field `PFC`"] pub type PFC_R = crate::R<bool, bool>; impl R { #[doc = "Bits 0:15 - Flash Size"] #[inline(always)] pub fn size(&self) -> SIZE_R { SIZE_R::new((self.bits & 0xffff) as u16) } #[doc = "Bits 16:18 - Flash Sector Size of the physical bank"] #[inline(always)] pub fn mainss(&self) -> MAINSS_R { MAINSS_R::new(((self.bits >> 16) & 0x07) as u8) } #[doc = "Bits 19:22 - EEPROM Sector Size of the physical bank"] #[inline(always)] pub fn eess(&self) -> EESS_R { EESS_R::new(((self.bits >> 19) & 0x0f) as u8) } #[doc = "Bit 28 - DMA Flash Access"] #[inline(always)] pub fn dfa(&self) -> DFA_R { DFA_R::new(((self.bits >> 28) & 0x01) != 0) } #[doc = "Bit 29 - Flash Mirror Mode"] #[inline(always)] pub fn fmm(&self) -> FMM_R { FMM_R::new(((self.bits >> 29) & 0x01) != 0) } #[doc = "Bit 30 - Prefetch Buffer Mode"] #[inline(always)] pub fn pfc(&self) -> PFC_R { PFC_R::new(((self.bits >> 30) & 0x01) != 0) } }
#[cfg(not(feature = "const_generics"))] use crate::Array; use crate::SmallVec; use core::ptr; macro_rules! create_with_parts { ( <$($({$s_impl_ty_prefix:ident})? $s_impl_ty:ident$(: $s_impl_ty_bound:ident)?),*>, <$s_decl_ty:ident$(, {$s_decl_const_ty:ident})?>, $array_item:ty ) => { /// An iterator that consumes a `SmallVec` and yields its items by value. /// /// Returned from [`SmallVec::into_iter`][1]. /// /// [1]: struct.SmallVec.html#method.into_iter pub struct IntoIter<$($($s_impl_ty_prefix)? $s_impl_ty$(: $s_impl_ty_bound)?),*> { pub(crate) data: SmallVec<$s_decl_ty$(, {$s_decl_const_ty})?>, pub(crate) current: usize, pub(crate) end: usize, } impl<$($($s_impl_ty_prefix)? $s_impl_ty$(: $s_impl_ty_bound)?),*> Drop for IntoIter<$s_decl_ty$(, {$s_decl_const_ty})?> { fn drop(&mut self) { for _ in self {} } } impl<$($($s_impl_ty_prefix)? $s_impl_ty$(: $s_impl_ty_bound)?),*> Iterator for IntoIter<$s_decl_ty$(, {$s_decl_const_ty})?> { type Item = $array_item; #[inline] fn next(&mut self) -> Option<$array_item> { if self.current == self.end { None } else { unsafe { let current = self.current as isize; self.current += 1; Some(ptr::read(self.data.as_ptr().offset(current))) } } } #[inline] fn size_hint(&self) -> (usize, Option<usize>) { let size = self.end - self.current; (size, Some(size)) } } impl<$($($s_impl_ty_prefix)? $s_impl_ty$(: $s_impl_ty_bound)?),*> DoubleEndedIterator for IntoIter<$s_decl_ty$(, {$s_decl_const_ty})?> { #[inline] fn next_back(&mut self) -> Option<$array_item> { if self.current == self.end { None } else { unsafe { self.end -= 1; Some(ptr::read(self.data.as_ptr().add(self.end))) } } } } impl<$($($s_impl_ty_prefix)? $s_impl_ty$(: $s_impl_ty_bound)?),*> ExactSizeIterator for IntoIter<$s_decl_ty$(, {$s_decl_const_ty})?> {} } } #[cfg(feature = "const_generics")] create_with_parts!(<T, {const} N: usize>, <T, {N}>, T); #[cfg(not(feature = "const_generics"))] create_with_parts!(<A: Array>, <A>, A::Item);
// Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved // use gltf::{mesh::Primitive, Buffer}; use spectral::prelude::*; use crate::{Fingerprint, Result}; /// Computes a `Fingerprint` from a `Primitive`. /// /// A fingerprint needs to be independent of triangle order and vertex order, and obviously it /// should be non-trivially different from the fingerprint of some other `Primitive`. This isn't /// as obvious as it seems: for example, if we simply took the geometric average of positions, /// all shapes that are symmetric around origin, regardless of scale, would be identical. /// /// We look at vertex positions and vertex colours, and simply add them up, with an added /// skew to the Y and Z dimensions, to break symmetries. /// /// More complexity could be added here, if warranted. pub fn build_fingerprint(primitive: &Primitive, blob: &[u8]) -> Result<Fingerprint> { let buf_to_blob = |buf: Buffer| { assert_that(&buf.index()).is_equal_to(0); if blob.is_empty() { None } else { Some(blob) } }; let reader = primitive.reader(buf_to_blob); let positions: Vec<[f32; 3]> = reader .read_positions() .ok_or(format!("Primitive lacks position data!"))? .collect(); let indices: Vec<u32> = reader .read_indices() .ok_or(format!("Primitive lacks indices!"))? .into_u32() .collect(); let count = indices.len() as f64; let mut cumulative_fingerprint = { let mut print: f64 = 0.0; for &ix in &indices { print += vec3_to_print(positions[ix as usize]) / count; } print }; if let Some(colors) = reader.read_colors(0) { let colors: Vec<[f32; 4]> = colors.into_rgba_f32().collect(); cumulative_fingerprint += { let mut print: f64 = 0.0; for &ix in &indices { print += vec4_to_print(colors[ix as usize]) / count; } print } } Ok(cumulative_fingerprint) } fn vec3_to_print(vec: [f32; 3]) -> f64 { // arbitrary symmetry-breaking shear (vec[0] + 1.3 * vec[1] + 1.7 * vec[2]) as f64 } fn vec4_to_print(vec: [f32; 4]) -> f64 { // arbitrary symmetry-breaking shear (vec[0] + 1.1 * vec[1] + 1.3 * vec[2] + 1.5 * vec[3]) as f64 }
// Menggunakan while untuk meng-iterasi data vector // fn main() { let num = vec![1,2,3,4,5]; let mut iter = (&num).into_iter(); while let Some(v) = iter.next() { println!("{}", v); } }
mod error; mod play_flag; use gstreamer::prelude::*; use gstreamer::*; use std::io::Write; use std::iter::Iterator; use std::sync::atomic::{AtomicI32, Ordering}; use std::sync::Arc; const GRAPH_LENGTH: usize = 78; fn got_location(prop_object: &Object) { let location: String = prop_object.property("temp-location"); println!("Temporary file: {}", location); /* Uncomment this line to keep the temporary file after the program exits */ // prop_object.set_property("temp-remove", false); } fn cb_message( pipeline: &Element, main_loop: &glib::MainLoop, msg: &Message, is_live: bool, buffering_level: &AtomicI32, ) { match msg.view() { MessageView::Error(err) => { println!("Error: {}", err.error()); let _ = pipeline.set_state(State::Ready); main_loop.quit(); } MessageView::Eos(_) => { /* end-of-stream */ let _ = pipeline.set_state(State::Ready); main_loop.quit(); } MessageView::Buffering(msg) => { /* If the stream is live, we do not care about buffering. */ if is_live { return; } let percent = msg.percent(); buffering_level.store(percent, Ordering::SeqCst); /* Wait until buffering is complete before start/resume playing */ if percent < 100 { let _ = pipeline.set_state(State::Paused); } else { let _ = pipeline.set_state(State::Playing); } } MessageView::ClockLost(_) => { /* Get a new clock */ let _ = pipeline.set_state(State::Paused); let _ = pipeline.set_state(State::Playing); } _ => { /* Unhandled message */ } } } fn refresh_ui(pipeline: &Element, buffering_level: i32) { let mut query = query::Buffering::new(Format::Percent); let result = pipeline.query(&mut query); if result { let mut graph = [' '; GRAPH_LENGTH]; for (start, stop) in query.ranges() { let start = start.value() as usize; let stop = stop.value() as usize; let denominator = stop - start; let start = start * GRAPH_LENGTH / denominator; let stop = stop * GRAPH_LENGTH / denominator; for char in graph.iter_mut().take(stop).skip(start) { *char = '-'; } } if let Some(position) = pipeline.query_position::<ClockTime>() { if let Some(duration) = pipeline.query_duration::<ClockTime>() { let i = (GRAPH_LENGTH as f64 * position.nseconds() as f64 / (duration.nseconds() + 1) as f64) as usize; graph[i] = if buffering_level < 100 { 'X' } else { '>' }; } } print!("[{}]", graph.iter().collect::<String>()); if buffering_level < 100 { print!(" Buffering: {:>3}%", buffering_level); } else { print!(" "); } print!("\r"); let _ = std::io::stdout().flush(); } } fn main() -> Result<(), error::Error> { /* Initialize GStreamer */ gstreamer::init().unwrap(); /* Initialize our data structure */ let buffering_level = Arc::new(AtomicI32::new(100)); /* Build the pipeline */ let pipeline = parse_launch("playbin uri=https://www.freedesktop.org/software/gstreamer-sdk/data/media/sintel_trailer-480p.webm").unwrap(); let bus = pipeline.bus().unwrap(); /* Start playing */ let is_live = match pipeline.set_state(State::Playing) { Err(_) => { eprintln!("Unable to set the pipeline to the playing state."); panic!(); } Ok(StateChangeSuccess::NoPreroll) => true, _ => false, }; let main_loop = glib::MainLoop::new(None, false); bus.add_signal_watch(); let pipeline_for_msg = pipeline.clone(); let main_loop_for_msg = main_loop.clone(); let buffering_level_for_msg = Arc::clone(&buffering_level); bus.connect_message(None, move |_, msg| { cb_message( &pipeline_for_msg, &main_loop_for_msg, msg, is_live, &buffering_level_for_msg, ); }); pipeline.connect("deep-notify::temp-location", false, |args| { let prop_object = args[1].get::<Object>().unwrap(); got_location(&prop_object); None }); /* Register a function that GLib will call every second */ let pipeline_for_ui = pipeline.clone(); glib::timeout_add_seconds(1, move || { refresh_ui(&pipeline_for_ui, buffering_level.load(Ordering::SeqCst)); Continue(true) }); main_loop.run(); /* Free resources */ let _ = pipeline.set_state(State::Null); println!(); Ok(()) }
use std::fmt; #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] pub struct PlayerControlled { pub id: PlayerId, } #[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)] pub struct PlayerId(pub u32); impl fmt::Display for PlayerControlled { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "PlayerControlled.id: {}", self.id) } } impl fmt::Display for PlayerId { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { write!(f, "{}", self.0) } }
use super::super::{Model, Var, LtXY, GtXY, LeXY, GeXY, LtXYC, GtXYC, LeXYC, GeXYC, LtXC, GtXC, LeXC, GeXC}; use super::{LtXYCx, LtXYCy}; #[test] fn propagator_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 255, "x"); let y = Var::new(m.clone(), -2, 255, "y"); LtXYCx::new(m.clone(), x.clone(), y.clone(), -2); assert_eq!(x.max(), 252); LtXYCy::new(m.clone(), x.clone(), y.clone(), -2); assert_eq!(y.min(), 1); } #[test] fn ltxy_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 255, "x"); let y = Var::new(m.clone(), -2, 255, "y"); LtXY::new(m.clone(), x.clone(), y.clone()); assert_eq!((x.max(), y.min()), (254, -1)); } #[test] fn gtxy_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 252, "x"); let y = Var::new(m.clone(), 2, 255, "y"); GtXY::new(m.clone(), x.clone(), y.clone()); assert_eq!((x.min(), y.max()), (3, 251)); } #[test] fn lexy_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 255, "x"); let y = Var::new(m.clone(), -2, 255, "y"); LeXY::new(m.clone(), x.clone(), y.clone()); assert_eq!((x.max(), y.min()), (255, -2)); } #[test] fn gexy_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 252, "x"); let y = Var::new(m.clone(), 2, 255, "y"); GeXY::new(m.clone(), x.clone(), y.clone()); assert_eq!((x.min(), y.max()), (2, 252)); } #[test] fn ltxyc_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 255, "x"); let y = Var::new(m.clone(), -2, 255, "y"); LtXYC::new(m.clone(), x.clone(), y.clone(), -1); assert_eq!((x.max(), y.min()), (253, 0)); } #[test] fn gtxyc_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 252, "x"); let y = Var::new(m.clone(), 2, 255, "y"); GtXYC::new(m.clone(), x.clone(), y.clone(), 1); assert_eq!((x.min(), y.max()), (4, 250)); } #[test] fn lexyc_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 255, "x"); let y = Var::new(m.clone(), -2, 255, "y"); LeXYC::new(m.clone(), x.clone(), y.clone(), 1); assert_eq!((x.max(), y.min()), (255, -2)); } #[test] fn gexyc_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 252, "x"); let y = Var::new(m.clone(), 2, 255, "y"); GeXYC::new(m.clone(), x.clone(), y.clone(), 3); assert_eq!((x.min(), y.max()), (5, 249)); } #[test] fn ltxc_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 252, "x"); LtXC::new(m.clone(), x.clone(), 3); assert_eq!((x.min(), x.max()), (-2, 2)); } #[test] fn lexc_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 252, "x"); LeXC::new(m.clone(), x.clone(), 3); assert_eq!((x.min(), x.max()), (-2, 3)); } #[test] fn gtxc_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 252, "x"); GtXC::new(m.clone(), x.clone(), 3); assert_eq!((x.min(), x.max()), (4, 252)); } #[test] fn gexc_does_propagate() { let m = Model::new(); let x = Var::new(m.clone(), -2, 252, "x"); GeXC::new(m.clone(), x.clone(), 3); assert_eq!((x.min(), x.max()), (3, 252)); }
// Copyright 2019 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. use failure::{bail, err_msg, Error, ResultExt}; use fidl_fuchsia_ui_text as txt; use fuchsia_async::TimeoutExt; use futures::prelude::*; use std::collections::HashSet; use std::convert::TryInto; use text::text_field_state::TextFieldState; pub struct TextFieldWrapper { proxy: txt::TextFieldProxy, last_state: TextFieldState, defunct_point_ids: HashSet<u64>, current_point_ids: HashSet<u64>, } /// This wraps the TextFieldProxy, and provides convenient features like storing the last state /// update, various validation functions for tests. It also a great place to add checks that work /// across all tests; for instance, right now, it validates that all TextPoints in all function /// calls are not reused across revisions, and that any distance or contents check works even if /// the range is inverted. impl TextFieldWrapper { /// Creates a new TextFieldWrapper from a proxy. This is a async function and can fail, since it /// waits for the initial state update to come from the TextField. pub async fn new(proxy: txt::TextFieldProxy) -> Result<TextFieldWrapper, Error> { let state = get_update(&proxy).await.context("Receiving initial state.")?; Ok(TextFieldWrapper { proxy, current_point_ids: all_point_ids_for_state(&state), defunct_point_ids: HashSet::new(), last_state: state, }) } /// Returns a cloned version of the latest state from the server. To update this, either use one /// of the editing methods on the TextFieldWrapper, or if making calls on the proxy directly, /// call `text_field_wrapper.wait_for_update().await` after you expect a new state update from /// the TextField. pub fn state(&self) -> TextFieldState { self.last_state.clone() } /// Waits for an on_update event from the TextFieldProxy, and updates the last state tracked /// by TextFieldWrapper. Edit functions on TextFieldWrapper itself already call this; only /// use it if you're doing something with the TextFieldProxy directly. This also validates /// that document, selection, and revision are all set on last_state, so these fields can be /// unwrapped in other parts of the code. pub async fn wait_for_update(&mut self) -> Result<(), Error> { self.defunct_point_ids = &self.defunct_point_ids | &all_point_ids_for_state(&self.last_state); self.last_state = match get_update(&self.proxy).await { Ok(v) => v, Err(e) => bail!(format!("{}", e)), }; self.current_point_ids = all_point_ids_for_state(&self.last_state); self.validate_point_ids() } /// An internal function that validates the current_point_ids and defunct_point_ids are /// disjoint sets. If they aren't disjoint, then the TextField incorrectly reused a /// point ID between two revisions. fn validate_point_ids(&mut self) -> Result<(), Error> { let in_both_sets = &self.current_point_ids & &self.defunct_point_ids; if in_both_sets.len() != 0 { let as_strings: Vec<String> = in_both_sets.into_iter().map(|i| format!("{}", i)).collect(); bail!(format!( "Expected TextPoint ids to not be reused between revisions: {}", as_strings.join(", ") )) } Ok(()) } /// Returns a handle to the raw TextFieldProxy, useful for sending it weird unexpected /// input and making sure it responds correctly. pub fn proxy(&self) -> &txt::TextFieldProxy { &self.proxy } /// Inserts text as though the user just typed it, at the caret, replacing any selected text. /// Also waits for an on_update state update event before returning. pub async fn simple_insert(&mut self, contents: &'static str) -> Result<(), Error> { let rev = self.last_state.revision; self.proxy.begin_edit(rev)?; self.proxy.replace(&mut self.last_state.selection.range, contents)?; if self.proxy.commit_edit().await? != txt::Error::Ok { bail!("Expected commit_edit to succeed"); } self.wait_for_update().await?; Ok(()) } /// Returns a new TextPoint offset from the specified one. Use this function instead of /// `text_field_wrapper.proxy().point_offset()` when possible, since it also double checks /// any points returned aren't used across revisions. You may need the proxy's /// point_offset method when giving weird data to the proxy, though, like incorrect /// revision numbers. pub async fn point_offset<'a>( &'a mut self, mut point: &'a mut txt::Position, offset: i64, ) -> Result<txt::Position, Error> { let (new_point, err) = self.proxy.position_offset(&mut point, offset, self.last_state.revision).await?; if err != txt::Error::Ok { bail!(format!("Expected point_offset request to succeed, returned {:?} instead", err)); } self.current_point_ids.insert(new_point.id); if let Err(e) = self.validate_point_ids() { return Err(e); } Ok(new_point) } /// A convenience function that returns the string contents of a range. pub async fn contents<'a>( &'a mut self, range: &'a mut txt::Range, ) -> Result<(String, txt::Position), Error> { let (contents, actual_start, err) = self.proxy.contents(range, self.last_state.revision).await?; if err != txt::Error::Ok { bail!(format!("Expected contents request to succeed, returned {:?} instead", err)); } Ok((contents, actual_start)) } /// A convenience function that returns the distance of a range. pub async fn distance<'a>(&'a mut self, range: &'a mut txt::Range) -> Result<i64, Error> { let (length, err) = self.proxy.distance(range, self.last_state.revision).await?; if err != txt::Error::Ok { bail!(format!("Expected length request to succeed, returned {:?} instead", err)); } Ok(length) } /// A convenience function that validates that a distance call returns an expected value. Also /// double checks that inverting the range correctly negates the returned distance. pub async fn validate_distance<'a>( &'a mut self, range: &'a txt::Range, expected_result: i64, ) -> Result<(), Error> { // try forwards let mut new_range = txt::Range { start: txt::Position { id: range.start.id }, end: txt::Position { id: range.end.id }, }; let length = self.distance(&mut new_range).await?; if length != expected_result { bail!(format!( "Expected distance request to return {:?}, instead got {:?}", expected_result, length )) }; // try backwards let inverted_expected_result = -expected_result; let mut new_range = txt::Range { start: txt::Position { id: range.end.id }, end: txt::Position { id: range.start.id }, }; let length = self.distance(&mut new_range).await?; if length != inverted_expected_result { bail!(format!( "Expected distance request to return {:?}, instead got {:?}", inverted_expected_result, length )) }; Ok(()) } /// A convenience function that validates that a contents call returns an expected value. Also /// double checks that inverting the range correctly returns an identical string. pub async fn validate_contents<'a>( &'a mut self, range: &'a txt::Range, expected_result: &'a str, ) -> Result<(), Error> { // try forwards let mut new_range = txt::Range { start: txt::Position { id: range.start.id }, end: txt::Position { id: range.end.id }, }; let (contents, _true_start_point) = self.contents(&mut new_range).await?; if contents != expected_result { bail!(format!( "Expected contents request to return {:?}, instead got {:?}", expected_result, contents )) }; // try backwards let mut new_range = txt::Range { start: txt::Position { id: range.end.id }, end: txt::Position { id: range.start.id }, }; let (contents, _true_start_point) = self.contents(&mut new_range).await?; if contents != expected_result { bail!(format!( "Expected contents request to return {:?}, instead got {:?}", expected_result, contents )) }; Ok(()) } } async fn get_update(text_field: &txt::TextFieldProxy) -> Result<TextFieldState, Error> { let mut stream = text_field.take_event_stream(); let msg_future = stream .try_next() .map_err(|e| err_msg(format!("{}", e))) .on_timeout(*crate::TEST_TIMEOUT, || Err(err_msg("Waiting for on_update event timed out"))); let msg = msg_future.await?.ok_or(err_msg("TextMgr event stream unexpectedly closed"))?; match msg { txt::TextFieldEvent::OnUpdate { state, .. } => Ok(state.try_into()?), } } fn all_point_ids_for_state(state: &TextFieldState) -> HashSet<u64> { let mut point_ids = HashSet::new(); let mut point_ids_for_range = |range: &txt::Range| { point_ids.insert(range.start.id); point_ids.insert(range.end.id); }; point_ids_for_range(&state.selection.range); state.composition.as_ref().map(|range| point_ids_for_range(&*range)); state.composition_highlight.as_ref().map(|range| point_ids_for_range(&*range)); state.dead_key_highlight.as_ref().map(|range| point_ids_for_range(&*range)); point_ids_for_range(&state.document); point_ids } #[cfg(test)] mod test { use super::*; fn default_range(n: u64) -> txt::Range { txt::Range { start: txt::Position { id: n }, end: txt::Position { id: n + 1 } } } fn default_state(n: u64) -> TextFieldState { TextFieldState { document: default_range(n), selection: txt::Selection { range: default_range(n + 2), anchor: txt::SelectionAnchor::AnchoredAtStart, affinity: txt::Affinity::Upstream, }, composition: None, composition_highlight: None, dead_key_highlight: None, revision: n + 4, } } #[fuchsia_async::run_singlethreaded] #[test] async fn test_wrapper_insert() { let (proxy, server_end) = fidl::endpoints::create_proxy::<txt::TextFieldMarker>() .expect("Should have created proxy"); let (mut stream, control_handle) = server_end .into_stream_and_control_handle() .expect("Should have created stream and control handle"); control_handle.send_on_update(default_state(0).into()).expect("Should have sent update"); fuchsia_async::spawn(async { let mut wrapper = TextFieldWrapper::new(proxy).await.expect("Should have created text field wrapper"); wrapper.simple_insert("meow!").await.expect("Should have inserted successfully"); }); let (revision, _ch) = stream .try_next() .await .expect("Waiting for message failed") .expect("Should have sent message") .into_begin_edit() .expect("Expected BeginEdit"); assert_eq!(revision, 4); let (_range, new_text, _ch) = stream .try_next() .await .expect("Waiting for message failed") .expect("Should have sent message") .into_replace() .expect("Expected Replace"); assert_eq!(new_text, "meow!"); let _responder = stream .try_next() .await .expect("Waiting for message failed") .expect("Should have sent message") .into_commit_edit() .expect("Expected CommitEdit"); } #[fuchsia_async::run_singlethreaded] #[test] async fn test_duplicate_points_cause_error() { let (proxy, server_end) = fidl::endpoints::create_proxy::<txt::TextFieldMarker>() .expect("Should have created proxy"); let (_stream, control_handle) = server_end .into_stream_and_control_handle() .expect("Should have created stream and control handle"); control_handle.send_on_update(default_state(0).into()).expect("Should have sent update"); let mut wrapper = TextFieldWrapper::new(proxy).await.expect("Should have created text field wrapper"); // send a valid update and make sure it works as expected let mut state = default_state(10); control_handle.send_on_update(state.clone().into()).expect("Should have sent update"); let res = wrapper.wait_for_update().await; assert!(res.is_ok()); assert_eq!(wrapper.state().document.start.id, 10); // send an update with the same points but an incremented revision state.revision += 1; control_handle.send_on_update(state.into()).expect("Should have sent update"); let res = wrapper.wait_for_update().await; assert!(res.is_err()); // should fail since some points were reused } }
// Copyright (c) The Starcoin Core Contributors // SPDX-License-Identifier: Apache-2.0 //! Auto derive CryptoHash implement. extern crate proc_macro; use proc_macro::TokenStream; use quote::quote; use syn::DeriveInput; #[proc_macro_derive(CryptoHash)] pub fn crypto_hash(input: TokenStream) -> TokenStream { let ast: DeriveInput = syn::parse(input).expect("Incorrect macro input"); let name = &ast.ident; let out = quote!( impl starcoin_crypto::hash::CryptoHash for #name { fn crypto_hash(&self) -> starcoin_crypto::HashValue { starcoin_crypto::HashValue::from_sha3_256( scs::to_bytes(self) .expect("Serialization should work.") .as_slice() ) } } ); out.into() }
fn main() { let c: f32 = convert_f_to_c(37.0); println!("The temp in C is {}", c); let n = 9; let fibs: i32 = fib(n); println!("The {}th term is {}", n, fibs); xmas(); } fn convert_f_to_c(f: f32) -> f32 { let c: f32 = (f - 32.0) * (5.0 / 9.0); c } fn fib(n: i32) -> i32 { let mut a = 0; let mut b = 1; let mut c = 1; if (n == 0) { return a; } for _val in (1..n) { c = a + b; a = b; b = c; } return b; } fn xmas() { let a = [ "A partridge in a pear tree", "Two turtle doves", "Three french hens", ]; let v = ["first", "second", "third"]; for (i, item) in a.iter().enumerate() { if i == 0 { println!( "On the {} day of Christmas my true love sent to me {}", v[i], item ); } else { let sliced_a = &a[0..i + 1]; let mystr = sliced_a.join(", "); println!( "On the {} day of Christmas my true love sent to me {}", v[i], mystr ); } } }
use curses; use {Error, Event, Key}; use super::Window; pub struct Input<'a> { window: &'a mut Window<'a>, } impl<'a> Input<'a> { #[inline] pub unsafe fn wrap<'b>(window: &'b mut Window<'b>) -> Input<'b> { Input { window: window } } } impl<'a> Input<'a> { #[inline] pub fn event(&mut self) -> Option<Event> { unsafe { let mut character = 0; let value = some!(Error::check(curses::wget_wch(self.window.as_mut_ptr(), &mut character))); Event::fetch(value, character) } } #[inline] pub fn character(&mut self) -> Option<char> { match self.event() { Some(Event::Key(Key::Char(ch))) => Some(ch), Some(..) => self.character(), None => None } } }
//! Internals for the `@michael-f-bryan/gcode` package. Not intended for public //! use. mod callbacks; mod parser; mod simple_wrappers; pub use callbacks::JavaScriptCallbacks; pub use parser::Parser; pub use simple_wrappers::{Comment, GCode, Line, Span, Word}; use gcode::Mnemonic; pub(crate) fn mnemonic_letter(m: Mnemonic) -> char { match m { Mnemonic::General => 'G', Mnemonic::Miscellaneous => 'M', Mnemonic::ProgramNumber => 'O', Mnemonic::ToolChange => 'T', } }
struct Data { value: i32 } #[no_mangle] extern fn new_data(value: i32) -> *mut Data { let d = Box::new(Data { value }); Box::into_raw(d) } #[no_mangle] extern fn drop_data(ptr: *mut Data) { unsafe { drop(Box::from_raw(ptr)); } } #[no_mangle] extern fn take_value(ptr: *mut Data) -> i32 { unsafe { let d = Box::from_raw(ptr); let v = d.value; Box::into_raw(d); v } }
use std::net::SocketAddr; use std::sync::Arc; use failure::Error; use tokio; use tokio::prelude::*; use trust_dns_resolver::AsyncResolver; use crate::relay::forwarding::handle_incoming_tcp; use tokio::net::TcpStream; use asocks5::socks::Address; use asocks5::socks::SocksError; use asocks5::socks::TcpRequestHeader; use crate::relay::TcpRouter; use asocks5::listen::handle_socks_handshake; use asocks5::Command; pub fn listen_socks(addr: &SocketAddr, resolver: Arc<AsyncResolver>, router: Arc<TcpRouter>)->Result<(), Error >{ let l = tokio::net::TcpListener::bind(addr)?; let mut l = l.incoming(); tokio::spawn_async(async move{ while let Some(s) = await!(l.next()) { match s { Ok(s) => { let r1 = resolver.clone(); let rt1 = router.clone(); tokio::spawn_async(async move { let _r = await!(handle_client(s, r1, rt1)).map_err(|e| { error!("error handling client {}", e); }); }); } Err(e) => { error!("error getting next socks client {}", e); } } } }); Ok(()) } async fn handle_client( s: TcpStream, res: Arc<AsyncResolver>, rt: Arc<TcpRouter>, ) -> Result<(), Error> { let (s, req) = await!(handle_socks_handshake(s))?; let a = await!(read_address(req, res.clone()))?; await!(handle_incoming_tcp(s, a, rt)) } async fn read_address(head: TcpRequestHeader, resolver: Arc<AsyncResolver>) -> Result<SocketAddr, Error> { let c = head.command; if c != Command::TcpConnect { return Err(SocksError::CommandUnSupport { cmd: c as u8}.into()); } match head.address { Address::SocketAddress(a) => return Ok(a), Address::DomainNameAddress(domain, port) => { let lookup = await!(resolver.lookup_ip(&*domain)).map_err(|e| { format_err!("Error resolving {}: {}", domain, e) })?; let ip = lookup.iter().next() .ok_or_else(||format_err!("No address found for domain {}", domain))?; Ok(SocketAddr::new(ip, port)) } } }
use crate::store::Store; use crate::structures::Structure; use retriever::traits::record::Record; use retriever::types::entry::Entry; use retriever::types::id::Id; use retriever::types::storage::Storage; use serde::{Deserialize, Serialize}; use std::marker::PhantomData; #[derive(Debug, Deserialize, Serialize, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)] pub struct ForeignKey<D: Structure> { chunk_keys: D::ChunkKeys, item_keys: D::ItemKeys, } impl<D: Structure> From<(D::ChunkKeys, D::ItemKeys)> for ForeignKey<D> { fn from((chunk_keys, item_keys): (D::ChunkKeys, D::ItemKeys)) -> Self { Self { chunk_keys, item_keys, } } } impl<D: Structure> From<ForeignKey<D>> for (D::ChunkKeys, D::ItemKeys) { fn from(key: ForeignKey<D>) -> Self { (key.chunk_keys, key.item_keys) } } impl<D: Structure> From<ForeignKey<D>> for Id<D::ChunkKeys, D::ItemKeys> { fn from(key: ForeignKey<D>) -> Self { Id::new(key.chunk_keys, key.item_keys) } } impl<D: 'static + Structure + Record<<D as Structure>::ChunkKeys, <D as Structure>::ItemKeys>> ForeignKey<D> { fn follow<'a, R>( &self, store: &'a mut Store, ) -> Entry< 'a, Id<<D as Structure>::ChunkKeys, <D as Structure>::ItemKeys>, <D as Structure>::ChunkKeys, <D as Structure>::ItemKeys, D, > where R: retriever::traits::record::Record< <D as Structure>::ChunkKeys, <D as Structure>::ItemKeys, >, { let dataset = store .datasets .get_mut::<Storage<<D as Structure>::ChunkKeys, <D as Structure>::ItemKeys, D>>() .expect("Expected known dataset"); let record: Id<D::ChunkKeys, D::ItemKeys> = self.clone().into(); let datum = dataset.entry(record); datum } } impl<D: Structure> ForeignKey<D> {}
use iron::prelude::*; use iron::status; use router::*; use bodyparser; use persistent::{Read, Write}; use hyper::header::*; use hyper::mime::*; use dal; use std::ops::Deref; use chrono::prelude::*; use serde_json; use std::str; use uuid; use bcrypt; use slog; use std; use multipart::server::Multipart; use multipart::server::MultipartData; //use multipart::server::{Multipart, Entries, SaveResult, SavedFile}; use server::loggerenclave::LoggerEnclave; pub mod authenticate; pub mod products; #[derive(Serialize, Deserialize, Debug)] pub struct ResponseData<T> { pub success: bool, pub data: T, pub message: String, } pub fn index_handler(req: &mut Request) -> IronResult<Response> { let logger: slog::Logger = get_logger!(req); info!(logger, "inside handler"); let respdata = "Hello"; Ok(Response::with((status::Ok, respdata))) } pub fn index_handler2(_: &mut Request) -> IronResult<Response> { let respdata = r#"{"key","value"}"#.as_bytes(); let mut resp = Response::with((status::Ok, respdata)); resp.headers = Headers::new(); resp.headers.set(ContentType(Mime( TopLevel::Application, SubLevel::Json, vec![(Attr::Charset, Value::Utf8)], ))); Ok(resp) } pub fn index_handler3(req: &mut Request) -> IronResult<Response> { let mut resp = Response::with(status::NotFound); let logger: slog::Logger = get_logger!(req); info!(logger, "Request recvd : {:?}", req); info!(logger, "Url: {:?}", req.url.path()); if let Some(params) = req.extensions.get::<Router>() { info!(logger, "Params {:?}", params["name"]); if let Some(name_param) = params.find("name") { info!(logger, "Found param name : {}", name_param); resp = Response::with((status::Ok, "text data")); resp.headers = Headers::new(); resp.headers.set(ContentType( Mime(TopLevel::Text, SubLevel::Plain, vec![]), )); } } Ok(resp) } pub fn get_db_time(req: &mut Request) -> IronResult<Response> { #[derive(Serialize, Deserialize, Debug)] pub struct DbData { pub id: i32, pub name: String, pub timestamp: i64, } let logger: slog::Logger = get_logger!(req); info!(logger, "in get_db_time"); let mut resp = Response::with(status::NotFound); let arcpool = match req.get::<Write<dal::DalPostgresPool>>() { Ok(x) => x, Err(e) => { error!( logger, "Unable to get connection pool, error message [{}]", e ); return Ok(resp); } }; let lockedpool = match arcpool.lock() { Ok(x) => x, Err(e) => { error!( logger, "Unable to get lock on connection pool, error message [{}]", e ); return Ok(resp); } }; let pool = lockedpool.deref(); let conn = match pool.rw_pool.get() { Ok(x) => x, Err(e) => { error!( logger, "Unable to get connection from pool, erro message [{}]", e ); return Ok(resp); } }; let stmt = match conn.prepare("SELECT 1 as id, 'someone' as name, now() as timestamp") { Ok(x) => x, Err(e) => { error!(logger, "Unable to prepare statement, error message [{}]", e); return Ok(resp); } }; let rows = match stmt.query(&[]) { Ok(x) => x, Err(e) => { error!(logger, "Unable to execute query, error message [{}]", e); return Ok(resp); } }; for row in rows.iter() { let _id: i32 = row.get("id"); let _name: String = row.get("name"); /*// time crate let _timestamp: Timespec = row.get("timestamp"); let utc_tm: Tm = at_utc(_timestamp); let local_tm: Tm = utc_tm.to_local(); info!( logger, "row [{}, {}, utc {}, local {}] ", _id, _name, utc_tm.asctime(), local_tm.asctime() ); */ // chrono crate let _datetime_utc: DateTime<Utc> = row.get("timestamp"); let _datetime_local: DateTime<Local> = row.get("timestamp"); info!(logger, "row [{}, {}, utc {}, local {}] ", _id, _name, _datetime_utc.to_rfc2822(), _datetime_local.to_rfc2822(), ); let data: DbData = DbData { id: _id, name: _name, //timestamp: _timestamp.sec, // time crate timestamp: _datetime_utc.timestamp(), // chrono crate }; if let Ok(json_resp) = serde_json::to_string(&data) { resp = Response::with((status::Ok, json_resp)); resp.headers.set(ContentType( Mime(TopLevel::Application, SubLevel::Json, vec![]), )); }; break; // we only need first element } Ok(resp) } pub fn authenticate(req: &mut Request) -> IronResult<Response> { let logger: slog::Logger = get_logger!(req); info!(logger, "in authenticate"); let mut resp = Response::with(status::NotFound); //let ref rhead = req.headers; //info!(logger, "rhead {}", rhead); //let ref rbody = req.body; //info!(logger, "rbody {}", rbody); let mut resp_content_type = ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![])); if req.headers.has::<ContentType>() { if let Some(ctype) = req.headers.get_raw("content-type") { if let Ok(strx) = str::from_utf8(&ctype[0]) { info!(logger, "content type received is {}", strx); if strx == "application/json" { resp_content_type = ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![])); } else if strx == "application/cbor" { resp_content_type = ContentType(Mime( TopLevel::Application, SubLevel::Ext("cbor".to_string()), vec![], )); } else if strx == "application/msgpack" { resp_content_type = ContentType(Mime( TopLevel::Application, SubLevel::Ext("msgpack".to_string()), vec![], )); } else if strx == "applcaiton/protobuf" { resp_content_type = ContentType(Mime( TopLevel::Application, SubLevel::Ext("protobuf".to_string()), vec![], )); } else { // json } } } else { resp_content_type = ContentType(Mime(TopLevel::Application, SubLevel::Json, vec![])); } } let rbody = req.get::<bodyparser::Json>(); info!(logger, "rbody {:?}", rbody); #[derive(Serialize, Deserialize, Clone, Debug)] struct AuthUser { pub username: String, pub password: String, }; let authuser = match req.get::<bodyparser::Struct<AuthUser>>() { Ok(Some(x)) => x, _ => { error!(logger, "Unable to get authuser from request"); return Ok(resp); } }; info!(logger, "authuser = {:?}", authuser); //let query = format!("select * from user where userid={}", authuser.username); let query = "select * from customer_local_auth where local_id=$1"; info!(logger, "query [{}]", query); let arcpool = match req.get::<Write<dal::DalPostgresPool>>() { Ok(x) => x, Err(e) => { error!( logger, "Unable to get connection pool, error message [{}]", e ); return Ok(resp); } }; let locked_pool = match arcpool.lock() { Ok(x) => x, Err(e) => { error!( logger, "Unable to get lock on connection pool, error message [{}]", e ); return Ok(resp); } }; let pool = locked_pool.deref(); let conn = match pool.rw_pool.get() { Ok(x) => x, Err(e) => { error!( logger, "Unable to get connection from pool, error message [{}]", e ); return Ok(resp); } }; let stmt = match conn.prepare(&query) { Ok(x) => x, Err(e) => { error!(logger, "Unable to prepare statement, error message [{}]", e); return Ok(resp); } }; let rows = match stmt.query(&[&"admin".to_string()]) { Ok(x) => x, Err(e) => { error!(logger, "Unable to execute query, error message [{}]", e); return Ok(resp); } }; if rows.is_empty() { info!(logger, "No data was found matching requested critera"); } else { for row in rows.iter() { #[derive(Debug, Serialize, Deserialize)] struct CustomerLocalAuth { pub customer_id_uuid: uuid::Uuid, pub password_hash: String, } let c: CustomerLocalAuth = CustomerLocalAuth { customer_id_uuid: row.get("customer_id_uuid"), password_hash: row.get("password_hash"), }; info!(logger, "c [{:?}]", c); if let Ok(res) = bcrypt::verify(&authuser.password, &c.password_hash) { info!(logger, "res [{:?}]", res); if res == true { resp = Response::with(status::Ok); } } break; // we only need first element } } //let ref rbody = req.body; //info!(logger, "line #{}", rbody); resp.headers.set(resp_content_type); Ok(resp) } pub fn upload_file(req: &mut Request) -> IronResult<Response> { let mut resp = Response::with(status::BadRequest); let logger: slog::Logger = get_logger!(req); /* // params, as it is iron related let params = match req.get_ref::<params::Params>() { Err(_) => { return Ok(resp); } Ok(x) => x, }; info!(logger, "parsed multipart/params data: {:?}", params); match params.find(&["f01", "name"]) { Some(&params::Value::String(ref name)) => { info!(logger, "data from f01 : {:?}", name); //let y = x as File; //info!(logger, "f01 {:?}", ); //info!(logger, "f01 {}", x.size); } _ => { return Ok(resp); } }; */ /* let form_data = match formdata::read_formdata(&mut req.body, &req.headers) { Ok(x) => x, Err(e) => { error!( logger, "unable to get files posted in request, error message {}", e ); return Ok(resp); } }; info!(logger, "read_data {:?}", form_data); for file in form_data.files { info!(logger, " file ::> {:?}", file); } */ /* let mut form_data = match Multipart::from_request(req) { Ok(x) => x, Err(_) => { info!(logger, "unable to get multipart"); return Ok(resp); } }; let fd = form_data.save().size_limit(1048576).with_dir( std::path::PathBuf::from("/saved/"), ); resp = match fd { SaveResult::Full(entries) => { info!(logger, "got full entries"); for (name, file) in entries.files { info!(logger, "entry: name {:?} files {:?}", name, file); let pth: std::path::PathBuf = file[0].path.clone(); let mut dpath: std::path::PathBuf = std::path::PathBuf::new(); if name == "f01" { dpath.push("/saved/"); dpath.push(name + ".jpg"); } else { continue; } let _ = std::fs::rename(&pth, &dpath); info!( logger, "file at path {} copied to {}", pth.to_string_lossy(), dpath.to_string_lossy() ); } Response::with((status::Ok)) } SaveResult::Partial(_, reason) => { error!(logger, "error fetching files, message {:?}", reason); Response::with((status::BadRequest)) } SaveResult::Error(_) => Response::with(status::BadRequest), }; */ /* */ let mut form_data = match Multipart::from_request(req) { Ok(x) => x, Err(_) => { info!(logger, "unable to get multipart"); return Ok(resp); } }; let multipart_field = match form_data.read_entry() { Ok(Some(x)) => x, _ => { return Ok(resp); } }; let fname = multipart_field.name; if let MultipartData::File(mut mfile) = multipart_field.data { let mut pdest = std::path::PathBuf::new(); if fname == "f01" { pdest.push("/saved/"); pdest.push(fname + ".jpg"); mfile.save().with_path(&pdest); info!(logger, "file saved to location {}", pdest.to_string_lossy()); resp.status = Some(status::Ok); } else { error!(logger, "unexpected file {}, discarding", fname); } } //info!(logger, "read_data {}", form_data); //resp.status = Some(status::Ok); // = Response::with((status::Ok)); Ok(resp) }
use std::cmp::PartialOrd; pub mod bubble_sort; pub mod quick_sort; pub mod selection_sort; pub mod insertion_sort; pub fn swap<T>(list: &mut [T], l_index: usize, r_index: usize) where T: PartialOrd + Copy, { let temp = list[r_index]; list[r_index] = list[l_index]; list[l_index] = temp } pub fn less<T>(a: T, b: T) -> bool where T: PartialOrd + Copy, { a < b } pub fn is_sorted<T>(list: &[T]) -> bool where T: PartialOrd + Copy, { for i in 1..list.len() { if list[i] < list[i - 1] { return false; } } return true; } #[cfg(test)] mod tests { use super::*; #[test] fn test_bubble_sort() { let mut list = [8, 100, 50, 22, 15, 6, 1, 1000, 999, 0]; // println!("test sort before -> {:?}", list); bubble_sort::sort(&mut list[..]); // println!("test sort after -> {:?}", list); assert_is_sorted(&list); } #[test] fn test_quick_sort() { // let mut list = [6, 1, 2, 7, 9, 3, 4, 5, 10, 8]; // println!("test sort before -> {:?}", list); let mut list = [6, 1]; quick_sort::sort(&mut list[..]); // println!("test sort after -> {:?}", list); assert_is_sorted(&list); } #[test] fn test_selection_sort() { let mut list = [6, 1, 2, 7, 9, 3, 4, 5, 10, 8]; // println!("test sort before -> {:?}", list); selection_sort::sort(&mut list[..]); // println!("test sort after -> {:?}", list); assert_is_sorted(&list); } #[test] fn test_insertion_sort() { let mut list = [6, 1, 2, 7, 9, 3, 4, 5, 10, 8]; // println!("test sort before -> {:?}", list); insertion_sort::sort(&mut list[..]); // println!("test sort after -> {:?}", list); assert_is_sorted(&list); } #[test] fn test_is_sorted() { let mut list = [6, 1, 2, 7, 9, 3, 4, 5, 10, 8]; quick_sort::sort(&mut list[..]); // println!("test list -> {:?}", list); // println!("test list is_sorted -> {}", is_sorted(&list)); } fn assert_is_sorted<T>(list: &[T]) where T: PartialOrd + Copy, { assert!(is_sorted(list), "list is not sorted"); } }
#![deny(warnings)] use hyper::client::conn::Builder; use hyper::client::connect::HttpConnector; use hyper::client::service::Connect; use hyper::service::Service; use hyper::{Body, Request}; #[tokio::main] async fn main() -> Result<(), Box<dyn std::error::Error>> { pretty_env_logger::init(); let mut mk_svc = Connect::new(HttpConnector::new(), Builder::new()); let uri = "http://127.0.0.1:8080".parse::<http::Uri>()?; let mut svc = mk_svc.call(uri.clone()).await?; let body = Body::empty(); let req = Request::get(uri).body(body)?; let res = svc.call(req).await?; println!("RESPONSE={:?}", res); Ok(()) }
use ndarray::prelude::*; use petgraph_drawing::{Drawing, DrawingIndex}; pub fn stress<N>(drawing: &Drawing<N, f32>, d: &Array2<f32>) -> f32 where N: DrawingIndex, { let n = drawing.len(); let mut s = 0.; for j in 1..n { for i in 0..j { let dx = drawing.coordinates[[i, 0]] - drawing.coordinates[[j, 0]]; let dy = drawing.coordinates[[i, 1]] - drawing.coordinates[[j, 1]]; let norm = (dx * dx + dy * dy).sqrt(); let dij = d[[i, j]]; let e = (norm - dij) / dij; s += e * e; } } s }
use std::str; pub struct IncomingResult<'a> { pub data: &'a [u8], } impl<'a> IncomingResult<'a> { pub fn begins_with(&self, name: &str) -> Option<&[u8]> { let len = name.len(); // Make sure name fits with the data if len > self.data.len() { return None; } for vals in self.data.iter().zip(name.as_bytes().iter()) { if vals.0 != vals.1 { return None; } } Some(&self.data[len..]) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_ok_string() { let res = IncomingResult { data: b"QTest123456" }; let t = res.begins_with("QTest").unwrap(); assert_eq!(t[0], b'1'); assert_eq!(t[1], b'2'); } #[test] fn test_too_long_in_string() { let res = IncomingResult { data: b"S10" }; assert_eq!(true, res.begins_with("TooLongString").is_none()); } #[test] fn test_same_length() { let res = IncomingResult { data: b"S10" }; assert_eq!(true, res.begins_with("S10").is_some()); } #[test] fn test_bad_data() { let res = IncomingResult { data: &[0,244,239] }; assert_eq!(true, res.begins_with("S").is_none()); } }
use rocket_contrib::databases::diesel; #[database("pg")] pub struct DbConnection(diesel::PgConnection);
use crate::structures::structure::*; use std::fs::File; use crate::structures::basic::*; #[derive(Debug, Default)] pub struct Module { types: Vec<FuncType>, funcs: Vec<String>, // FIXME tables: Vec<TableType>, mems: Vec<MemType>, globals: Vec<GlobalType>, elem: Vec<String>, // FIXME data: Vec<u8>, // FIXME start: bool, // FIXME imports: Vec<u8>, // FIXME exports: Vec<u8>, // FIXME } impl Module { pub fn load(path: File) -> Self { let m = Module::default(); } }
// This file is part of linux-epoll. It is subject to the license terms in the COPYRIGHT file found in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. No part of linux-epoll, including this file, may be copied, modified, propagated, or distributed except according to the terms contained in the COPYRIGHT file. // Copyright © 2019 The developers of linux-epoll. See the COPYRIGHT file in the top-level directory of this distribution and at https://raw.githubusercontent.com/lemonrock/linux-epoll/master/COPYRIGHT. use super::*; include!("bytes_label.rs"); include!("compressed_error.rs"); include!("guard_next_label_starts_at_pointer.rs"); include!("iterator_next_label.rs"); include!("parse_and_ignore_bytes_label.rs"); include!("parse_and_register_bytes_label.rs"); include!("parse_bytes_label.rs"); include!("parse_name.rs"); include!("Label.rs"); include!("LabelBitfield.rs"); include!("LabelBytes.rs"); include!("LabelKind.rs"); include!("LabelsRegister.rs"); include!("Name.rs"); include!("ParsedLabelInformation.rs"); include!("ParsedLabels.rs"); include!("UncompressedName.rs"); include!("UncompressedNameHeader.rs"); include!("UpTo63Bytes.rs"); include!("UpTo255Bytes.rs"); include!("WithoutCompressionParsedName.rs"); include!("WithCompressionParsedNameIterator.rs"); include!("WithoutCompressionParsedName.rs"); include!("WithoutCompressionParsedNameIterator.rs");
// Copyright 2022 Datafuse Labs. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. use std::alloc::Allocator; use std::iter::TrustedLen; use std::mem; use std::mem::MaybeUninit; use common_base::mem_allocator::MmapAllocator; use crate::table0::Entry; use crate::HashtableLike; pub struct LookupHashtable<K: Sized, const CAPACITY: usize, V, A: Allocator + Clone = MmapAllocator> { flags: Box<[bool; CAPACITY], A>, data: Box<[Entry<K, V>; CAPACITY], A>, len: usize, allocator: A, } pub struct LookupTableIter<'a, const CAPACITY: usize, K, V> { flags: &'a [bool; CAPACITY], slice: &'a [Entry<K, V>; CAPACITY], i: usize, } pub struct LookupTableIterMut<'a, const CAPACITY: usize, K, V> { flags: &'a [bool; CAPACITY], slice: &'a mut [Entry<K, V>; CAPACITY], i: usize, } impl<'a, const CAPACITY: usize, K: Sized, V> LookupTableIter<'a, CAPACITY, K, V> { pub fn create(flags: &'a [bool; CAPACITY], slice: &'a [Entry<K, V>; CAPACITY]) -> Self { LookupTableIter::<'a, CAPACITY, K, V> { i: 0, flags, slice } } } impl<'a, const CAPACITY: usize, K: Sized, V> LookupTableIterMut<'a, CAPACITY, K, V> { pub fn create(flags: &'a [bool; CAPACITY], slice: &'a mut [Entry<K, V>; CAPACITY]) -> Self { LookupTableIterMut::<'a, CAPACITY, K, V> { i: 0, flags, slice } } } impl<K: Sized, const CAPACITY: usize, V, A: Allocator + Clone> LookupHashtable<K, CAPACITY, V, A> { pub fn create(allocator: A) -> LookupHashtable<K, CAPACITY, V, A> { unsafe { LookupHashtable::<K, CAPACITY, V, A> { flags: Box::<[bool; CAPACITY], A>::new_zeroed_in(allocator.clone()).assume_init(), data: Box::<[Entry<K, V>; CAPACITY], A>::new_zeroed_in(allocator.clone()) .assume_init(), len: 0, allocator, } } } } macro_rules! lookup_impl { ($ty:ident, $capacity:expr) => { impl<V, A: Allocator + Clone> HashtableLike for LookupHashtable<$ty, $capacity, V, A> { type Key = $ty; type Value = V; type EntryRef<'a> = &'a Entry<$ty, V> where Self: 'a, Self::Key: 'a, Self::Value: 'a; type EntryMutRef<'a> = &'a mut Entry<$ty, V> where Self: 'a, Self::Key:'a, Self::Value: 'a; type Iterator<'a> = LookupTableIter<'a, $capacity, $ty, V> where Self: 'a, Self::Key: 'a, Self::Value: 'a; type IteratorMut<'a> = LookupTableIterMut<'a, $capacity, $ty, V> where Self: 'a, Self::Key: 'a, Self::Value: 'a; fn len(&self) -> usize { self.len } fn bytes_len(&self) -> usize { mem::size_of::<MaybeUninit<[bool; $capacity]>>() + mem::size_of::<MaybeUninit<[Entry<$ty, V>; $capacity]>>() + mem::size_of::<Self>() } fn entry(&self, key: &$ty) -> Option<Self::EntryRef<'_>> { match self.flags[*key as usize] { true => Some(&self.data[*key as usize]), false => None, } } fn entry_mut(&mut self, key: &$ty) -> Option<Self::EntryMutRef<'_>> { match self.flags[*key as usize] { true => Some(&mut self.data[*key as usize]), false => None, } } fn get(&self, key: &$ty) -> Option<&Self::Value> { unsafe { self.entry(key).map(|e| e.val.assume_init_ref()) } } fn get_mut(&mut self, key: &$ty) -> Option<&mut Self::Value> { unsafe { self.entry_mut(key).map(|e| e.val.assume_init_mut()) } } unsafe fn insert(&mut self, key: &$ty) -> Result<&mut MaybeUninit<Self::Value>, &mut Self::Value> { match self.insert_and_entry(key) { Ok(e) => Ok(&mut e.val), Err(e) => Err(e.val.assume_init_mut()), } } unsafe fn insert_and_entry(&mut self, key: &$ty) -> Result<Self::EntryMutRef<'_>, Self::EntryMutRef<'_>> { match self.flags[*key as usize] { true => Err(&mut self.data[*key as usize]), false => { self.flags[*key as usize] = true; let e = &mut self.data[*key as usize]; self.len += 1; e.key.write(*key); Ok(e) } } } unsafe fn insert_and_entry_with_hash(&mut self, key: &$ty, _hash: u64) -> Result<Self::EntryMutRef<'_>, Self::EntryMutRef<'_>> { self.insert_and_entry(key) } fn iter(&self) -> Self::Iterator<'_> { LookupTableIter::create(&self.flags, &self.data) } fn clear(&mut self) { unsafe { self.len = 0; self.flags = Box::<[bool; $capacity], A>::new_zeroed_in(self.allocator.clone()).assume_init(); self.data = Box::<[Entry<$ty, V>; $capacity], A>::new_zeroed_in(self.allocator.clone()).assume_init(); } } } impl<'a, V> Iterator for LookupTableIter<'a, $capacity, $ty, V> { type Item = &'a Entry<$ty, V>; fn next(&mut self) -> Option<Self::Item> { while self.i < $capacity && !self.flags[self.i] { self.i += 1; } if self.i == $capacity { None } else { let res = unsafe { &*(self.slice.as_ptr().add(self.i)) }; self.i += 1; Some(res) } } fn size_hint(&self) -> (usize, Option<usize>) { let remaining = $capacity - self.i; (remaining, Some(remaining)) } } unsafe impl<'a, V> TrustedLen for LookupTableIter<'a, $capacity, $ty, V> {} impl<'a, V> Iterator for LookupTableIterMut<'a, $capacity, $ty, V> { type Item = &'a mut Entry<$ty, V>; fn next(&mut self) -> Option<Self::Item> { while self.i < $capacity && !self.flags[self.i] { self.i += 1; } if self.i == $capacity { None } else { let res = unsafe { &mut *(self.slice.as_ptr().add(self.i) as *mut _) }; self.i += 1; Some(res) } } } }; } lookup_impl!(u8, 256); lookup_impl!(u16, 65536);
// Find the Most Competitive Subsequence // https://leetcode.com/explore/challenge/card/january-leetcoding-challenge-2021/581/week-3-january-15th-january-21st/3611/ pub struct Solution; impl Solution { // Causes timeout #[cfg(disable)] pub fn most_competitive(mut nums: Vec<i32>, k: i32) -> Vec<i32> { let k = k as usize; let mut start = 0; while start < k { let mut it = nums[start..=nums.len() - k + start].iter().enumerate(); let first = it.next().unwrap(); let min_idx = it .fold( first, |(mi, m), (i, v)| { if v < m { (i, v) } else { (mi, m) } }, ) .0; nums.drain(start..start + min_idx); start += 1; } nums.drain(start..); nums } // 1st accepted (in-place) #[cfg(disable)] pub fn most_competitive(mut nums: Vec<i32>, k: i32) -> Vec<i32> { let k = k as usize; let mut start = 0; while nums.len() > k && start < nums.len() - 1 { if nums[start] > nums[start + 1] { nums.remove(start); if start > 0 { start -= 1; } } else { start += 1; } } nums.drain(k..); nums } // Faster #[cfg(disable)] pub fn most_competitive(nums: Vec<i32>, k: i32) -> Vec<i32> { let mut needed = k as usize; let mut left = nums.len(); let mut res = Vec::with_capacity(needed); for num in nums { while left > needed && res.last() > Some(&num) { res.pop(); needed += 1; } if needed > 0 { needed -= 1; res.push(num) } left -= 1; } res } // Better, but requires newer rust #[cfg(disable)] pub fn most_competitive(nums: Vec<i32>, k: i32) -> Vec<i32> { let mut needed = k as usize; let mut left = nums.len(); let mut res = Vec::with_capacity(needed); for num in nums { while left > needed && matches!(res.last(), Some(&last) if last > num) { res.pop(); needed += 1; } if needed > 0 { needed -= 1; res.push(num) } left -= 1; } res } pub fn most_competitive(nums: Vec<i32>, k: i32) -> Vec<i32> { let n = nums.len(); let k = k as usize; let mut arr = vec![]; let mut m = 0; for i in 0..n { while let Some(&top) = arr.last() { if top > nums[i] && k < n - m { m += 1; arr.pop(); } else { break; } } arr.push(nums[i]); } arr[0..k].to_vec() } } #[cfg(test)] mod tests { use super::*; fn check(src: Vec<i32>, k: i32, res: Vec<i32>) { assert_eq!(Solution::most_competitive(src, k), res); } #[test] fn example1() { check(vec![3, 5, 2, 6], 2, vec![2, 6]); } #[test] fn example2() { check(vec![2, 4, 3, 3, 5, 4, 9, 6], 4, vec![2, 3, 3, 4]); } #[test] fn test1() { check(vec![3, 2, 1], 3, vec![3, 2, 1]); } #[test] fn test2() { check( vec![71, 18, 52, 29, 55, 73, 24, 42, 66, 8, 80, 2], 3, vec![8, 80, 2], ); } #[test] fn test3() { let mut src = vec![1; 100_000]; *src.last_mut().unwrap() = 0; let mut res = vec![1; 5_000]; *res.last_mut().unwrap() = 0; check(src, 5_000, res); } }
#[cfg(feature = "serde")] mod serde; /// Handle to a value inside the BeachMap. #[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] pub struct ID<V = super::DefaultVersion> { pub(crate) index: usize, pub(crate) version: V, } impl<V: Default> ID<V> { /// Returns an [`ID`] that can be used as a dummy value. /// This [`ID`] can't access any value. /// /// [`ID`]: ID pub fn invalid() -> Self { ID { index: usize::MAX, version: V::default(), } } }
//============================================================================== // Notes //============================================================================== // config.rs //============================================================================== // Crates and Mods //============================================================================== use nrf52832_pac::{twi0, spi0, spim0, uart0}; //============================================================================== // Accelerometer //============================================================================== #[allow(dead_code)] pub const ACCEL_I2C_SDA_PIN: u8 = I2C_SDA_PIN; #[allow(dead_code)] pub const ACCEL_I2C_SCL_PIN: u8 = I2C_SCL_PIN; #[allow(dead_code)] pub const ACCEL_I2C_FREQUENCY: twi0::frequency::FREQUENCY_A = I2C_FREQUENCY; #[allow(dead_code)] pub const ACCEL_INT_PIN: u8 = 8; //============================================================================== // Battery //============================================================================== pub const ADC_RAM_BUFFER: u32 = 0x2000_FBF0; pub const ADC_RAM_BUFFER_LEN: usize = 8; pub const BATTERY_ADC_CHANNEL: u8 = 7; pub const BATTERY_ADC_PIN: u8 = 31; pub const CHARGER_CONNECTED_PIN: u8 = 12; //============================================================================== // DEBUG //============================================================================== //============================================================================== // Flash //============================================================================== // pub const FLASH_CS_PIN: u8 = 3; //============================================================================== // I2C //============================================================================== pub const I2C_SCL_PIN: u8 = 7; pub const I2C_SDA_PIN: u8 = 6; pub const I2C_FREQUENCY: twi0::frequency::FREQUENCY_A = twi0::frequency::FREQUENCY_A::K100; //============================================================================== // LCD //============================================================================== pub const LCD_BACKLIGHT_LOW: u8 = 14; pub const LCD_BACKLIGHT_MID: u8 = 22; pub const LCD_BACKLIGHT_HIGH: u8 = 23; pub const LCD_CS_PIN: u8 = 25; pub const LCD_DCX_PIN: u8 = 18; pub const LCD_RESET_PIN: u8 = 26; //============================================================================== // Push Button //============================================================================== pub const PUSH_BUTTON_IN_PIN: u8 = 13; pub const PUSH_BUTTON_OUT_PIN: u8 = 15; //============================================================================== // RTC //============================================================================== //============================================================================== // SPI //============================================================================== pub const SPI_CPHA: spi0::config::CPHA_A = spi0::config::CPHA_A::TRAILING; pub const SPI_CPOL: spi0::config::CPOL_A = spi0::config::CPOL_A::ACTIVELOW; pub const SPI_FREQUENCY: spi0::frequency::FREQUENCY_A = spi0::frequency::FREQUENCY_A::M8; pub const SPI_ORDER: spi0::config::ORDER_A = spi0::config::ORDER_A::MSBFIRST; pub const SPI_MOSI_PIN: u8 = 3; pub const SPI_MISO_PIN: u8 = 4; pub const SPI_SCLK_PIN: u8 = 2; //============================================================================== // SPI and SPIM //============================================================================== pub const SPIM_CPHA: spim0::config::CPHA_A = spim0::config::CPHA_A::TRAILING; pub const SPIM_CPOL: spim0::config::CPOL_A = spim0::config::CPOL_A::ACTIVELOW; pub const SPIM_FREQUENCY: spim0::frequency::FREQUENCY_A = spim0::frequency::FREQUENCY_A::M8; pub const SPIM_ORDER: spim0::config::ORDER_A = spim0::config::ORDER_A::MSBFIRST; pub const SPIM_DMA_MAX: u32 = 0x20010000; pub const SPIM_DMA_MIN: u32 = 0x20000000; pub const SPIM_DMA_RX_PTR: u32 = 0x2000FE00; pub const SPIM_DMA_TX_PTR_A: u32 = 0x2000FD00; pub const SPIM_DMA_TX_PTR_B: u32 = 0x2000FC00; pub const SPIM_DMA_SIZE: u32 = 256; //============================================================================== // Touch Sensor //============================================================================== pub const TOUCH_I2C_ADDRESS: u8 = 0x15; pub const TOUCH_INT_PIN: u8 = 28; pub const TOUCH_RESET_PIN: u8 = 10; //============================================================================== // Uart //============================================================================== #[allow(dead_code)] pub const UART_CTS_PIN: Option<u8> = Some(7); #[allow(dead_code)] pub const UART_RTS_PIN: Option<u8> = Some(5); #[allow(dead_code)] pub const UART_RX_PIN: u8 = 8; #[allow(dead_code)] pub const UART_TX_PIN: u8 = 6; #[allow(dead_code)] pub const UART_BAUD: uart0::baudrate::BAUDRATE_A = uart0::baudrate::BAUDRATE_A::BAUD115200; #[allow(dead_code)] pub const UART_PARITY: uart0::config::PARITY_A = uart0::config::PARITY_A::EXCLUDED; #[allow(dead_code)] pub const UART_ECHO: bool = true; #[allow(dead_code)] pub const UART_RX_BUFFER_LENGTH: usize = 32;